<?php
if (!defined('ABSPATH')) exit;

/**
 * Admin-side settings page for Simple Amazon Affiliate
 */
class SAA_Admin {

    /** @var SAA_Plugin */
    private $plugin;

    public function __construct(SAA_Plugin $plugin) {
        $this->plugin = $plugin;
    }

    /**
     * Register hooks
     */
    public function init(): void {
        add_action('admin_menu', [$this, 'add_settings_page']);
        add_action('admin_init', [$this, 'register_settings']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
        add_action('wp_ajax_saa_test_api', [$this, 'ajax_test_api']);
    }

    /**
     * Add submenu under Settings
     */
    public function add_settings_page(): void {
        add_options_page(
            __('Simple Amazon Affiliate Settings', 'slurpywp-saa-lang'),
            __('Simple Amazon Affiliate', 'slurpywp-saa-lang'),
            'manage_options',
            'saa-settings',
            [$this, 'render_settings_page']
        );
    }

    /**
     * Register settings
     */
    public function register_settings(): void {
        register_setting('saa_options_group', 'saa_options', [$this, 'sanitize_options']);

        // Section 1: API credentials
        add_settings_section(
            'saa_api_section',
            __('Amazon Product Advertising API (PA API) Credentials (Optional)', 'slurpywp-saa-lang'),
            function() {
                echo '<p>' . esc_html__('Enter your API credentials to automatically pull product details from Amazon. If you don’t have a valid Amazon Associates account, leave these blank - you can still use this plugin by manually entering the product.', 'slurpywp-saa-lang') . '</p>';
				
				echo '<table class="form-table"><tr>
						<th></th>
						<td>
							<a href="https://affiliate-program.amazon.co.uk/help/node/topic/GTPNVFFUV2GQ8AZV" target="_blank">
								' . esc_html__('Need help finding your credentials?', 'slurpywp-saa-lang') . '
							</a>
						</td>
					  </tr></table>';
            },
            'saa-settings'
        );

        // Fields
        add_settings_field('associate_tag', __('Associate Tag', 'slurpywp-saa-lang'), [$this, 'field_text'], 'saa-settings', 'saa_api_section', ['id' => 'associate_tag']);
        add_settings_field('access_key', __('Access Key', 'slurpywp-saa-lang'), [$this, 'field_text'], 'saa-settings', 'saa_api_section', ['id' => 'access_key']);
        add_settings_field('secret_key', __('Secret Key', 'slurpywp-saa-lang'), [$this, 'field_password'], 'saa-settings', 'saa_api_section', ['id' => 'secret_key']);
        add_settings_field('region', __('Region', 'slurpywp-saa-lang'), [$this, 'field_region'], 'saa-settings', 'saa_api_section');

        // Section 2: Uninstall
        add_settings_section(
            'saa_uninstall_section',
            __('Uninstallation Settings', 'slurpywp-saa-lang'),
            '__return_false',
            'saa-settings'
        );

        add_settings_field(
            'delete_on_uninstall',
            __('Delete all data on uninstall', 'slurpywp-saa-lang'),
            [$this, 'field_checkbox'],
            'saa-settings',
            'saa_uninstall_section',
            ['id' => 'delete_on_uninstall', 'label' => __('Check this if you want all plugin data, including saved products, to be deleted on uninstall.', 'slurpywp-saa-lang')]
        );
    }

    /**
     * Field renderers
     */
    public function field_text($args): void {
        $id = $args['id'];
        $val = esc_attr($this->plugin->get_option($id, ''));
        echo '<input type="text" id="' . esc_attr($id) . '" name="saa_options[' . esc_attr($id) . ']" value="' . $val . '" class="regular-text">';
    }

    public function field_password($args): void {
        $id = $args['id'];
        $val = esc_attr($this->plugin->get_option($id, ''));
        echo '<input type="password" id="' . esc_attr($id) . '" name="saa_options[' . esc_attr($id) . ']" value="' . $val . '" class="regular-text">';
    }

	public function field_region(): void {
		$current = $this->plugin->get_option('region', '');
		$regions = [
			''   => __('(None)', 'slurpywp-saa-lang'),
			'UK' => 'amazon.co.uk',
			'US' => 'amazon.com',
			'CA' => 'amazon.ca',
			'DE' => 'amazon.de',
			'FR' => 'amazon.fr',
			'IT' => 'amazon.it',
			'ES' => 'amazon.es',
			'JP' => 'amazon.co.jp',
			'IN' => 'amazon.in',
		];
	
		echo '<select id="region" name="saa_options[region]">';
		foreach ($regions as $key => $label) {
			printf(
				'<option value="%s" %s>%s</option>',
				esc_attr($key),
				selected($current, $key, false),
				esc_html($label)
			);
		}
		echo '</select>';
	
		// Help text
		echo '<p class="description" style="margin-top:15px;">' .
			 esc_html__('To test your API credentials connection, first Save Changes, and then click Test Connection button.', 'slurpywp-saa-lang') .
			 '</p>';
	
		// Button
		echo '<p><button type="button" id="saa-test-api" class="button" style="margin-top:15px;margin-bottom:5px;">' .
			 esc_html__('Test Connection', 'slurpywp-saa-lang') .
			 '</button></p>';
	
		// Status message placeholder
		echo '<div id="saa-api-status" style="margin-top:6px;"></div>';
	}

    public function field_checkbox($args): void {
        $id = $args['id'];
        $label = $args['label'] ?? '';
        $val = $this->plugin->get_option($id, 0);
        echo '<label><input type="checkbox" id="' . esc_attr($id) . '" name="saa_options[' . esc_attr($id) . ']" value="1" ' . checked(1, $val, false) . '> ' . esc_html($label) . '</label>';
    }

    /**
     * Sanitize settings
     */
    public function sanitize_options($input): array {
        $clean = [];
        $clean['associate_tag'] = sanitize_text_field($input['associate_tag'] ?? '');
        $clean['access_key'] = sanitize_text_field($input['access_key'] ?? '');
        $clean['secret_key'] = sanitize_text_field($input['secret_key'] ?? '');
        $clean['region'] = sanitize_text_field($input['region'] ?? '');
        $clean['delete_on_uninstall'] = !empty($input['delete_on_uninstall']) ? 1 : 0;
        return $clean;
    }

    /**
     * Render settings page
     */
    public function render_settings_page(): void {
        ?>
        <div class="wrap saa-settings">
            <h1><?php esc_html_e('Simple Amazon Affiliate Settings', 'slurpywp-saa-lang'); ?></h1>
            <form method="post" action="options.php">
                <?php
                settings_fields('saa_options_group');
                do_settings_sections('saa-settings');
                submit_button();
                ?>
            </form>
        </div>
        <?php
    }

    /**
     * Enqueue CSS/JS
     */
    public function enqueue_assets($hook): void {
        if ($hook !== 'settings_page_saa-settings') {
            return;
        }

        wp_enqueue_style(
            'saa-admin',
            SAA_PLUGIN_URL . 'admin/css/admin.css',
            [],
            SAA_PLUGIN_VERSION
        );

        wp_enqueue_script(
            'saa-admin',
            SAA_PLUGIN_URL . 'admin/js/admin.js',
            ['jquery'],
            SAA_PLUGIN_VERSION,
            true
        );

        wp_localize_script('saa-admin', 'saaAdmin', [
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce'    => wp_create_nonce('saa_test_api'),
        ]);
    }

    /**
     * AJAX: Test API connection
     */
	public function ajax_test_api(): void {
		check_ajax_referer('saa_test_api', 'nonce');
	
		if (!$this->plugin->is_api_configured() || !$this->plugin->api()) {
			wp_send_json_error( __('API credentials are incomplete.', 'slurpywp-saa-lang') );
		}
	
		$result = $this->plugin->api()->test_connection();
	
		if (is_array($result)) {
			if ($result['success']) {
				wp_send_json_success( $result['message'] ); // message already translated upstream
			} else {
				wp_send_json_error( $result['message'] );
			}
		} else {
			// Legacy fallback if test_connection() ever returned bool
			if ($result) {
				wp_send_json_success( __('Connection successful!', 'slurpywp-saa-lang') );
			} else {
				wp_send_json_error( __('Connection failed. Please check your credentials.', 'slurpywp-saa-lang') );
			}
		}
	}
}
