<?php

namespace PSSG_Sync_Sheet\Admin;

use PSSG_Sync_Sheet\App\Core\Admin_Base;
use PSSG_Sync_Sheet\App\Core\Base;
use PSSG_Sync_Sheet\App\Handle\Quick_Table;
use PSSG_Sync_Sheet\App\Http\Api as API_Request;
use PSSG_Sync_Sheet\App\Handle\Description_Handle;
use PSSG_Sync_Sheet\App\Handle\Localization_Handle;
use PSSG_Sync_Sheet\App\Handle\Sales_Handle;
use PSSG_Sync_Sheet\App\Handle\Thumbs_Handle;
use PSSG_Sync_Sheet\App\Handle\Api_Request_Handle as API_Handle;
use PSSG_Sync_Sheet\App\Handle\Sheet_Style_Handle;
use PSSG_Sync_Sheet\App\Http\Sheet;
use PSSG_Sync_Sheet\App\Http\Sheet_Style;
use PSSG_Sync_Sheet\Admin\Page_Loader;
use PSSG_Sync_Sheet\App\Service\Request_Log;
use PSSG_Sync_Sheet\App\Handle\Schedule_Sync_Handle;

class Admin_Loader extends Admin_Base
{
    /**
     * Option key for tracking if user has been notified about AppsScript update.
     * Bump the version suffix whenever a new update notice must be shown to
     * users who already dismissed a previous one.
     */
    const APPSCRIPT_UPDATE_NOTICE_KEY = 'pssg_appscript_update_notice_v2';

    public function __construct()
    {
        parent::__construct();
    }

    public function init()
    {
        // Auto-generate Access Key if not exists
        $this->maybe_generate_access_key();

        $sheet = new Sheet();
        $sheet->run();

        // Register sheet styling handler (applies formatting via batchUpdate
        // after the first page of products is synced to Google Sheets).
        Sheet_Style::init();

        API_Request::init();

        Description_Handle::init();
        Localization_Handle::init();
        Sheet_Style_Handle::init();
        Sales_Handle::init();
        Thumbs_Handle::init();

        //Need run() method, otherwise, it will not work
        API_Handle::init()->run();

        $page_loader = new Page_Loader();
        $page_loader->run();

        // Schedule Sync Handler
        Schedule_Sync_Handle::init()->run();


        //Plugin Page menu handle
        add_filter('plugin_action_links_' . $this->base_file, [$this, 'plugin_action_links']);

        //pssg_quick_table_update
        add_action('wp_ajax_pssg_quick_table_update', [$this, 'quick_table_update']);
        add_action('wp_ajax_noprev_pssg_quick_table_update', [$this, 'quick_table_update']);

        // Show AppsScript update notice for existing users
        add_action('admin_notices', [$this, 'show_appscript_update_notice']);
        add_action('wp_ajax_pssg_dismiss_appscript_notice', [$this, 'dismiss_appscript_notice']);

        // Add WooCommerce Products page buttons
        add_action('admin_head', [$this, 'add_woocommerce_products_buttons']);
        add_filter('page_title_action_links', [$this, 'page_title_action_links'], 10, 2);

        // Add admin bar menu
        add_action('admin_bar_menu', [$this, 'add_admin_bar_menu'], 100);
    }

    public function plugin_action_links($links)
    {
        $my_links = [];
        $setting_link = admin_url('admin.php?page=' . $this->main_slug);
        $my_links[] =  '<a href="' . esc_url($setting_link) . '" title="' . esc_attr__('Settings', 'product-sync-master-sheet') . '" target="_blank">' . esc_html__('Settings', 'product-sync-master-sheet') . '</a>';
        return array_merge($my_links, $links);
    }

    public function page_title_action_links($actions, $post_type)
    {
        $actions['import_posts'] = array(
            'url'   => admin_url('admin.php?page=import-posts'),
            'label' => __('Saiful', 'textdomain'),
        );
        return $actions;
    }

    /**
     * Add "Your Google Sheet" and "Sync with Sheet" buttons to WooCommerce Products page
     *
     * @return void
     */
    public function add_woocommerce_products_buttons()
    {
        $screen = get_current_screen();
        if (!$screen || $screen->id !== 'edit-product') {
            return;
        }

        $sheet_url = $this->settings['sheet_url'] ?? '';

        // Validate that the URL is a Google Sheets URL
        $is_valid_sheet_url = !empty($sheet_url) &&
            filter_var($sheet_url, FILTER_VALIDATE_URL) &&
            strpos($sheet_url, 'docs.google.com/spreadsheets') !== false;

        $setup_complete = $this->is_setup_complete();

        $sync_page_url = admin_url('admin.php?page=' . $this->main_slug);

        // Button labels based on setup status
        if ($setup_complete) {
            $sync_button_text = __('Sync with Sheet', 'product-sync-master-sheet');
        } else {
            $sync_button_text = __('Sync Master Sheet - Setup', 'product-sync-master-sheet');
        }

?>
        <style>
            a.pssg-wc-buttons.page-title-action .dashicons {
                display: inline-block;
                margin-top: 4px;
                margin-right: 5px;
            }
        </style>
        <script>
            jQuery(document).ready(function($) {
                var buttonsHtml = '';
                <?php if ($is_valid_sheet_url) : ?>
                    buttonsHtml += '<a href="<?php echo esc_url($sheet_url); ?>" target="_blank" class="pssg-wc-buttons page-title-action" title="<?php echo esc_attr__('Open your Google Sheet', 'product-sync-master-sheet'); ?>"><span class="dashicons dashicons-media-spreadsheet"></span><?php echo esc_html__('Google Sheet', 'product-sync-master-sheet'); ?></a>';
                <?php endif; ?>
                buttonsHtml += '<a href="<?php echo esc_url($sync_page_url); ?>" class="pssg-wc-buttons page-title-action" title="<?php echo esc_attr__('Go to Sync Master Sheet', 'product-sync-master-sheet'); ?>"><span class="dashicons dashicons-update"></span><?php echo esc_js($sync_button_text); ?></a>';
                buttonsHtml += '';

                $('.wrap .page-title-action').last().after(buttonsHtml);
            });
        </script>
    <?php
    }

    /**
     * Add Sync with Sheet link to admin bar
     *
     * @param WP_Admin_Bar $wp_admin_bar
     * @return void
     */
    public function add_admin_bar_menu($wp_admin_bar)
    {
        if (!current_user_can('manage_woocommerce')) {
            return;
        }

        $sync_page_url = admin_url('admin.php?page=' . $this->main_slug);

        $wp_admin_bar->add_node([
            'id'    => 'pssg-sync-sheet',
            'title' => '<span class="ab-icon dashicons dashicons-update" style="margin-right: 5px;"></span>' . __('Sync Master Sheet', 'product-sync-master-sheet'),
            'href'  => $sync_page_url,
            'meta'  => [
                'title' => __('Go to Sync Master Sheet', 'product-sync-master-sheet'),
            ],
        ]);
    }

    /**
     * Check if setup wizard is complete
     *
     * @return bool
     */
    private function is_setup_complete()
    {
        $saved_data = $this->settings ?? [];

        $required_fields = ['sheet_url', 'spreadsheet_id', 'sheet_name'];
        foreach ($required_fields as $field) {
            if (empty($saved_data[$field])) {
                return false;
            }
        }

        // Check if service file is configured
        // $service_data = get_option('pssg_service_json_data', []);
        // if (empty($service_data['client_email'])) {
        //     return false;
        // }

        return true;
    }

    public function quick_table_update()
    {
        $nonce = sanitize_text_field(wp_unslash($_POST['nonce'] ?? ''));
        if (empty($nonce) || ! wp_verify_nonce($nonce, plugin_basename(PSSG_BASE_FILE))) {
            echo wp_json_encode(['status' => 'failed', 'message' => '', 'error' => __('Nonce not founded', 'product-sync-master-sheet')]);
            wp_die();
        }

        $params = [];

        if (is_array($_POST['params'])) {
            foreach ($_POST['params'] as $param_key => $param_value) {
                $params[$param_key] = sanitize_text_field($param_value);
            }
        }

        if (empty($params)) { //Fully sanitized(all key and value) above inside foreach using sanitize_text_field
            echo wp_json_encode(['status' => 'failed', 'message' => '', 'error' => __('Params empty or somethig went wrong', 'product-sync-master-sheet')]);
            wp_die();
        }


        $quickTable = Quick_Table::init();
        $response = $quickTable->single_product_update($params);

        echo wp_json_encode($response);
        wp_die();
    }

    /**
     * Auto-generate Access Key if not exists
     * This ensures Access Key is always available for AppsScript
     *
     * @return void
     */
    private function maybe_generate_access_key()
    {
        if (!Request_Log::has_access_key()) {
            Request_Log::generate_access_key();
        }
    }

    /**
     * Show notice for existing users about AppsScript update
     * This detects users who had the plugin before the security update
     * 
     * Detection logic: If user has sheet configured but notice not dismissed,
     * they are likely an existing user who needs to update AppsScript.
     *
     * @return void
     */
    public function show_appscript_update_notice()
    {
        // Only show on admin pages
        if (!is_admin()) {
            return;
        }
        global $current_screen;
        
        $_id = $current_screen->id ?? '';
        $rand = wp_rand(1, 10);

        if ( ! str_contains( $_id, 'pssg' ) && $rand !== 1  ) {
            return;
        }

        // Check if notice was already dismissed
        if (get_option(self::APPSCRIPT_UPDATE_NOTICE_KEY, false)) {
            return;
        }


        // Only show to users who appear to be existing users
        $current_screen = get_current_screen();
        if (!$current_screen) {
            return;
        }

    ?>  
        <div class="notice notice-warning is-dismissible pssg-appscript-update-notice" data-nonce="<?php echo esc_attr(wp_create_nonce('pssg_dismiss_notice')); ?>">
            <h3 style="margin-top: 10px;">
                <span class="dashicons dashicons-update" style="color: #dba617;"></span>
                <?php echo esc_html__('Sync Master Sheet — AppsScript Code Updated', 'product-sync-master-sheet'); ?>
            </h3>
            <p>
                <?php echo esc_html__('The AppsScript code used to connect your Google Sheet has been updated. To ensure everything works correctly, please copy the latest AppsScript and replace the old one in your Google Sheet.', 'product-sync-master-sheet'); ?>
            </p>
            <p><strong><?php echo esc_html__('Steps to update:', 'product-sync-master-sheet'); ?></strong></p>
            <ol style="margin-left: 20px;">
                <li><?php echo esc_html__('Go to the plugin\'s main page and click the "Copy AppsScript" button.', 'product-sync-master-sheet'); ?></li>
                <li><?php echo esc_html__('Open your Google Sheet → Extensions → Apps Script.', 'product-sync-master-sheet'); ?></li>
                <li><?php echo esc_html__('Delete the old script, paste the new one, and click Save.', 'product-sync-master-sheet'); ?></li>
            </ol>
            <p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=' . $this->main_slug)); ?>" class="button button-primary">
                    <?php echo esc_html__('Go to Plugin — Copy AppsScript', 'product-sync-master-sheet'); ?>
                </a>
                <button type="button" class="button pssg-dismiss-notice" style="margin-left: 10px;">
                    <?php echo esc_html__('Dismiss', 'product-sync-master-sheet'); ?>
                </button>
            </p>
        </div>
        <script>
            jQuery(document).ready(function($) {
                $('.pssg-appscript-update-notice').on('click', '.pssg-dismiss-notice, .notice-dismiss', function(e) {
                    var $notice = $(this).closest('.pssg-appscript-update-notice');
                    var nonce = $notice.data('nonce');
                    $.post(ajaxurl, {
                        action: 'pssg_dismiss_appscript_notice',
                        nonce: nonce
                    });
                    $notice.fadeOut();
                });
            });
        </script>
<?php
    }

    /**
     * AJAX handler to dismiss the AppsScript update notice
     *
     * @return void
     */
    public function dismiss_appscript_notice()
    {
        check_ajax_referer('pssg_dismiss_notice', 'nonce');
        update_option(self::APPSCRIPT_UPDATE_NOTICE_KEY, true);
        wp_send_json_success();
    }
}
