<?php
// Exit if accessed directly
if (! defined('ABSPATH')) {
    exit;
}

// -------------------------------
// Settings Page with Tabs
// -------------------------------
function ezhp_settings_page()
{
?>
    <div class="wrap">
        <h1><?php esc_html_e('EZ Horoscope Settings', 'ez-horoscope'); ?></h1>

        <h2 class="nav-tab-wrapper">
            <a href="#ezhp-tab-automation" class="nav-tab nav-tab-active"><?php esc_html_e('Automation', 'ez-horoscope'); ?></a>
            <a href="#ezhp-tab-utilities" class="nav-tab"><?php esc_html_e('Utilities', 'ez-horoscope'); ?></a>
            <a href="#ezhp-tab-voice" class="nav-tab"><?php esc_html_e('AI Voice Agents', 'ez-horoscope'); ?></a>
            <a href="#ezhp-tab-horoscope" class="nav-tab"><?php esc_html_e('Legacy Settings', 'ez-horoscope'); ?></a>
        </h2>

        <!-- TAB 1: Horoscope Settings -->
        <div id="ezhp-tab-horoscope" class="ezhp-tab-content" style="display:none;">
            <p>
                <strong><span style="background-color: #fff59d; padding: 2px 4px;">
                        These settings are for the legacy shortcodes. Use the EZ Horoscope Blocks for up-to-date features and functionality.
                    </span></strong>

                <br>For documentation, visit:
                <a href="https://ezhoroscope.com/documentation/" target="_blank" rel="noopener">https://ezhoroscope.com/documentation/</a>
                <br>For video tutorials, visit our youtube channel:
                <a href="https://www.youtube.com/@ezhoroscope" target="_blank" rel="noopener">https://www.youtube.com/@ezhoroscope</a>
            </p>

            <form method="post" action="options.php">
                <?php
                // Verify nonce for horoscope settings form
                if (isset($_POST['_wpnonce']) && ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'ezhp_horoscope_settings_group-options')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'ez-horoscope'));
                }
                settings_fields('ezhp_horoscope_settings_group');
                do_settings_sections('ez-horoscope-settings');
                submit_button();
                ?>
            </form>
        </div>

        <!-- TAB 2: Voice Agent Settings -->
        <div id="ezhp-tab-voice" class="ezhp-tab-content" style="display:none;">
            <h2><?php esc_html_e('AI Voice Agents', 'ez-horoscope'); ?></h2>

            <p style="max-width:800px;">
                <?php esc_html_e('Brilyi Voice Agents allow you to embed an interactive AI assistant directly on your horoscope pages. These agents can speak with visitors, answer questions, share horoscope insights, and engage users in real time — all powered by the Brilyi AI platform.  To try it out without a Brilyi account, generate a shortcode for the Astrology Demonstration Agent below and paste that shortcode in one of your pages.', 'ez-horoscope'); ?>
            </p>
            <p style="max-width:800px;">
                <?php esc_html_e('To begin, go to the Brilyi Dashboard and register for an account. Once signed in, select a subscription plan for your organization, create your first agent, then generate an API key in your Organization Settings. Copy that key and paste it into the field below. Then click Save Voice Agent Settings.', 'ez-horoscope'); ?>
            </p>
            <p style="max-width:800px;">
                <?php esc_html_e('After saving your API key, click “Load Agents” to sync your available agents from Brilyi. Then choose an agent and click “Generate Shortcode” to insert your voice widget anywhere on your WordPress pages or posts.', 'ez-horoscope'); ?>
            </p>

            <!-- Optional: button to open Brilyi in a new tab -->
            <p>
                <a class="button button-secondary" href="https://dashboard.brilyi.com" target="_blank" rel="noopener">
                    <?php esc_html_e('Open Brilyi Platform', 'ez-horoscope'); ?>
                </a>
            </p>

            <?php
            $settings_updated = isset($_GET['settings-updated']) ? sanitize_text_field(wp_unslash($_GET['settings-updated'])) : '';
            if ($settings_updated) :
            ?>
                <div id="message" class="updated notice is-dismissible">
                    <p><?php esc_html_e('Voice Agent settings saved successfully.', 'ez-horoscope'); ?></p>
                </div>
            <?php endif; ?>

            <form method="post" action="options.php">
                <?php
                // Verify nonce for voice agent settings form
                if (isset($_POST['_wpnonce']) && ! wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce'])), 'ezhp_voice_settings_group-options')) {
                    wp_die(esc_html__('Security check failed. Please try again.', 'ez-horoscope'));
                }
                settings_fields('ezhp_voice_settings_group');
                do_settings_sections('ezhp-voice-settings');

                $agent_id   = get_option('ezhp_voice_agent_id', '');
                $last4      = get_option('ezhp_voice_api_key_last4', '');
                ?>


                <table class="form-table" role="presentation">
                    <tr>
                        <th scope="row"><?php esc_html_e('Actions', 'ez-horoscope'); ?></th>
                        <td>
                            <button type="button" class="button" id="ezhp_load_agents"><?php esc_html_e('Load Agents', 'ez-horoscope'); ?></button>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="ezhp_agent_dropdown"><?php esc_html_e('Select Agent', 'ez-horoscope'); ?></label>
                        </th>
                        <td>
                            <select id="ezhp_agent_dropdown" name="ezhp_voice_agent_id" style="width: 400px;" disabled>
                                <!-- Always include demo agent -->
                                <option value="03A262CA-8DAA-4620-A9B2-90A133EDA393"
                                    <?php selected($agent_id, '03A262CA-8DAA-4620-A9B2-90A133EDA393'); ?>>
                                    <?php esc_html_e('Astrology Demonstration Agent', 'ez-horoscope'); ?>
                                </option>

                                <?php if ($agent_id && $agent_id !== '03A262CA-8DAA-4620-A9B2-90A133EDA393') : ?>
                                    <option value="<?php echo esc_attr($agent_id); ?>" selected>
                                        <?php echo esc_html($agent_id); ?>
                                    </option>
                                <?php endif; ?>
                            </select>
                            <p class="description"><?php esc_html_e('Choose the Voice Agent to use from your Brilyi account.', 'ez-horoscope'); ?></p>
                        </td>
                    </tr>

                    <tr>
                        <th scope="row"><?php esc_html_e('Shortcode', 'ez-horoscope'); ?></th>
                        <td>
                            <button type="button" class="button button-primary" id="ezhp_generate_shortcode">
                                <?php esc_html_e('Generate Shortcode', 'ez-horoscope'); ?>
                            </button>
                            <div id="ezhp_shortcode_result" style="margin-top:8px;"></div>
                        </td>
                    </tr>
                </table>


                <?php submit_button(__('Save Voice Agent Settings', 'ez-horoscope')); ?>
            </form>



        </div>

        <!-- TAB 3: Automation Settings -->
        <!-- TAB 1: Automation Settings -->
        <div id="ezhp-tab-automation" class="ezhp-tab-content" style="display:block;">
            <h2><?php esc_html_e('Page Generator', 'ez-horoscope'); ?></h2>

            <?php
            // Get the current language (default to English)
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Reading URL parameter for display purposes only, not processing form data
            $ezhp_current_lang = isset($_GET['lang']) ? sanitize_text_field(wp_unslash($_GET['lang'])) : 'en';
            
            // Get page configurations for the current language
            $ezhp_pages_config = array();
            $ezhp_existing_pages = array();
            $ezhp_existing_count = 0;
            
            if (function_exists('ezhp_get_automation_pages_config') && function_exists('ezhp_get_existing_automation_pages')) {
                $ezhp_pages_config = ezhp_get_automation_pages_config($ezhp_current_lang);
                
                // Extract slugs from config to check for existing pages
                $ezhp_config_slugs = array_column($ezhp_pages_config, 'slug');
                $ezhp_existing_pages = ezhp_get_existing_automation_pages($ezhp_config_slugs);
                $ezhp_existing_count = count($ezhp_existing_pages);
            }
            ?>

            <?php if ($ezhp_existing_count > 0) : ?>
            <div class="ezhp-existing-pages-notice" style="background: #fff; border: 1px solid #c3c4c7; border-left: 4px solid #72aee6; padding: 12px 16px; margin-bottom: 20px; max-width: 900px;">
                <h3 style="margin: 0 0 10px 0; font-size: 14px;">
                    <?php
                    printf(
                        /* translators: %d: number of existing pages */
                        esc_html(_n(
                            '%d page has already been created:',
                            '%d pages have already been created:',
                            $ezhp_existing_count,
                            'ez-horoscope'
                        )),
                        esc_html($ezhp_existing_count)
                    );
                    ?>
                </h3>
                <table class="widefat striped" style="margin-top: 10px;">
                    <thead>
                        <tr>
                            <th><?php esc_html_e('Page Title', 'ez-horoscope'); ?></th>
                            <th><?php esc_html_e('Slug', 'ez-horoscope'); ?></th>
                            <th><?php esc_html_e('Actions', 'ez-horoscope'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($ezhp_existing_pages as $ezhp_existing_slug => $ezhp_existing_page) : ?>
                        <tr>
                            <td><?php echo esc_html($ezhp_existing_page['title']); ?></td>
                            <td><code><?php echo esc_html($ezhp_existing_page['slug']); ?></code></td>
                            <td>
                                <a href="<?php echo esc_url($ezhp_existing_page['url']); ?>" target="_blank"><?php esc_html_e('View', 'ez-horoscope'); ?></a>
                                |
                                <a href="<?php echo esc_url($ezhp_existing_page['edit']); ?>" target="_blank"><?php esc_html_e('Edit', 'ez-horoscope'); ?></a>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
            <?php endif; ?>

            <p style="max-width:800px;">
                <?php esc_html_e('Quickly create all the pages you need for your horoscope website. Customize the page titles and slugs below, then click "Create Pages" to generate them automatically. Each page will contain the appropriate EZ Horoscope block, ready to display content.', 'ez-horoscope'); ?>
            </p>
            <p style="max-width:800px;">
                <?php esc_html_e('Uncheck any pages you don\'t want to create. If a page with the same slug already exists, a number will be appended (e.g., daily-horoscope-2).', 'ez-horoscope'); ?>
            </p>

            <table class="form-table" role="presentation" style="max-width: 900px;">
                <tr>
                    <th scope="row">
                        <label for="ezhp-language-select"><?php esc_html_e('Language', 'ez-horoscope'); ?></label>
                    </th>
                    <td>
                        <?php
                        $ezhp_languages = array(
                            'en' => 'English',
                            'ar' => 'العربية (Arabic)',
                            'az' => 'Azərbaycan (Azerbaijani)',
                            'bg' => 'Български (Bulgarian)',
                            'bn' => 'বাংলা (Bengali)',
                            'ca' => 'Català (Catalan)',
                            'cs' => 'Čeština (Czech)',
                            'da' => 'Dansk (Danish)',
                            'de' => 'Deutsch (German)',
                            'el' => 'Ελληνικά (Greek)',
                            'eo' => 'Esperanto',
                            'es' => 'Español (Spanish)',
                            'et' => 'Eesti (Estonian)',
                            'eu' => 'Euskara (Basque)',
                            'fa' => 'فارسی (Persian)',
                            'fi' => 'Suomi (Finnish)',
                            'fr' => 'Français (French)',
                            'ga' => 'Gaeilge (Irish)',
                            'gl' => 'Galego (Galician)',
                            'he' => 'עברית (Hebrew)',
                            'hi' => 'हिन्दी (Hindi)',
                            'hu' => 'Magyar (Hungarian)',
                            'id' => 'Bahasa Indonesia (Indonesian)',
                            'it' => 'Italiano (Italian)',
                            'ja' => '日本語 (Japanese)',
                            'ko' => '한국어 (Korean)',
                            'lt' => 'Lietuvių (Lithuanian)',
                            'lv' => 'Latviešu (Latvian)',
                            'ms' => 'Bahasa Melayu (Malay)',
                            'nb' => 'Norsk Bokmål (Norwegian)',
                            'nl' => 'Nederlands (Dutch)',
                            'pl' => 'Polski (Polish)',
                            'pt' => 'Português (Portuguese)',
                            'ro' => 'Română (Romanian)',
                            'ru' => 'Русский (Russian)',
                            'sk' => 'Slovenčina (Slovak)',
                            'sl' => 'Slovenščina (Slovenian)',
                            'sq' => 'Shqip (Albanian)',
                            'sv' => 'Svenska (Swedish)',
                            'th' => 'ไทย (Thai)',
                            'tl' => 'Tagalog (Filipino)',
                            'tr' => 'Türkçe (Turkish)',
                            'uk' => 'Українська (Ukrainian)',
                            'ur' => 'اردو (Urdu)',
                            'zh' => '中文 (Chinese)',
                        );
                        ?>
                        <select id="ezhp-language-select" name="ezhp_language" style="min-width: 250px;">
                            <?php foreach ($ezhp_languages as $ezhp_lang_code => $ezhp_lang_name) : ?>
                                <option value="<?php echo esc_attr($ezhp_lang_code); ?>" <?php selected($ezhp_lang_code, $ezhp_current_lang); ?>>
                                    <?php echo esc_html($ezhp_lang_name); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <p class="description">
                            <?php esc_html_e('Select the language for the horoscope content and page headings.', 'ez-horoscope'); ?>
                        </p>
                    </td>
                </tr>
            </table>

            <div id="ezhp-automation-messages"></div>

            <p style="margin-top: 20px; margin-bottom: 10px;">
                <a href="#" id="ezhp-select-all-new" class="button button-small"><?php esc_html_e('Select New Pages', 'ez-horoscope'); ?></a>
                <a href="#" id="ezhp-select-all" class="button button-small"><?php esc_html_e('Select All', 'ez-horoscope'); ?></a>
                <a href="#" id="ezhp-deselect-all" class="button button-small"><?php esc_html_e('Deselect All', 'ez-horoscope'); ?></a>
            </p>

            <table class="widefat ezhp-automation-table" style="max-width: 900px; margin-top: 20px;">
                <thead>
                    <tr>
                        <th style="width: 50px;"><?php esc_html_e('Create?', 'ez-horoscope'); ?></th>
                        <th style="width: 250px;"><?php esc_html_e('Page Title', 'ez-horoscope'); ?></th>
                        <th style="width: 250px;"><?php esc_html_e('Slug', 'ez-horoscope'); ?></th>
                        <th style="width: 200px;"><?php esc_html_e('Block', 'ez-horoscope'); ?></th>
                    </tr>
                </thead>
                <tbody id="ezhp-automation-grid">
                    <?php
                    foreach ($ezhp_pages_config as $ezhp_index => $ezhp_page) :
                    ?>
                        <tr data-index="<?php echo esc_attr($ezhp_index); ?>">
                            <td style="text-align: center;">
                            <?php $ezhp_page_exists = isset($ezhp_existing_pages[$ezhp_page['slug']]); ?>
                            <input type="checkbox" 
                                   name="ezhp_pages[<?php echo esc_attr($ezhp_index); ?>][create]" 
                                   class="ezhp-create-checkbox" 
                                   <?php checked(!$ezhp_page_exists); ?>>
                        </td>
                            <td>
                                <input type="text"
                                    name="ezhp_pages[<?php echo esc_attr($ezhp_index); ?>][title]"
                                    value="<?php echo esc_attr($ezhp_page['title']); ?>"
                                    class="regular-text ezhp-title-input"
                                    style="width: 100%;">
                            </td>
                            <td>
                            <input type="text" 
                                   name="ezhp_pages[<?php echo esc_attr($ezhp_index); ?>][slug]" 
                                   value="<?php echo esc_attr($ezhp_page['slug']); ?>" 
                                   class="regular-text ezhp-slug-input" 
                                   style="width: 100%;">
                            <input type="hidden" 
                                   name="ezhp_pages[<?php echo esc_attr($ezhp_index); ?>][block]" 
                                   value="<?php echo esc_attr($ezhp_page['block']); ?>">
                            <input type="hidden" 
                                   name="ezhp_pages[<?php echo esc_attr($ezhp_index); ?>][sign]" 
                                   value="<?php echo esc_attr($ezhp_page['sign']); ?>">
                            <?php if ($ezhp_page_exists) : ?>
                            <span class="ezhp-page-exists-badge" style="display: inline-block; margin-top: 4px; padding: 2px 6px; background: #dff0d8; color: #3c763d; font-size: 11px; border-radius: 3px;">
                                <?php esc_html_e('Exists', 'ez-horoscope'); ?>
                            </span>
                            <?php endif; ?>
                        </td>
                            <td>
                                <code><?php echo esc_html($ezhp_page['block']); ?></code>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>

            <p style="margin-top: 20px;">
                <button type="button" class="button button-primary" id="ezhp-create-pages-btn">
                    <?php esc_html_e('Create Pages', 'ez-horoscope'); ?>
                </button>
                <span id="ezhp-automation-spinner" class="spinner" style="float: none; margin-top: 0;"></span>
            </p>

            <div id="ezhp-automation-results" style="margin-top: 20px; max-width: 900px;"></div>

            <!-- Results Modal -->
            <div id="ezhp-automation-modal" class="ezhp-modal" style="display:none;">
                <div class="ezhp-modal-overlay"></div>
                <div class="ezhp-modal-container">
                    <div class="ezhp-modal-header">
                        <h2><?php esc_html_e('Pages Created', 'ez-horoscope'); ?></h2>
                        <button type="button" class="ezhp-modal-close" aria-label="<?php esc_attr_e('Close', 'ez-horoscope'); ?>">&times;</button>
                    </div>
                    <div class="ezhp-modal-body">
                        <div id="ezhp-modal-summary"></div>
                        <table class="widefat striped" id="ezhp-modal-results-table">
                            <thead>
                                <tr>
                                    <th><?php esc_html_e('Page Title', 'ez-horoscope'); ?></th>
                                    <th><?php esc_html_e('Slug', 'ez-horoscope'); ?></th>
                                    <th><?php esc_html_e('Status', 'ez-horoscope'); ?></th>
                                    <th><?php esc_html_e('Actions', 'ez-horoscope'); ?></th>
                                </tr>
                            </thead>
                            <tbody id="ezhp-modal-results-body">
                            </tbody>
                        </table>
                    </div>
                    <div class="ezhp-modal-footer">
                        <button type="button" class="button button-primary ezhp-modal-close"><?php esc_html_e('Close', 'ez-horoscope'); ?></button>
                    </div>
                </div>
            </div>
     </div>

        <!-- TAB: Utilities -->
        <div id="ezhp-tab-utilities" class="ezhp-tab-content" style="display:none;">
            <h2><?php esc_html_e( 'Cache Management', 'ez-horoscope' ); ?></h2>

            <p style="max-width: 800px;">
                <?php esc_html_e( 'Horoscope content is cached for one hour to improve performance. Use this tool to clear all cached horoscope data and force fresh content from the API on the next page load.', 'ez-horoscope' ); ?>
            </p>

            <p style="max-width: 800px; margin-bottom: 20px;">
                <strong><?php esc_html_e( 'Cached content types:', 'ez-horoscope' ); ?></strong>
                <?php esc_html_e( 'Daily Horoscopes, Weekly Horoscopes, Monthly Horoscopes, Horoscope Summaries, Horoscope Sections', 'ez-horoscope' ); ?>
            </p>

            <?php wp_nonce_field( 'ezhp_clear_cache_nonce', 'ezhp_cache_nonce' ); ?>

            <p>
                <button type="button" class="button button-primary" id="ezhp-clear-cache-btn">
                    <?php esc_html_e( 'Clear All Caches', 'ez-horoscope' ); ?>
                </button>
                <span id="ezhp-cache-spinner" class="spinner" style="float: none; margin-top: 0;"></span>
            </p>

            <div id="ezhp-cache-results" style="margin-top: 15px; max-width: 800px;"></div>
        </div>

    </div>

    <script>
        (function($) {
            const storageKey = 'ezhp-active-tab';

            function showTab(tabId) {
                $('.nav-tab-wrapper a').removeClass('nav-tab-active');
                $('.ezhp-tab-content').hide();
                $('.nav-tab-wrapper a[href="' + tabId + '"]').addClass('nav-tab-active');
                $(tabId).show();
            }

            // On click: save active tab
            $('.nav-tab-wrapper a').on('click', function(e) {
                e.preventDefault();
                const tabId = $(this).attr('href');
                localStorage.setItem(storageKey, tabId);
                showTab(tabId);
            });

            // On page load: restore last tab
            const savedTab = localStorage.getItem(storageKey);
            if (savedTab && $(savedTab).length) {
                showTab(savedTab);
            } else {
                showTab('#ezhp-tab-automation');  // default to Horoscope if nothing saved
            }
        })(jQuery);
    </script>

<?php
}
