<script src="https://cdnjs.cloudflare.com/ajax/libs/slim-select/1.25.0/slimselect.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/slim-select/1.25.0/slimselect.min.css" rel="stylesheet">

<?php
if (!current_user_can('manage_options')) {
    die('Sorry, you are not allowed to access this page.');
    return;
}
?>

<script language="javascript" type="text/javascript">
    function imgFlagError(image) {
        image.onerror = "";
        image.src = "<?php echo plugins_url('/images/flags/noFlag.png', AHCPRO_PLUGIN_MAIN_FILE) ?>";
        return true;
    }
</script>

<style type="text/css">
    .ahc_main_container {
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        padding: 20px;
    }

    .ahc-header {
        display: flex;
        align-items: center;
        margin-bottom: 30px;
        background: #fff;
        padding: 20px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    }

    .ahc-header img {
        margin-right: 15px;
    }

    .ahc-header h1 {
        margin: 0;
        font-size: 24px;
        color: #23282d;
        font-weight: 600;
    }

    .ahc-settings-icon {
        margin-left: auto;
        padding: 8px;
        border-radius: 4px;
        transition: background-color 0.2s;
    }

    .ahc-settings-icon:hover {
        background-color: #f0f0f0;
    }

    .panel {
        background: #fff;
        border-radius: 8px;
        box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);
        border: none;
        margin-bottom: 20px;
        overflow: hidden;
    }

    .panel-header {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        padding: 20px;
        margin: 0;
        font-size: 20px;
        font-weight: 600;
    }

    /* Tab Styles - Matching free version design */
    .tab-container {
        width: 100%;
        margin: 0;
    }

    .tab-navigation {
        display: flex;
        border-bottom: 2px solid #e0e0e0;
        margin-bottom: 0;
        background: #f8f9fa;
    }

    .tab-button {
        background: transparent;
        border: none;
        border-bottom: 3px solid transparent;
        padding: 18px 25px;
        cursor: pointer;
        font-size: 16px;
        font-weight: 600;
        color: #666;
        transition: all 0.3s ease;
        text-decoration: none;
        display: inline-block;
    }

    .tab-button:hover {
        color: #667eea;
        border-bottom-color: #667eea;
        background: rgba(102, 126, 234, 0.05);
    }

    .tab-button.active {
        color: #667eea;
        border-bottom-color: #667eea;
        background: rgba(102, 126, 234, 0.1);
        font-weight: 700;
    }

    .tab-content {
        display: none;
        background: #fff;
        padding: 30px;
    }

    .tab-content.active {
        display: block;
    }

    .settings-section {
        margin-bottom: 35px;
        padding-bottom: 25px;
        border-bottom: 1px solid #e5e5e5;
    }

    .settings-section:last-child {
        border-bottom: none;
        margin-bottom: 0;
        padding-bottom: 0;
    }

    .section-title {
        font-size: 18px;
        font-weight: 600;
        color: #23282d;
        margin-bottom: 15px;
        display: flex;
        align-items: center;
    }

    .section-title::before {
        content: '';
        width: 4px;
        height: 20px;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        margin-right: 12px;
        border-radius: 2px;
    }

    .form-row {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;
        align-items: flex-start;
    }

    .form-group {
        flex: 1;
    }

    .form-group.half-width {
        flex: 0 0 48%;
    }

    .form-group.quarter-width {
        flex: 0 0 23%;
    }

    .form-label {
        display: block;
        font-weight: 600;
        color: #333;
        margin-bottom: 8px;
        font-size: 14px;
    }

    .form-control {
        width: 100%;
        padding: 12px 15px;
        border: 2px solid #e0e0e0;
        border-radius: 6px;
        font-size: 14px;
        transition: all 0.3s ease;
        background: #fff;
        box-sizing: border-box;
    }

    .form-control:focus {
        outline: none;
        border-color: #667eea;
        box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
    }

    .form-help {
        font-size: 12px;
        color: #666;
        margin-top: 5px;
        font-style: italic;
    }

    .timezone-note {
        background: #e8f5e8;
        color: #2d5016;
        padding: 10px 15px;
        border-radius: 6px;
        font-size: 13px;
        border-left: 4px solid #4caf50;
        margin-top: 10px;
    }

    .checkbox-container {
        display: flex;
        align-items: flex-start;
        gap: 10px;
        padding: 15px;
        background: #f8f9fa;
        border-radius: 6px;
        border: 1px solid #e9ecef;
        transition: all 0.2s ease;
        margin-bottom: 15px;
    }

    .checkbox-container:hover {
        background: #f0f2f5;
    }

    .checkbox-container input[type="checkbox"] {
        margin: 0;
        width: 18px;
        height: 18px;
        accent-color: #667eea;
        cursor: pointer;
    }

    .checkbox-container input[type="checkbox"]:checked {
        background-color: #667eea;
        border-color: #667eea;
    }

    .checkbox-label {
        flex: 1;
        font-size: 14px;
        color: #333;
        line-height: 1.4;
    }

    .checkbox-label.warning {
        color: #d32f2f;
        font-weight: 500;
    }

    .select-container {
        position: relative;
    }

    .multi-select {
        min-height: 52px;
        padding: 10px;
    }

    .button-group {
        display: flex;
        gap: 15px;
        margin-top: 30px;
        padding-top: 25px;
        border-top: 1px solid #e5e5e5;
    }

    .btn {
        padding: 15px 30px;
        border: none;
        border-radius: 6px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        min-width: 150px;
    }

    .btn-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    .btn-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
    }

    .btn-secondary {
        background: #f8f9fa;
        color: #333;
        border: 2px solid #e9ecef;
    }

    .btn-secondary:hover {
        background: #e9ecef;
        transform: translateY(-1px);
    }

    /* Legacy button support */
    .button,
    input[type="submit"],
    button[type="submit"] {
        padding: 15px 30px;
        border: none;
        border-radius: 6px;
        font-size: 16px;
        font-weight: 600;
        cursor: pointer;
        text-decoration: none;
        display: inline-flex;
        align-items: center;
        justify-content: center;
        transition: all 0.3s ease;
        margin-right: 15px;
        min-width: 150px;
    }

    .button-primary {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
    }

    .button-primary:hover {
        transform: translateY(-2px);
        box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
    }

    .button-secondary {
        background: #f8f9fa;
        color: #333;
        border: 2px solid #e9ecef;
    }

    .button-secondary:hover {
        background: #e9ecef;
        transform: translateY(-1px);
    }

    .success-message {
        background: #d4edda;
        color: #155724;
        padding: 15px 20px;
        border-radius: 6px;
        border-left: 4px solid #28a745;
        margin: 20px 0;
        display: flex;
        align-items: center;
        gap: 10px;
    }

    .success-message::before {
        content: '✓';
        font-weight: bold;
        font-size: 18px;
    }

    .success-links {
        margin-top: 10px;
    }

    .success-links a {
        color: #155724;
        text-decoration: none;
        font-weight: 500;
        margin-right: 15px;
    }

    .success-links a:hover {
        text-decoration: underline;
    }

    /* Mobile App Instructions */
    .mobile-app-instructions {
        background: #f8f9fa;
        padding: 15px;
        border-radius: 6px;
        border-left: 4px solid #667eea;
        font-size: 14px;
    }

    .mobile-app-instructions p {
        margin: 5px 0;
    }

    .mobile-app-instructions a {
        color: #667eea;
        text-decoration: none;
        font-weight: 500;
    }

    .mobile-app-instructions a:hover {
        text-decoration: underline;
    }

    /* Test message styling */
    #gsc-test-message {
        padding: 10px;
        border-radius: 4px;
        margin-top: 10px;
    }

    /* Legacy grid support */
    .row {
        display: flex;
        gap: 20px;
        margin-bottom: 20px;
        flex-wrap: wrap;
    }

    .col-md-6 {
        flex: 0 0 48%;
        min-width: 300px;
        box-sizing: border-box;
    }

    .col-md-12 {
        flex: 1;
        box-sizing: border-box;
    }

    /* Legacy label support */
    label {
        display: block;
        font-weight: 600;
        color: #333;
        margin-bottom: 8px;
        font-size: 14px;
    }

    .form-text,
    small {
        font-size: 12px;
        color: #666;
        margin-top: 5px;
        font-style: italic;
    }

    textarea.form-control {
        resize: vertical;
        min-height: 100px;
    }

    /* Sync Section Styles */
    #gsc-sync-status {
        border: 1px solid #dee2e6;
    }

    .sync-success {
        background: #d4edda !important;
        color: #155724 !important;
        border-left-color: #28a745 !important;
    }

    .sync-error {
        background: #f8d7da !important;
        color: #721c24 !important;
        border-left-color: #dc3545 !important;
    }

    .sync-warning {
        background: #fff3cd !important;
        color: #856404 !important;
        border-left-color: #ffc107 !important;
    }

    .spinner {
        background: url(../../../wp-admin/images/spinner.gif) no-repeat;
        background-size: 20px 20px;
        width: 20px;
        height: 20px;
        display: inline-block;
        opacity: 0.7;
        filter: alpha(opacity=70);
        vertical-align: middle;
    }

    @media (max-width: 768px) {

        .form-row,
        .row {
            flex-direction: column;
        }

        .form-group.half-width,
        .form-group.quarter-width,
        .col-md-6 {
            flex: 1;
            min-width: auto;
        }

        .tab-button {
            padding: 12px 15px;
            font-size: 14px;
        }

        .button-group {
            flex-direction: column;
        }

        .btn,
        .button {
            width: 100%;
            margin-right: 0;
            margin-bottom: 10px;
        }

        #gsc-sync-status .form-row {
            flex-direction: column;
        }
    }
</style>

<?php
ahcpro_include_scripts();
$msg = '';
if (isset($_POST['save_general'])) {
    if (ahcpro_savesettings()) {
        $msg = '<div class="success-message" style="font-size: 16px; font-weight: bold;">Settings saved successfully!</div>';
    }
}

if (isset($_POST['save_gsc'])) {
    $json_data = stripslashes($_POST['gsc_service_account_json']);
    $decoded = json_decode($json_data, true);

    if (json_last_error() === JSON_ERROR_NONE && isset($decoded['private_key']) && isset($decoded['client_email'])) {
        update_option('ahcpro_gsc_service_account_json', $json_data);
        $msg = '<div class="success-message" style="font-size: 16px; font-weight: bold;">Service Account JSON saved successfully!</div>';
    } else if (!empty($json_data)) {
        $msg = '<div style="background: #f8d7da; color: #721c24; padding: 15px; border-radius: 6px; border-left: 4px solid #dc3545; margin: 20px 0;">Invalid JSON format. Please check your Service Account JSON.</div>';
    }
}
$ahcpro_get_save_settings = ahcpro_get_save_settings();
$hits_days = isset($ahcpro_get_save_settings[0]->set_hits_days) ? $ahcpro_get_save_settings[0]->set_hits_days : 14;
$ajax_check = isset($ahcpro_get_save_settings[0]->set_ajax_check) ? ($ahcpro_get_save_settings[0]->set_ajax_check * 1000) : 10 * 1000;
$set_ips = isset($ahcpro_get_save_settings[0]->set_ips) ? $ahcpro_get_save_settings[0]->set_ips : "";
$set_google_map = isset($ahcpro_get_save_settings[0]->set_google_map) ? $ahcpro_get_save_settings[0]->set_google_map : '';
$delete_plugin_data = get_option('ahcpro_delete_plugin_data_on_uninstall');
$ahcpro_save_ips = get_option('ahcpro_save_ips_opn');
$ahcproUserRoles = get_option('ahcproUserRoles');
$ahcproExcludeRoles = get_option('ahcproExcludeRoles');
$ahcproRobots = get_option('ahcproRobots');
$ahcpro_haships = get_option('ahcpro_haships');
$ahcpro_hide_top_bar_icon = get_option('ahcpro_hide_top_bar_icon');

if ($set_ips != '') {
    $set_ips = str_ireplace(' ', '&#10;', $set_ips);
}
?>

<div class="ahc_main_container">
    <!-- Header -->
    <div class="ahc-header">
        <img width="40px" src="<?php echo esc_url(plugins_url('/images/logo.png', AHCPRO_PLUGIN_MAIN_FILE)); ?>"
            alt="Plugin Logo">
        <h1>Visitor Traffic Real Time Statistics Pro - Settings</h1>
        <a class="ahc-settings-icon" href="admin.php?page=ahc_hits_counter_menu_pro" title="Back to Dashboard">
            <img src="<?php echo esc_url(plugins_url('/images/settings.jpg', AHCPRO_PLUGIN_MAIN_FILE)); ?>"
                alt="Dashboard" />
        </a>
    </div>

    <!-- Success/Error Messages -->
    <?php echo $msg; ?>

    <!-- Main Settings Panel -->
    <div class="panel">
        <div class="tab-container">
            <div class="tab-navigation">
                <button type="button" class="tab-button active" onclick="openTab(event, 'general-tab')">General Settings</button>
                <button type="button" class="tab-button" onclick="openTab(event, 'gsc-tab')">Google Console API</button>
            </div>

            <!-- General Settings Tab -->
            <div id="general-tab" class="tab-content active">
                <form method="post" enctype="multipart/form-data" name="general_settings_form">
                    <?php $nonce = wp_create_nonce('ahc_settings_action'); ?>
                    <input type="hidden" name="ahc_settings_send" value="<?php echo esc_attr($nonce); ?>" />

                    <!-- Statistics Configuration -->
                    <div class="settings-section">
                        <h3 class="section-title">Statistics Configuration</h3>

                        <div class="form-row">
                            <div class="form-group half-width">
                                <label class="form-label" for="set_hits_days">Statistics Time Range (Days)</label>
                                <input type="number" value="<?php echo esc_attr($hits_days); ?>" class="form-control"
                                    id="set_hits_days" name="set_hits_days" min="1" max="365" placeholder="14">
                                <div class="form-help">Number of days to display in statistics charts (default: 14 days)</div>
                            </div>

                            <div class="form-group half-width">
                                <label class="form-label" for="set_custom_timezone">Timezone</label>
                                <select class="form-control" id="set_custom_timezone" name="set_custom_timezone">
                                    <?php
                                    $wp_timezone_string = get_option('timezone_string');
                                    $custom_timezone_offset = (get_option('ahcpro_custom_timezone') != '') ? get_option('ahcpro_custom_timezone') : $wp_timezone_string;
                                    $timezones = DateTimeZone::listIdentifiers(DateTimeZone::ALL);
                                    foreach ($timezones as $key => $value) {
                                    ?>
                                        <option value="<?php echo esc_attr($value); ?>"
                                            <?php echo ($value == $custom_timezone_offset) ? 'selected' : ''; ?>>
                                            <?php echo esc_html($value); ?>
                                        </option>
                                    <?php } ?>
                                </select>
                                <div class="timezone-note">
                                    <strong>Note:</strong> Please select the same timezone in your <a
                                        href="options-general.php" target="_blank">general settings page</a>
                                </div>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group half-width">
                                <label class="form-label" for="set_ajax_check">Online Users Check Interval (Seconds)</label>
                                <input type="number" value="<?php echo esc_attr(intval($ajax_check) / 1000); ?>"
                                    class="form-control" id="set_ajax_check" name="set_ajax_check" min="5" max="300"
                                    placeholder="10">
                                <div class="form-help">How often to check for online users (default: 10 seconds)</div>
                            </div>

                            <div class="form-group half-width">
                                <label class="form-label" for="set_google_map">Map Display Data</label>
                                <select class="form-control" name="set_google_map" id="set_google_map">
                                    <option value="all"
                                        <?php echo ($set_google_map == 'all') ? 'selected=selected' : ''; ?>>All time visitors</option>
                                    <option value="today_visitors"
                                        <?php echo ($set_google_map == 'today_visitors') ? 'selected=selected' : ''; ?>>
                                        Today visitors per country</option>
                                    <option value="top10"
                                        <?php echo ($set_google_map == 'top10') ? 'selected=selected' : ''; ?>>Top 10 countries</option>
                                    <option value="online"
                                        <?php echo ($set_google_map == 'online') ? 'selected=selected' : ''; ?>>Online Visitors</option>
                                    <option value="this_month"
                                        <?php echo ($set_google_map == 'this_month') ? 'selected=selected' : ''; ?>>This Month Visitors</option>
                                    <option value="past_month"
                                        <?php echo ($set_google_map == 'past_month') ? 'selected=selected' : ''; ?>>Past Month Visitors</option>
                                </select>
                                <div class="form-help">Select what data to display on the map visualization</div>
                            </div>
                        </div>
                    </div>

                    <!-- Exclusion Settings -->
                    <div class="settings-section">
                        <h3 class="section-title">Tracking Exclusions</h3>

                        <div class="form-row">
                            <div class="form-group half-width">
                                <label class="form-label" for="set_ips">IP Addresses to Exclude</label>
                                <textarea placeholder="192.168.1.1&#10;192.168.1.2&#10;One IP per line" name="set_ips"
                                    id="set_ips" rows="4"
                                    class="form-control"><?php echo esc_html($set_ips); ?></textarea>
                                <div class="form-help">Excluded IP addresses will not be tracked. Enter one IP address per line.</div>
                            </div>

                            <div class="form-group half-width">
                                <label class="form-label" for="ahcproExcludeRoles">User Roles to Exclude from Statistics</label>
                                <div class="select-container">
                                    <select id="ahcproExcludeRoles" name="ahcproExcludeRoles[]" multiple="true"
                                        class="multi-select">
                                        <?php
                                        global $wp_roles;
                                        if (!isset($wp_roles)) $wp_roles = new WP_Roles();
                                        $available_roles_names = $wp_roles->get_names();
                                        $available_roles_capable = array();

                                        foreach ($available_roles_names as $role_key => $role_name) {
                                            $available_roles_capable[$role_key] = $role_name;
                                        }

                                        $UserRoles = get_option('ahcproExcludeRoles');
                                        $UserRoles_arr = explode(',', $UserRoles);

                                        foreach ($available_roles_capable as $role) {
                                            $translated_role_name = $role;
                                            $selected_value = in_array($translated_role_name, $UserRoles_arr) ? 'selected=selected' : '';
                                        ?>
                                            <option <?php echo $selected_value; ?>
                                                value="<?php echo esc_attr($translated_role_name); ?>">
                                                <?php echo esc_html($translated_role_name); ?>
                                            </option>
                                        <?php } ?>
                                    </select>
                                </div>
                                <div class="form-help">Selected user roles will be excluded from visitor tracking</div>
                            </div>
                        </div>
                    </div>

                    <!-- Access Control -->
                    <div class="settings-section">
                        <h3 class="section-title">Access Control</h3>

                        <div class="form-row">
                            <div class="form-group half-width">
                                <label class="form-label" for="ahcproUserRoles">Plugin Access Permissions</label>
                                <div class="select-container">
                                    <select id="ahcproUserRoles" name="ahcproUserRoles[]" multiple="true"
                                        class="multi-select">
                                        <?php
                                        $UserRoles = get_option('ahcproUserRoles');
                                        $UserRoles_arr = explode(',', $UserRoles);

                                        foreach ($available_roles_capable as $role) {
                                            $translated_role_name = $role;
                                            $is_admin = ($translated_role_name == 'Administrator' || $translated_role_name == 'Super Admin');
                                            $selected_value = (in_array($translated_role_name, $UserRoles_arr) || $is_admin) ? 'selected=selected' : '';
                                        ?>
                                            <option <?php echo $selected_value; ?>
                                                value="<?php echo esc_attr($translated_role_name); ?>">
                                                <?php echo esc_html($translated_role_name); ?>
                                                <?php echo $is_admin ? ' (Always Enabled)' : ''; ?>
                                            </option>
                                        <?php } ?>
                                    </select>
                                </div>
                                <div class="form-help">Select which user roles can access the plugin dashboard and statistics</div>
                            </div>

                            <div class="form-group half-width">
                                <label class="form-label">Mobile App Setup Instructions</label>
                                <div class="mobile-app-instructions">
                                    <p><strong>Step 1:</strong> Download the App (<a target="_blank"
                                            href="https://play.google.com/store/apps/details?id=com.codepress.trafic.trafic_static_app">click here</a>)</p>
                                    <p><strong>Step 2:</strong> Activate the Mobile App to generate QR Code (<a
                                            href="<?php echo esc_url(admin_url('/admin.php?page=ahcpro_app')); ?>">click here</a>)</p>
                                    <p><strong>Step 3:</strong> Open the App and scan the QR Code</p>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Privacy & Display Options -->
                    <div class="settings-section">
                        <h3 class="section-title">Privacy & Display Options</h3>

                        <div class="form-row">
                            <div class="form-group half-width">
                                <div class="checkbox-container">
                                    <input type="checkbox" id="ahcpro_hide_top_bar_icon" value="1"
                                        name="ahcpro_hide_top_bar_icon"
                                        <?php echo ($ahcpro_hide_top_bar_icon == 1) ? 'checked=checked' : ''; ?>>
                                    <label class="checkbox-label" for="ahcpro_hide_top_bar_icon">
                                        <strong>Hide Top Bar Icon</strong><br>
                                        Remove the plugin icon from the WordPress admin top bar
                                    </label>
                                </div>
                            </div>

                            <div class="form-group half-width">
                                <div class="checkbox-container">
                                    <input type="checkbox" id="ahcpro_haships" value="1" name="ahcpro_haships"
                                        <?php echo ($ahcpro_haships == 1) ? 'checked=checked' : ''; ?>>
                                    <label class="checkbox-label" for="ahcpro_haships">
                                        <strong>Hash IP Addresses</strong><br>
                                        Hide the last 3 digits of all IP addresses for privacy protection
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Data Management -->
                    <div class="settings-section">
                        <h3 class="section-title">Data Management</h3>

                        <div class="form-row">
                            <div class="form-group">
                                <div class="checkbox-container">
                                    <input type="checkbox" id="delete_plugin_data" value="1" name="delete_plugin_data"
                                        <?php echo ($delete_plugin_data == 1) ? 'checked=checked' : ''; ?>>
                                    <label class="checkbox-label warning" for="delete_plugin_data">
                                        <strong>⚠️ Delete All Data on Uninstall</strong><br>
                                        WARNING: All statistics data will be permanently deleted when the plugin is
                                        uninstalled. This action cannot be undone.
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="button-group">
                        <input type="submit" name="save_general" value="Save Settings" class="btn btn-primary" />
                        <a href="admin.php?page=ahc_hits_counter_menu_pro" class="btn btn-secondary">Back to Dashboard</a>
                    </div>
                </form>
            </div>

            <!-- Google Console API Tab -->
            <div id="gsc-tab" class="tab-content">
                <form method="post" enctype="multipart/form-data" name="gsc_settings_form">
                    <?php $nonce = wp_create_nonce('ahc_settings_action'); ?>
                    <input type="hidden" name="ahc_settings_send" value="<?php echo esc_attr($nonce); ?>" />

                    <div class="settings-section">
                        <h3 class="section-title">Google Search Console API Configuration</h3>

                        <div class="form-row">
                            <div class="form-group">
                                <label class="form-label" for="gsc_service_account_json">Service Account JSON Credentials</label>
                                <textarea class="form-control" id="gsc_service_account_json"
                                    name="gsc_service_account_json" rows="8"
                                    placeholder="Paste your Service Account JSON credentials here..."><?php echo esc_textarea(get_option('ahcpro_gsc_service_account_json', '')); ?></textarea>
                                <div class="form-help">
                                    <strong>How to get Service Account JSON:</strong><br>
                                    1. Go to <a href="https://console.developers.google.com/" target="_blank">Google Cloud Console</a><br>
                                    2. Select your project → APIs & Services → Credentials<br>
                                    3. Find your Service Account → Click "Manage keys"<br>
                                    4. Click "Add Key" → "Create new key" → Choose "JSON"<br>
                                    5. Download the JSON file and paste its contents here<br>
                                    6. Add the service account email to your <a href="https://search.google.com/search-console/" target="_blank">Search Console property</a><br><br>
                                    <strong>📖 Complete Documentation:</strong> <a href="https://developers.google.com/webmaster-tools/about" target="_blank">Google Search Console API Guide</a>
                                </div>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group half-width">
                                <input type="button" id="test-gsc-button" value="Test Connection" class="btn btn-secondary" style="background-color: mediumseagreen;" />
                                <div class="form-help">Verify your JSON credentials are working</div>
                                <div id="gsc-test-message"></div>
                            </div>
                        </div>
                    </div>

                    <!-- Search Console Data Sync Section -->
                    <div class="settings-section">
                        <h3 class="section-title">Search Console Data Sync</h3>

                        <div id="gsc-sync-status" class="form-row" style="background: #f8f9fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
                            <div class="form-group half-width">
                                <label class="form-label">Last Sync Status</label>
                                <div id="sync-status-display" style="font-size: 14px; color: #666;">
                                    <div class="spinner" style="float: none; margin: 0 10px 0 0; visibility: visible;"></div>
                                    Loading sync status...
                                </div>
                            </div>

                            <div class="form-group half-width">
                                <label class="form-label">Manual Sync</label>
                                <button type="button" id="manual-gsc-sync" class="btn btn-primary" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                    <span class="dashicons dashicons-update" style="margin-top: 3px; margin-right: 5px;"></span>
                                    Sync Search Console Data
                                </button>
                                <div class="form-help">Manually sync the latest search query data from Google Search Console</div>
                                <div id="sync-message" style="margin-top: 10px;"></div>
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group">
                                <div style="background: #e3f2fd; padding: 15px; border-radius: 6px; border-left: 4px solid #2196f3;">
                                    <strong>ℹ️ How Sync Works:</strong><br>
                                    • Data is synced from Google Search Console when you click the sync button<br>
                                    • Shows search queries that brought visitors to your site<br>
                                    • Updates the "Latest Search Words" table on your dashboard<br>
                                    • Only syncs when you visit this settings page and click sync<br>
                                    • Data may take 1-3 days to appear in Google Search Console for new sites
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Action Buttons -->
                    <div class="button-group">
                        <input type="submit" name="save_gsc" value="Save GSC Settings" class="btn btn-primary" />
                        <a href="admin.php?page=ahc_hits_counter_menu_pro" class="btn btn-secondary">Back to Dashboard</a>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Load sync status on page load
        loadSyncStatus();

        // Manual sync button handler
        document.getElementById('manual-gsc-sync').addEventListener('click', function() {
            const button = this;
            const messageDiv = document.getElementById('sync-message');

            // Disable button and show loading
            button.disabled = true;
            button.innerHTML = '<span class="spinner" style="float: none; margin: 0 5px 0 0;"></span>Syncing...';
            messageDiv.innerHTML = '<div style="background: #e3f2fd; color: #1976d2; padding: 10px; border-radius: 4px; border-left: 3px solid #2196f3;">🔄 Syncing data from Google Search Console...</div>';

            fetch(ajaxurl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'ahcpro_manual_gsc_sync',
                        nonce: '<?php echo wp_create_nonce('ahcpro_manual_gsc_sync'); ?>'
                    })
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        messageDiv.innerHTML = '<div style="background: #d4edda; color: #155724; padding: 10px; border-radius: 4px; border-left: 3px solid #28a745;">✅ ' + data.data.message + '</div>';

                        // Refresh sync status
                        setTimeout(loadSyncStatus, 1000);

                        // Auto-hide success message after 5 seconds
                        setTimeout(() => {
                            messageDiv.innerHTML = '';
                        }, 5000);
                    } else {
                        messageDiv.innerHTML = '<div style="background: #f8d7da; color: #721c24; padding: 10px; border-radius: 4px; border-left: 3px solid #dc3545;">❌ ' + data.data + '</div>';
                    }
                })
                .catch(err => {
                    messageDiv.innerHTML = '<div style="background: #f8d7da; color: #721c24; padding: 10px; border-radius: 4px; border-left: 3px solid #dc3545;">❌ Request failed: ' + err.message + '</div>';
                })
                .finally(() => {
                    // Re-enable button
                    button.disabled = false;
                    button.innerHTML = '<span class="dashicons dashicons-update" style="margin-top: 3px; margin-right: 5px;"></span>Sync Search Console Data';
                });
        });

        // Function to load sync status
        function loadSyncStatus() {
            const statusDiv = document.getElementById('sync-status-display');

            fetch(ajaxurl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'ahcpro_get_gsc_sync_status'
                    })
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        const status = data.data;
                        let statusHtml = '';

                        if (status.has_synced) {
                            statusHtml = `
                        <div style="color: #155724;">
                            <strong>✅ Last Sync:</strong> ${status.last_sync_human}<br>
                            <strong>📊 Keywords Synced:</strong> ${status.last_count}<br>
                            <small style="color: #666;">Full date: ${status.last_sync}</small>
                        </div>
                    `;
                        } else {
                            statusHtml = `
                        <div style="color: #856404;">
                            <strong>⚠️ Never synced</strong><br>
                            <small>Click the sync button to get search data</small>
                        </div>
                    `;
                        }

                        statusDiv.innerHTML = statusHtml;
                    } else {
                        statusDiv.innerHTML = '<div style="color: #721c24;">❌ Could not load sync status</div>';
                    }
                })
                .catch(err => {
                    statusDiv.innerHTML = '<div style="color: #721c24;">❌ Error loading status</div>';
                });
        }

        // Test GSC Connection
        document.getElementById('test-gsc-button').addEventListener('click', function() {
            const jsonTextarea = document.getElementById('gsc_service_account_json');
            const messageBox = document.getElementById('gsc-test-message');
            const jsonValue = jsonTextarea.value;

            messageBox.innerHTML = '<span style="color:#555;">Testing connection...</span>';

            fetch(ajaxurl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: new URLSearchParams({
                        action: 'test_gsc_connection',
                        nonce: '<?php echo wp_create_nonce("test_gsc_nonce"); ?>',
                        gsc_service_account_json: jsonValue
                    })
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        messageBox.innerHTML =
                            `<div style="color:green;">${data.data.message.replace(/\n/g, "<br>")}</div>`;
                    } else {
                        messageBox.innerHTML =
                            `<div style="color:red; font-weight:bold;">❌ ${data.data.message}</div>`;
                    }
                })
                .catch(err => {
                    messageBox.innerHTML = `<div style="color:red;">Error: ${err.message}</div>`;
                });
        });

        // Initialize SlimSelect for multi-select dropdowns
        if (typeof SlimSelect !== 'undefined') {
            new SlimSelect({
                select: '#ahcproExcludeRoles',
                settings: {
                    placeholderText: 'Select roles to exclude...',
                    searchText: 'Search roles...',
                    searchPlaceholder: 'Search...'
                }
            });

            new SlimSelect({
                select: '#ahcproUserRoles',
                settings: {
                    placeholderText: 'Select roles with access...',
                    searchText: 'Search roles...',
                    searchPlaceholder: 'Search...'
                }
            });
        }

        // Add form validation
        jQuery('form[name="general_settings_form"]').on('submit', function(e) {
            var hits_days = parseInt(jQuery('#set_hits_days').val());
            var ajax_check = parseInt(jQuery('#set_ajax_check').val());

            if (hits_days < 1 || hits_days > 365) {
                alert('Statistics time range must be between 1 and 365 days.');
                e.preventDefault();
                return false;
            }

            if (ajax_check < 5 || ajax_check > 300) {
                alert('Online users check interval must be between 5 and 300 seconds.');
                e.preventDefault();
                return false;
            }
        });
    });

    // Tab functionality
    function openTab(evt, tabName) {
        var i, tabcontent, tabbuttons;

        // Hide all tab content
        tabcontent = document.getElementsByClassName("tab-content");
        for (i = 0; i < tabcontent.length; i++) {
            tabcontent[i].classList.remove("active");
        }

        // Remove active class from all tab buttons
        tabbuttons = document.getElementsByClassName("tab-button");
        for (i = 0; i < tabbuttons.length; i++) {
            tabbuttons[i].classList.remove("active");
        }

        // Show the selected tab and mark button as active
        document.getElementById(tabName).classList.add("active");
        evt.currentTarget.classList.add("active");
    }
</script>