<?php

/**
 * Plugin Name: Preciousuite Gold Buyback Quote Calculator
 * Description: A professional gold buyback calculator with a daily rate management system in the admin dashboard.
 * Version: 1.8
 * Author: Vimal Kava
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Text Domain: preciousuite-gold-buyback-quote-calculator
 */

if (!defined('ABSPATH'))
    exit;

define('PRECIOUSUITE_PATH', plugin_dir_path(__FILE__));
define('PRECIOUSUITE_URL', plugin_dir_url(__FILE__));

if (is_admin()) {
    require_once PRECIOUSUITE_PATH . 'includes/precioussuite/class-precioussuite-registry.php';
    require_once PRECIOUSUITE_PATH . 'includes/precioussuite/class-precioussuite-admin.php';

    PreciousSuite_Admin::init(array(
        'version' => '1.1.11',
        'base_path' => PRECIOUSUITE_PATH . 'includes/precioussuite/',
        'base_url' => PRECIOUSUITE_URL . 'includes/precioussuite/',
    ));

    add_action('init', 'preciousuite_pgbqcgold_register_precioussuite_module');
}

function preciousuite_pgbqcgold_register_precioussuite_module()
{
    precioussuite_register_module(array(
        'slug' => 'buyback-calculator',
        'name' => __('Buyback Calculator', 'preciousuite-gold-buyback-quote-calculator'),
        'label' => __('Buyback Calculator', 'preciousuite-gold-buyback-quote-calculator'),
        'description' => __('Generate customer gold buyback quotes with optional lead capture.', 'preciousuite-gold-buyback-quote-calculator'),
        'settings_url' => admin_url('admin.php?page=preciousuite-settings'),
        'plugin_file' => plugin_basename(__FILE__),
        'wporg_slug' => 'preciousuite-gold-buyback-quote-calculator',
        'position' => 30,
        'stats' => 'preciousuite_pgbqcgold_precioussuite_stats',
    ));
}

// Load Classes
require_once PRECIOUSUITE_PATH . 'includes/class-preciousuite-settings.php';
require_once PRECIOUSUITE_PATH . 'includes/class-preciousuite-quotes.php';
if (is_admin()) {
    require_once PRECIOUSUITE_PATH . 'includes/class-preciousuite-deactivator.php';
}

// Initialize Settings
if (is_admin()) {
    new PRECIOUSUITE_Settings();
}

add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'preciousuite_pgbqcgold_settings_link');

if (!function_exists('preciousuite_pgbqcgold_settings_link')) {
    function preciousuite_pgbqcgold_settings_link($links)
    {
        $settings_link = '<a href="admin.php?page=preciousuite-settings">' . __('Settings', 'preciousuite-gold-buyback-quote-calculator') . '</a>';
        array_unshift($links, $settings_link);
        return $links;
    }
}

add_filter('plugin_row_meta', 'preciousuite_plugin_row_meta', 10, 2);

function preciousuite_plugin_row_meta($links, $file)
{
    if ('preciousuite-gold-buyback-quote-calculator/preciousuite-gold-buyback-quote-calculator.php' == $file) {
        $row_meta = array(
            'docs' => '<a href="' . esc_url('https://www.preciousuite.com') . '" target="_blank" aria-label="' . esc_attr__('Plugin Additional Links', 'preciousuite-gold-buyback-quote-calculator') . '" style="color:green;">' . esc_html__('Documentation', 'preciousuite-gold-buyback-quote-calculator') . '</a>'
        );

        return array_merge($links, $row_meta);
    }
    return (array) $links;
}

if (false) {
    add_action('admin_notices', 'preciousuite_review_notice');
}

function preciousuite_review_notice()
{
    if (get_option('preciousuite_review_notice_dismissed')) {
        return;
    }

    if (!current_user_can('manage_options')) {
        return;
    }

    if (
        !get_option('preciousuite_activation_time') ||
        (time() - get_option('preciousuite_activation_time')) < 2 * DAY_IN_SECONDS
    ) {
        return;
    }

    $review_url = 'https://wordpress.org/support/plugin/preciousuite-gold-buyback-quote-calculator/reviews/#new-post';

    $website_url = 'https://preciousuite.com/';

    $dismiss_url = wp_nonce_url(
        add_query_arg('preciousuite_dismiss_review', '1'),
        'preciousuite_dismiss_nonce'
    );
?>

    <div class="notice notice-info"
        style="padding:16px 20px; display:flex; align-items:flex-start; gap:16px; border-left-color:#d4af37;">

        <div style="font-size:36px;">⭐</div>

        <div style="flex:1;">

            <p style="margin:0 0 6px 0; font-weight:600;">
                Hey, I noticed you've been using Preciousuite Gold Buyback Quote Calculator for the past few days — that's
                awesome!
            </p>

            <p style="margin:0 0 12px 0; color:#50575e;">
                If you’re enjoying the plugin, please consider leaving a review on WordPress.
                Your feedback helps improve the plugin and supports future updates.
            </p>

            <div style="display:flex; flex-wrap:wrap; gap:10px; align-items:center;">

                <a href="<?php echo esc_url($review_url); ?>" target="_blank" class="button button-primary"
                    style="background:#d4af37; border-color:#b8962e; color:#fff;">

                    Leave a Review
                </a>

                <a href="<?php echo esc_url($dismiss_url); ?>" style="color:#50575e; font-size:13px;">
                    I already did
                </a>

                <a href="<?php echo esc_url($dismiss_url); ?>" style="color:#50575e; font-size:13px;">
                    Maybe later
                </a>

                <a href="<?php echo esc_url($website_url); ?>" target="_blank" style="font-size:13px; color:#2271b1;">

                    🌐 Visit our website
                </a>

            </div>

        </div>

        <a href="<?php echo esc_url($dismiss_url); ?>" style="color:#50575e; font-size:18px; text-decoration:none;">
            ✕
        </a>

    </div>

<?php
}

add_action('admin_init', 'preciousuite_handle_review_dismiss');

function preciousuite_handle_review_dismiss()
{
    if (
        isset($_GET['preciousuite_dismiss_review']) &&
        isset($_GET['_wpnonce']) &&
        wp_verify_nonce(
            sanitize_text_field(wp_unslash($_GET['_wpnonce'])),
            'preciousuite_dismiss_nonce'
        ) &&
        current_user_can('manage_options')
    ) {

        update_option('preciousuite_review_notice_dismissed', true);

        wp_safe_redirect(
            remove_query_arg(array(
                'preciousuite_dismiss_review',
                '_wpnonce'
            ))
        );

        exit;
    }
}

/**
 * Enqueue Admin Assets
 */
add_action('admin_enqueue_scripts', 'preciousuite_pgbqcgold_admin_enqueue_assets');
function preciousuite_pgbqcgold_admin_enqueue_assets($hook)
{
    if ($hook === 'plugins.php') {
        wp_enqueue_script('jquery-ui-dialog');
        wp_enqueue_script('jquery-ui-button');
        wp_enqueue_script('jquery-ui-draggable');
        wp_enqueue_script('jquery-ui-resizable');
        wp_enqueue_script('jquery-ui-widget');
        wp_enqueue_script('jquery-ui-core');
        wp_enqueue_style('wp-jquery-ui-dialog');
    }

    $allowed_hooks = array(
        'preciousuite_page_preciousuite-settings',
        'preciousuite_page_preciousuite-quotes',
    );

    if (!in_array($hook, $allowed_hooks)) {
        return;
    }

    wp_enqueue_style('preciousuite-admin-style', PRECIOUSUITE_URL . 'assets/css/admin-style.css', array(), '1.2.0');
    wp_enqueue_style('preciousuite-responsive', PRECIOUSUITE_URL . 'assets/css/responsive.css', array(), '1.2.0');
}


/**
 * Enqueue Assets
 */
add_action('wp_enqueue_scripts', 'preciousuite_enqueue_assets');
function preciousuite_enqueue_assets()
{
    wp_enqueue_style('preciousuite-style', PRECIOUSUITE_URL . 'assets/css/style.css', array(), '1.2.0');
    wp_enqueue_style('preciousuite-responsive', PRECIOUSUITE_URL . 'assets/css/responsive.css', array(), '1.2.0');
    wp_enqueue_script('preciousuite-script', PRECIOUSUITE_URL . 'assets/js/calculator.js', array('jquery'), '1.2.0', true);

    // Fetch values from settings (Default values if not set)
    $manual_rate = get_option('preciousuite_manual_gold_rate', '75.00');
    $margin = get_option('preciousuite_buyback_margin', '95');
    $currency = get_option('preciousuite_currency', '$');

    wp_localize_script('preciousuite-script', 'preciousuite_data', array(
        'live_price' => floatval($manual_rate),
        'buyback_percentage' => floatval($margin) / 100,
        'currency' => $currency,
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('preciousuite_lead_nonce'),
        'enable_lead_capture' => get_option('preciousuite_enable_lead_capture', '1'),
        'whatsapp_enable' => get_option('preciousuite_whatsapp_enable', '0'),
        'whatsapp_number' => preg_replace('/[^0-9]/', '', get_option('preciousuite_whatsapp_number', ''))
    ));
}

/**
 * Enqueue Admin Assets
 */
add_action('admin_enqueue_scripts', 'preciousuite_admin_enqueue_assets');
function preciousuite_admin_enqueue_assets($hook)
{
    // Only load on our settings page
    $allowed_hooks = array(
        'preciousuite_page_preciousuite-settings',
        'preciousuite_page_preciousuite-quotes',
    );

    if (!in_array($hook, $allowed_hooks)) {
        return;
    }

    wp_enqueue_style('preciousuite-admin-style', PRECIOUSUITE_URL . 'assets/css/admin-style.css', array(), '1.2.0');
}

/**
 * Register Shortcode [preciousuite_calculator]
 */
add_shortcode('preciousuite_calculator', 'preciousuite_render_calculator');
function preciousuite_render_calculator()
{
    ob_start();
    include PRECIOUSUITE_PATH . 'templates/calculator-form.php';
    return ob_get_clean();
}

/**
 * Handle Lead Submission via AJAX
 */
add_action('wp_ajax_preciousuite_submit_lead', 'preciousuite_handle_lead_submission');
add_action('wp_ajax_nopriv_preciousuite_submit_lead', 'preciousuite_handle_lead_submission');
function preciousuite_handle_lead_submission()
{
    check_ajax_referer('preciousuite_lead_nonce', 'nonce');

    $email = isset($_POST['email']) ? sanitize_email(wp_unslash($_POST['email'])) : '';
    $weight = isset($_POST['weight']) ? sanitize_text_field(wp_unslash($_POST['weight'])) : '';
    $karat = isset($_POST['karat']) ? sanitize_text_field(wp_unslash($_POST['karat'])) : '';
    $price = isset($_POST['price']) ? sanitize_text_field(wp_unslash($_POST['price'])) : '';

    if (!is_email($email)) {
        wp_send_json_error(array('message' => 'Invalid email address.'));
    }

    // 1. Generate Unique ID
    $unique_id = 'PS-' . strtoupper(substr(uniqid(), -6));

    // 2. Save explicitly to Database
    $post_id = wp_insert_post(array(
        'post_title' => $unique_id,
        'post_type' => 'preciousuite_quote',
        'post_status' => 'publish'
    ));

    if ($post_id) {
        update_post_meta($post_id, '_preciousuite_email', $email);
        update_post_meta($post_id, '_preciousuite_weight', $weight);
        update_post_meta($post_id, '_preciousuite_karat', $karat);
        update_post_meta($post_id, '_preciousuite_price', $price);
    }

    // WhatsApp URL Generation
    $whatsapp_url = '';
    if (get_option('preciousuite_whatsapp_enable') && !empty(get_option('preciousuite_whatsapp_number'))) {
        $whatsapp_number = preg_replace('/[^0-9]/', '', get_option('preciousuite_whatsapp_number'));

        $wa_text = "Hello! I just locked in a Gold Buyback Quote on your website.\n\n";
        $wa_text .= "- *Quote ID:* " . $unique_id . "\n";
        $wa_text .= "- *Weight:* " . $weight . "g\n";
        $wa_text .= "- *Purity:* " . $karat . "\n";
        $wa_text .= "- *Locked Price:* " . $price . "\n\n";
        $wa_text .= "Let me know when I can come to the shop to finalize!";

        $whatsapp_url = 'https://wa.me/' . $whatsapp_number . '?text=' . rawurlencode($wa_text);
    }

    // 3. Compose Professional Email
    $admin_email = get_option('admin_email');
    $subject = 'New Gold Buyback Quote: ' . $unique_id;

    ob_start();
?>
    <div
        style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; border: 1px solid #ddd; border-radius: 5px; overflow: hidden;">
        <div style="background-color: #d4af37; padding: 20px; text-align: center; color: #fff;">
            <h2 style="margin: 0; font-size: 24px;">New Lead: Quote <?php echo esc_html($unique_id); ?></h2>
        </div>
        <div style="padding: 20px; background-color: #f9f9f9; color: #333;">
            <p style="font-size: 16px; margin-top:0;">A customer has just requested a quote using the Preciousuite Gold
                Buyback Quote Calculator.</p>
            <p><strong>Customer Email:</strong> <a href="mailto:<?php echo esc_attr($email); ?>"
                    style="color: #2980b9;"><?php echo esc_html($email); ?></a></p>
            <table
                style="width: 100%; border-collapse: collapse; margin-top: 15px; background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                <tr>
                    <td style="padding: 12px; border-bottom: 1px solid #eee;"><strong>Weight</strong></td>
                    <td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;">
                        <?php echo esc_html($weight); ?>g
                    </td>
                </tr>
                <tr>
                    <td style="padding: 12px; border-bottom: 1px solid #eee;"><strong>Purity</strong></td>
                    <td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;">
                        <?php echo esc_html($karat); ?>
                    </td>
                </tr>
                <tr>
                    <td style="padding: 12px; border-bottom: 1px solid #eee;"><strong>Quoted Price</strong></td>
                    <td
                        style="padding: 12px; border-bottom: 1px solid #eee; text-align: right; font-size: 18px; color: #27ae60;">
                        <strong><?php echo esc_html($price); ?></strong>
                    </td>
                </tr>
            </table>
            <p style="font-size: 14px; color: #777; margin-top: 20px;">You can look up this exact quote in your WordPress
                dashboard under <strong>Gold Calc > Quotes</strong> by searching for ID
                <strong><?php echo esc_html($unique_id); ?></strong>.
            </p>
        </div>
    </div>
    <?php
    $message = ob_get_clean();

    $headers = array('Content-Type: text/html; charset=UTF-8');

    // Capture specific PHPMailer errors
    $mail_error = '';
    $error_handler = function ($error) use (&$mail_error) {
        $mail_error = $error->get_error_message();
    };
    add_action('wp_mail_failed', $error_handler);

    $admin_mail_sent = wp_mail($admin_email, $subject, $message, $headers);

    // 4. Compose Thank You Email to the Customer
    $customer_subject = 'Your Gold Quote is Locked! (ID: ' . $unique_id . ')';
    ob_start();
    ?>
    <div
        style="font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; border: 1px solid #ddd; border-radius: 5px; overflow: hidden;">
        <div style="background-color: #27ae60; padding: 20px; text-align: center; color: #fff;">
            <h2 style="margin: 0; font-size: 24px;">Your Gold Quote is Locked!</h2>
        </div>
        <div style="padding: 20px; background-color: #f9f9f9; color: #333;">
            <p style="font-size: 16px; margin-top:0;">Thank you for using our Preciousuite Gold Buyback Quote Calculator. We
                have securely saved your quoted price.</p>
            <p style="font-size: 18px; text-align: center; border: 2px dashed #27ae60; padding: 15px; margin: 20px 0;">
                <strong>Your Unique Quote ID: <?php echo esc_html($unique_id); ?></strong>
            </p>
            <table
                style="width: 100%; border-collapse: collapse; margin-top: 15px; background: #fff; box-shadow: 0 1px 3px rgba(0,0,0,0.1);">
                <tr>
                    <td style="padding: 12px; border-bottom: 1px solid #eee;"><strong>Weight</strong></td>
                    <td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;">
                        <?php echo esc_html($weight); ?>g
                    </td>
                </tr>
                <tr>
                    <td style="padding: 12px; border-bottom: 1px solid #eee;"><strong>Purity</strong></td>
                    <td style="padding: 12px; border-bottom: 1px solid #eee; text-align: right;">
                        <?php echo esc_html($karat); ?>
                    </td>
                </tr>
                <tr>
                    <td style="padding: 12px; border-bottom: 1px solid #eee;"><strong>Locked Price</strong></td>
                    <td
                        style="padding: 12px; border-bottom: 1px solid #eee; text-align: right; font-size: 18px; color: #27ae60;">
                        <strong><?php echo esc_html($price); ?></strong>
                    </td>
                </tr>
            </table>
            <p style="font-size: 14px; color: #777; margin-top: 20px;">Please bring this Quote ID with you when you visit
                our shop so we can easily look up your file and finalize the transaction!</p>
            <p style="font-size: 14px;">We look forward to seeing you soon.</p>
        </div>
    </div>
    <?php
    $customer_message = ob_get_clean();
    $customer_mail_sent = wp_mail($email, $customer_subject, $customer_message, $headers);

    remove_action('wp_mail_failed', $error_handler);

    if ($admin_mail_sent || $customer_mail_sent) {
        wp_send_json_success(array(
            'message' => 'Your quote has been locked and submitted successfully!',
            'whatsapp_url' => $whatsapp_url
        ));
    } else {
        $msg = 'Failed to send lead.';
        if (!empty($mail_error)) {
            $msg .= ' Debug: ' . $mail_error;
        }
        wp_send_json_error(array('message' => $msg));
    }
}

/**
 * Override PHPMailer with custom SMTP options if enabled
 */
add_action('phpmailer_init', 'preciousuite_custom_smtp_setup');

function preciousuite_custom_smtp_setup($phpmailer)
{
    if (get_option('preciousuite_smtp_enable')) {
        $phpmailer->isSMTP();
        $phpmailer->Host = get_option('preciousuite_smtp_host');
        $phpmailer->SMTPAuth = true;
        $phpmailer->Port = get_option('preciousuite_smtp_port');
        $phpmailer->Username = get_option('preciousuite_smtp_username');
        $phpmailer->Password = get_option('preciousuite_smtp_password');

        if ($phpmailer->Port == 587) {
            $phpmailer->SMTPSecure = 'tls';
        } elseif ($phpmailer->Port == 465) {
            $phpmailer->SMTPSecure = 'ssl';
        }

        $smtp_user = get_option('preciousuite_smtp_username');
        if (!is_email($smtp_user)) {
            $smtp_user = get_option('admin_email'); // Fallback in case of an invalid username
        }

        $phpmailer->setFrom($smtp_user, get_bloginfo('name'));
    }
}

// Ensure WordPress strictly uses this From address before PHPMailer runs it
add_filter('wp_mail_from', function ($email) {
    if (get_option('preciousuite_smtp_enable')) {
        $user = get_option('preciousuite_smtp_username');
        return is_email($user) ? $user : get_option('admin_email');
    }
    return $email;
});

add_filter('wp_mail_from_name', function ($name) {
    if (get_option('preciousuite_smtp_enable')) {
        return get_bloginfo('name');
    }
    return $name;
});


register_activation_hook(__FILE__, function () {
    if (!get_option('preciousuite_activation_time')) {
        update_option('preciousuite_activation_time', time());
    }
});

/**
 * Deactivation Hook — saves reason transient then calls portal API
 */
if (false) {
    register_deactivation_hook(__FILE__, function () {
        $reason = get_transient('preciousuite_pgbqcgold_deactivation_reason') ?: '';
        delete_transient('preciousuite_pgbqcgold_deactivation_reason');

        $plugin_data = preciousuite_pgbqcgold_get_plugin_data();
        $admin_email = $plugin_data['admin_email'];

        $token = preciousuite_pgbqcgold_get_token();
        if (!$token)
            return;

        $search = preciousuite_pgbqcgold_search_email($token, $admin_email);

        $payload = array(
            'plugin' => 'preciousuite-gold-buyback-quote-calculator',
            'site_url' => $plugin_data['site_url'],
            'email' => $admin_email,
            'store_country' => $plugin_data['country_info'],
            'plugin_version' => $plugin_data['plugin_version'],
            'eStatus' => 'deactivate',
            'reason' => $reason,
            'type' => 'wordpress',
        );

        if ($search && isset($search['success']) && $search['success'] === false) {
            preciousuite_pgbqcgold_store_log($token, $payload);
        } else {
            preciousuite_pgbqcgold_update_log($admin_email, array(
                'eStatus' => 'deactivate',
                'plugin' => 'preciousuite-gold-buyback-quote-calculator',
                'reason' => $reason,
                'type' => 'wordpress',
            ));
        }
    });
}

// ─────────────────────────────────────────────────────────────────────────────
// Deactivation Modal — plugins.php footer
// ─────────────────────────────────────────────────────────────────────────────

if (false) {
    add_action('admin_footer', 'preciousuite_pgbqcgold_deactivation_modal_html');
}
function preciousuite_pgbqcgold_deactivation_modal_html()
{
    global $pagenow;
    if ($pagenow !== 'plugins.php')
        return;
    ?>
    <div id="preciousuite-pgbqcgold-modal" title="Why are you deactivating?" style="display:none;">
        <p style="margin-bottom:15px;">Before you deactivate, please let us know why. Your feedback helps us improve!</p>
        <div style="margin-bottom:10px;">
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_pgbqcgold_reason" value="Temporary deactivation - I'll be back"
                    style="margin-right:8px;">
                Temporary deactivation - I'll be back
            </label>
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_pgbqcgold_reason" value="Found a better plugin"
                    style="margin-right:8px;">
                Found a better plugin
            </label>
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_pgbqcgold_reason" value="Plugin is not working"
                    style="margin-right:8px;">
                Plugin is not working
            </label>
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_pgbqcgold_reason" value="No longer needed" style="margin-right:8px;">
                No longer needed
            </label>
            <label style="display:block;margin-bottom:5px;">
                <input type="radio" name="preciousuite_pgbqcgold_reason" value="other" style="margin-right:8px;">
                Other
            </label>
        </div>
        <div id="preciousuite-pgbqcgold-custom-wrap" style="display:none;margin-top:10px;">
            <label>Please specify:</label><br>
            <textarea id="preciousuite-pgbqcgold-custom-reason" rows="3" cols="50" placeholder="Your reason..."
                style="width:100%;margin-top:5px;"></textarea>
        </div>
    </div>

    <script type="text/javascript">
        jQuery(document).ready(function($) {
            var deactivateUrl = '';

            $(document).on('click', 'a[href*="action=deactivate"][href*="preciousuite-gold-buyback-quote-calculator"]', function(e) {
                e.preventDefault();
                deactivateUrl = $(this).attr('href');

                // Reset modal state
                $('input[name="preciousuite_pgbqcgold_reason"]').prop('checked', false);
                $('#preciousuite-pgbqcgold-custom-wrap').hide();
                $('#preciousuite-pgbqcgold-custom-reason').val('');

                $('#preciousuite-pgbqcgold-modal').dialog({
                    modal: true,
                    width: 500,
                    closeOnEscape: false,
                    draggable: false,
                    resizable: false,
                    buttons: {
                        'Submit & Deactivate': function() {
                            var selected = $('input[name="preciousuite_pgbqcgold_reason"]:checked').val();
                            var custom = $('#preciousuite-pgbqcgold-custom-reason').val().trim();

                            if (!selected) {
                                alert('Please select a reason.');
                                return;
                            }
                            if (selected === 'other' && !custom) {
                                alert('Please provide a custom reason.');
                                return;
                            }

                            var finalReason = (selected === 'other') ? custom : selected;

                            $.post('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
                                action: 'preciousuite_pgbqcgold_store_deactivation_reason',
                                reason: finalReason,
                                nonce: '<?php echo esc_js(wp_create_nonce('preciousuite_pgbqcgold_deactivation_nonce')); ?>'
                            }, function() {
                                window.location.href = deactivateUrl;
                            });
                        },
                        'Cancel': function() {
                            $(this).dialog('close');
                        }
                    }
                });

                return false;
            });

            // Toggle custom reason textarea
            $(document).on('change', 'input[name="preciousuite_pgbqcgold_reason"]', function() {
                if ($(this).val() === 'other') {
                    $('#preciousuite-pgbqcgold-custom-wrap').show();
                } else {
                    $('#preciousuite-pgbqcgold-custom-wrap').hide();
                    $('#preciousuite-pgbqcgold-custom-reason').val('');
                }
            });
        });
    </script>
<?php
}

// ─────────────────────────────────────────────────────────────────────────────
// AJAX — Store deactivation reason in transient
// ─────────────────────────────────────────────────────────────────────────────

add_action('wp_ajax_preciousuite_pgbqcgold_store_deactivation_reason', 'preciousuite_pgbqcgold_store_deactivation_reason');
function preciousuite_pgbqcgold_store_deactivation_reason()
{
    if (
        !wp_verify_nonce(
            sanitize_text_field(wp_unslash($_POST['nonce'] ?? '')),
            'preciousuite_pgbqcgold_deactivation_nonce'
        )
    ) {
        wp_die('Security check failed');
    }

    $reason = sanitize_text_field(wp_unslash($_POST['reason'] ?? ''));
    if (!empty($reason)) {
        // Max 500 chars, 1 hour transient
        set_transient('preciousuite_pgbqcgold_deactivation_reason', substr($reason, 0, 500), HOUR_IN_SECONDS);
    }

    wp_die();
}

// ─────────────────────────────────────────────────────────────────────────────
// Portal API Helper Functions
// ─────────────────────────────────────────────────────────────────────────────

function preciousuite_pgbqcgold_get_token()
{
    $response = wp_remote_post('https://portal.preciousuite.com/api/auth/token', array(
        'body' => json_encode(array(
            'email' => 'admin@gmail.com',
            'password' => 'admin@123',
        )),
        'headers' => array('Content-Type' => 'application/json'),
        'timeout' => 15,
    ));

    if (is_wp_error($response))
        return false;

    $data = json_decode(wp_remote_retrieve_body($response), true);
    return ($data && !empty($data['success']) && !empty($data['data']['token']))
        ? $data['data']['token']
        : false;
}

function preciousuite_pgbqcgold_search_email($token, $email)
{
    $url = 'https://portal.preciousuite.com/api/plugin-log/search/email'
        . '?email=' . urlencode($email)
        . '&plugin=' . urlencode('preciousuite-gold-buyback-quote-calculator');

    $response = wp_remote_get($url, array(
        'headers' => array('Authorization' => 'Bearer ' . $token),
        'timeout' => 15,
    ));

    if (is_wp_error($response))
        return false;
    return json_decode(wp_remote_retrieve_body($response), true);
}

function preciousuite_pgbqcgold_store_log($token, $log_data)
{
    $response = wp_remote_post('https://portal.preciousuite.com/api/plugin-log/store', array(
        'body' => json_encode($log_data),
        'headers' => array(
            'Authorization' => 'Bearer ' . $token,
            'Content-Type' => 'application/json',
        ),
        'timeout' => 15,
    ));

    if (is_wp_error($response))
        return false;
    return json_decode(wp_remote_retrieve_body($response), true);
}

function preciousuite_pgbqcgold_update_log($email, $update_data)
{
    $token = preciousuite_pgbqcgold_get_token();
    if (!$token)
        return false;

    $url = 'https://portal.preciousuite.com/api/plugin-log/update/email?email=' . urlencode($email);

    $response = wp_remote_post($url, array(
        'method' => 'PUT',
        'body' => json_encode($update_data),
        'headers' => array(
            'Authorization' => 'Bearer ' . $token,
            'Content-Type' => 'application/json',
        ),
        'timeout' => 15,
    ));

    if (is_wp_error($response))
        return false;
    return json_decode(wp_remote_retrieve_body($response), true);
}

function preciousuite_pgbqcgold_get_plugin_data()
{
    if (!function_exists('get_plugin_data')) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    $admin_users = get_users(array(
        'role' => 'administrator',
        'number' => 1,
        'orderby' => 'ID',
        'order' => 'ASC',
    ));
    $admin_email = !empty($admin_users) ? $admin_users[0]->user_email : get_option('admin_email');

    $country_info = 'WooCommerce not active';
    if (class_exists('WooCommerce')) {
        $country_raw = get_option('woocommerce_default_country');
        $country_code = explode(':', $country_raw)[0];
        $country_info = $country_code;
        if (class_exists('WC_Countries')) {
            $wc = new WC_Countries();
            $country_info = $wc->countries[$country_code] ?? $country_code;
        }
    }

    $pd = get_plugin_data(PRECIOUSUITE_PATH . 'preciousuite-gold-buyback-quote-calculator.php', false, false);

    return array(
        'admin_email' => $admin_email,
        'site_url' => get_site_url(),
        'country_info' => $country_info,
        'plugin_version' => $pd['Version'] ?? '1.0.0',
    );
}

function preciousuite_pgbqcgold_precioussuite_stats()
{
    $counts = wp_count_posts('preciousuite_quote');
    $total = isset($counts->publish) ? (int) $counts->publish : 0;

    return array(
        array(
            'label' => __('Buyback Quotes', 'preciousuite-gold-buyback-quote-calculator'),
            'value' => (string) $total,
        ),
    );
}
