<?php

namespace Unlockafe_addons\Classes;

use Unlockafe_addons\Classes\Sync_Advantage_Core;

use function __;
use function add_action;
use function add_query_arg;
use function add_settings_field;
use function add_settings_section;
use function add_submenu_page;
use function admin_url;
use function do_settings_sections;
use function esc_attr;
use function esc_html;
use function esc_html__;
use function esc_url;
use function get_option;
use function http_build_query;
use function is_null;
use function is_wp_error;
use function json_decode;
use function sanitize_text_field;
use function settings_fields;
use function submit_button;
use function time;
use function update_option;
use function wp_create_nonce;
use function wp_die;
use function wp_enqueue_script;
use function wp_enqueue_style;
use function wp_localize_script;
use function wp_nonce_field;
use function wp_nonce_url;
use function wp_parse_args;
use function wp_redirect;
use function wp_remote_post;
use function wp_remote_retrieve_body;
use function wp_verify_nonce;

if (!defined('ABSPATH')) exit; // Exit if accessed directly

class Sync_Advantage_Settings {

    private static $_instance = null;
    private $option_name = 'unlockafe_sync_advantage_options';

    public static function instance() {
        if (is_null(self::$_instance)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    private function __construct() {
        // CHANGE: We now only register the fields for display, not the setting itself.
        add_action('admin_init', [$this, 'register_settings_fields']);
        add_action('admin_menu', [$this, 'add_admin_menu']);
        add_action('admin_init', [$this, 'handle_google_oauth_callback_action']);
        add_action('admin_action_unlockafe_google_disconnect', [$this, 'handle_google_disconnect_action']);
        add_action('admin_enqueue_scripts', [$this, 'admin_enqueue_scripts']);
    }

    public function admin_enqueue_scripts($hook) {
        if ('woocommerce_page_unlockafe-sync-advantage-settings' !== $hook) {
            return;
        }
        wp_enqueue_script('unlockafe-sync-advantage-settings', UNLOCKAFE_ASSETS . 'admin/js/sync-advantage-settings.js', ['jquery'], UNLOCKAFE_VERSION, true);
        $options = get_option($this->option_name);
        wp_localize_script('unlockafe-sync-advantage-settings', 'syncAdvantageSettings', [
            'ajax_url'      => admin_url('admin-ajax.php'),
            'nonce'         => wp_create_nonce('sync_advantage_ajax_nonce'),
            'google_sheet_id' => $options['google_sheet_id'] ?? '',
        ]);
    }

    public function add_admin_menu() {
        add_submenu_page('woocommerce', __('Sync Advantage Settings', 'unlock-addons-for-elementor'), __('Sync Advantage', 'unlock-addons-for-elementor'), 'manage_woocommerce', 'unlockafe-sync-advantage-settings', [$this, 'render_settings_page']);
    }

    // CHANGE: This function no longer uses register_setting(). It only sets up the sections and fields for display.
    public function register_settings_fields() {
        add_settings_section('google_connection_status', __('Connection Status', 'unlock-addons-for-elementor'), [$this, 'render_connection_status_section'], 'unlockafe-sync-advantage-settings');
        add_settings_section('unlockafe_sync_advantage_main_section', __('Sync Advantage Settings', 'unlock-addons-for-elementor'), [$this, 'render_section_text'], 'unlockafe-sync-advantage-settings');
        add_settings_field('google_client_id', __('Google Client ID', 'unlock-addons-for-elementor'), [$this, 'render_text_field'], 'unlockafe-sync-advantage-settings', 'unlockafe_sync_advantage_main_section', ['id' => 'google_client_id']);
        add_settings_field('google_client_secret', __('Google Client Secret', 'unlock-addons-for-elementor'), [$this, 'render_text_field'], 'unlockafe-sync-advantage-settings', 'unlockafe_sync_advantage_main_section', ['id' => 'google_client_secret', 'type' => 'password']);
        add_settings_field('enable_background_sync', __('Enable Automatic Sync', 'unlock-addons-for-elementor'), [$this, 'render_checkbox_field'], 'unlockafe-sync-advantage-settings', 'unlockafe_sync_advantage_main_section', ['name' => 'enable_background_sync', 'label' => __('Enable background sync from Google Sheets to WooCommerce every 15 minutes.', 'unlock-addons-for-elementor')]);
        add_settings_field('google_sheet_id', __('Google Sheet ID', 'unlock-addons-for-elementor'), [$this, 'render_text_field'], 'unlockafe-sync-advantage-settings', 'unlockafe_sync_advantage_main_section', ['id' => 'google_sheet_id', 'desc' => __('The ID of the Google Sheet to sync with.', 'unlock-addons-for-elementor')]);
        add_settings_field('webhook_url', __('Webhook URL', 'unlock-addons-for-elementor'), [$this, 'render_text_field'], 'unlockafe-sync-advantage-settings', 'unlockafe_sync_advantage_main_section', ['id' => 'webhook_url', 'desc' => __('The URL of the webhook.', 'unlock-addons-for-elementor')]);
    }

    public function handle_google_oauth_callback_action() {
        if (isset($_GET['action']) && $_GET['action'] === 'google_oauth_callback' && isset($_GET['code'])) {
            if (!isset($_GET['state']) || !wp_verify_nonce($_GET['state'], 'google_oauth_state')) {
                wp_die(__('Invalid state or nonce. Please try again.', 'unlock-addons-for-elementor'));
            }
            $this->handle_oauth_callback(sanitize_text_field($_GET['code']));
        }
    }

    public function handle_google_disconnect_action() {
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'google_disconnect_nonce')) {
            wp_die(__('Security check failed. Please try again.', 'unlock-addons-for-elementor'));
        }
        $this->disconnect_google();
    }

    public function render_checkbox_field($args) {
        $options = get_option($this->option_name);
        $name = $args['name'];
        $label = $args['label'];
        $checked = isset($options[$name]) && $options[$name] === '1' ? 'checked' : '';
        ?>
        <input type="checkbox" id="<?php echo esc_attr($name); ?>" name="<?php echo esc_attr($this->option_name . '[' . $name . ']'); ?>" value="1" <?php echo $checked; ?>/>
        <label for="<?php echo esc_attr($name); ?>"><?php echo esc_html($label); ?></label>
        <?php
    }

    public function render_connection_status_section() {
        $options = get_option($this->option_name);
        $is_connected = !empty($options['google_access_token']);

        if ($is_connected) {
            echo '<p style="color: green; font-weight: bold;">' . esc_html__('Status: Connected to Google.', 'unlock-addons-for-elementor') . '</p>';
            $disconnect_url = add_query_arg(['action' => 'unlockafe_google_disconnect'], admin_url('admin.php'));
            echo '<a href="' . esc_url(wp_nonce_url($disconnect_url, 'google_disconnect_nonce')) . '" class="button">' . esc_html__('Disconnect from Google', 'unlock-addons-for-elementor') . '</a>';
            echo '&nbsp;<button id="sync-all-orders" class="button-primary">' . esc_html__('Sync All Orders', 'unlock-addons-for-elementor') . '</button>';
            echo '<div id="sync-status-message" style="margin-top: 10px;"></div>';
        } else {
            echo '<p style="color: red; font-weight: bold;">' . esc_html__('Status: Not connected to Google.', 'unlock-addons-for-elementor') . '</p>';
            if (empty($options['google_client_id']) || empty($options['google_client_secret'])) {
                echo '<p>' . esc_html__('Please enter and save your Google Client ID and Client Secret to begin.', 'unlock-addons-for-elementor') . '</p>';
            } else {
                echo '<a href="' . esc_url($this->get_google_auth_url()) . '" class="button-primary">' . esc_html__('Connect to Google', 'unlock-addons-for-elementor') . '</a>';
            }
        }
    }

    public function render_section_text() {
        echo '<p>' . esc_html__('Enter your Google API credentials. You can get these from the Google Cloud Console.', 'unlock-addons-for-elementor') . '</p>';
    }

    public function render_text_field($args) {
        $options = get_option($this->option_name);
        $id = $args['id'];
        $type = isset($args['type']) ? $args['type'] : 'text';
        $value = isset($options[$id]) ? $options[$id] : '';
        echo '<input type="' . esc_attr($type) . '" id="' . esc_attr($id) . '" name="' . esc_attr($this->option_name) . '[' . esc_attr($id) . ']" value="' . esc_attr($value) . '" class="regular-text">';
        if (!empty($args['desc'])) {
            echo '<p class="description">' . esc_html($args['desc']) . '</p>';
        }
    }

    private function get_google_auth_url() {
        $options = get_option($this->option_name);
        $client_id = $options['google_client_id'] ?? '';
        if (empty($client_id)) return '#';
        $state = wp_create_nonce('google_oauth_state');
        $redirect_uri = admin_url('admin.php?page=unlockafe-sync-advantage-settings&action=google_oauth_callback', 'https');
        return 'https://accounts.google.com/o/oauth2/v2/auth?' . http_build_query([
            'client_id' => $client_id,
            'redirect_uri' => $redirect_uri,
            'response_type' => 'code',
            'scope' => 'https://www.googleapis.com/auth/spreadsheets',
            'access_type' => 'offline',
            'prompt' => 'consent',
            'state' => $state
        ]);
    }

    public function handle_oauth_callback($code) {
        $options = get_option($this->option_name);
        $client_id = $options['google_client_id'] ?? '';
        $client_secret = $options['google_client_secret'] ?? '';
        if (empty($client_id) || empty($client_secret)) {
            wp_die('Client ID or Secret is not set.');
        }
        $redirect_uri = admin_url('admin.php?page=unlockafe-sync-advantage-settings&action=google_oauth_callback', 'https');
        $response = wp_remote_post('https://oauth2.googleapis.com/token', [
            'body' => ['code' => $code, 'client_id' => $client_id, 'client_secret' => $client_secret, 'redirect_uri' => $redirect_uri, 'grant_type' => 'authorization_code']
        ]);

        if (is_wp_error($response)) {
            wp_die('Error fetching token: ' . $response->get_error_message());
        }

        $body = json_decode(wp_remote_retrieve_body($response), true);

        if (isset($body['access_token'])) {
            $this->save_google_token_data($body);
            wp_redirect(admin_url('admin.php?page=unlockafe-sync-advantage-settings&status=connected'));
            exit;
        } else {
            wp_die('Error getting access token: ' . ($body['error_description'] ?? 'Unknown error'));
        }
    }

    private function save_google_token_data($token_data) {
        $options = get_option($this->option_name, []);
        $options['google_access_token'] = $token_data['access_token'];
        if (isset($token_data['refresh_token'])) {
            $options['google_refresh_token'] = $token_data['refresh_token'];
        }
        $options['google_token_expires_in'] = time() + (int)$token_data['expires_in'];
        update_option($this->option_name, $options);
    }

    private function disconnect_google() {
        $options = get_option($this->option_name);
        unset($options['google_access_token'], $options['google_refresh_token'], $options['google_token_expires_in']);
        update_option($this->option_name, $options);
        wp_redirect(admin_url('admin.php?page=unlockafe-sync-advantage-settings&status=disconnected'));
        exit;
    }

    // NEW: This function handles the saving of the settings form manually.
    private function handle_form_submission() {
        if (!isset($_POST['submit']) || !isset($_POST['unlockafe_settings_nonce'])) {
            return;
        }

        if (!wp_verify_nonce($_POST['unlockafe_settings_nonce'], 'unlockafe_settings_update')) {
            wp_die('Nonce verification failed!');
        }

        $old_options = get_option($this->option_name, []);
        $posted_options = $_POST[$this->option_name] ?? [];

        $new_options = [];
        $new_options['google_client_id'] = isset($posted_options['google_client_id']) ? sanitize_text_field($posted_options['google_client_id']) : '';
        $new_options['google_client_secret'] = isset($posted_options['google_client_secret']) ? trim($posted_options['google_client_secret']) : '';
        $new_options['google_sheet_id'] = isset($posted_options['google_sheet_id']) ? sanitize_text_field($posted_options['google_sheet_id']) : '';
        $new_options['webhook_url'] = isset($posted_options['webhook_url']) ? esc_url_raw(trim($posted_options['webhook_url'])) : '';
        $new_options['enable_background_sync'] = isset($posted_options['enable_background_sync']) ? '1' : '0';

        $final_options = wp_parse_args($new_options, $old_options);

        update_option($this->option_name, $final_options);

        // Add a success notice that will be displayed on the page.
        add_action('admin_notices', function() {
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Settings saved.', 'unlock-addons-for-elementor') . '</p></div>';
        });
    }

    public function render_settings_page() {
        // CHANGE: Call the manual form handler before rendering the page.
        $this->handle_form_submission();
        ?>
        <div class="wrap">
            <h1><?php echo esc_html__('Sync Advantage for Google Sheets', 'unlock-addons-for-elementor'); ?></h1>
            <?php
            // This will display the "Settings saved" notice from our manual handler.
            do_action('admin_notices');

            if (!empty($_GET['status'])) {
                if ($_GET['status'] === 'connected') {
                    echo '<div class="notice notice-success is-dismissible" style="margin: 10px 0;"><p>' . esc_html__('Successfully connected to Google.', 'unlock-addons-for-elementor') . '</p></div>';
                } elseif ($_GET['status'] === 'disconnected') {
                    echo '<div class="notice notice-success is-dismissible" style="margin: 10px 0;"><p>' . esc_html__('Successfully disconnected from Google.', 'unlock-addons-for-elementor') . '</p></div>';
                }
            }
            ?>
            <div id="unlockafe-sync-message" class="notice" style="display:none; margin-top: 10px; padding: 10px;"></div>
            <p><?php echo esc_html__('Connect your WooCommerce store with Google Sheets. Manage settings for automatic and manual data synchronization.', 'unlock-addons-for-elementor'); ?></p>
            
            <!-- CHANGE: The form now posts to itself and uses a manual nonce field instead of settings_fields(). -->
            <form action="" method="post">
                <?php
                wp_nonce_field('unlockafe_settings_update', 'unlockafe_settings_nonce');
                do_settings_sections('unlockafe-sync-advantage-settings');
                submit_button();
                ?>
            </form>

            <div class="unlockafe-manual-sync-wrapper">
                <button type="button" id="unlockafe-manual-sync" class="button button-secondary"><?php echo esc_html__('Run Manual Sync', 'unlock-addons-for-elementor'); ?></button>
                <span class="spinner"></span>
                <p class="description"><?php echo esc_html__('Manually sync all order data between WooCommerce and Google Sheets. This will update statuses and create new orders in both directions.', 'unlock-addons-for-elementor'); ?></p>
            </div>
        </div>
        <?php
    }
}

Sync_Advantage_Settings::instance();
