<?php
// If this file is called directly, abort.
if (!defined('WPINC')) {
    die;
}

// Display typing text for this section
if (function_exists('aysa_display_typing_text_section')) {
    $seo_settings_text = "In this section, you can configure core SEO settings. This might include preferences for how Aysa handles sitemaps, robots.txt, or schema markup to ensure optimal technical SEO.";
    echo aysa_display_typing_text_section($seo_settings_text, 'seo-settings');
}

$seo_country_options = array('Romania', 'United States', 'United Kingdom', 'Germany', 'France', 'Italy', 'Spain');
$seo_country_regions = array(
    'Romania' => array('Bucharest', 'Ilfov', 'Cluj', 'Timis', 'Iasi', 'Constanta'),
    'United States' => array('California', 'Texas', 'Florida', 'New York', 'Illinois'),
    'United Kingdom' => array('England', 'Scotland', 'Wales', 'Northern Ireland'),
    'Germany' => array('Berlin', 'Bavaria', 'Hesse', 'Hamburg'),
    'France' => array('Ile-de-France', 'Provence-Alpes-Cote d Azur', 'Occitanie'),
    'Italy' => array('Lombardy', 'Lazio', 'Campania'),
    'Spain' => array('Madrid', 'Catalonia', 'Andalusia'),
);

if (function_exists('WC') && WC() && isset(WC()->countries)) {
    $wc_countries_obj = WC()->countries;
    if (is_object($wc_countries_obj) && method_exists($wc_countries_obj, 'get_countries') && method_exists($wc_countries_obj, 'get_states')) {
        $wc_countries = $wc_countries_obj->get_countries();
        if (is_array($wc_countries) && !empty($wc_countries)) {
            asort($wc_countries);
            $seo_country_options = array_values($wc_countries);
            $seo_country_regions = array();
            foreach ($wc_countries as $country_code => $country_name) {
                $states = $wc_countries_obj->get_states($country_code);
                $region_names = array();
                if (is_array($states) && !empty($states)) {
                    foreach ($states as $state_name) {
                        if (is_string($state_name) && $state_name !== '') {
                            $region_names[] = $state_name;
                        }
                    }
                }
                if (!empty($region_names)) {
                    $seo_country_regions[(string) $country_name] = array_values(array_unique($region_names));
                }
            }
        }
    }
}
?>

<div class="aysa-wizard-section">
    <div class="aysa-wizard-header">
            <h2>SEO Settings</h2>
            <p class="aysa-text-muted">Configure your SEO settings to optimize your website's visibility in search engines</p>
        <div class="aysa-info-box">
            <span class="dashicons dashicons-info-outline"></span>
            <p>These settings help determine where and how your website appears in search results. The more specific you are, the better we can optimize your content for your target audience.</p>
        </div>
    </div>

    <form id="aysa-seo-settings-form" method="post" action="<?php echo admin_url('admin-post.php'); ?>">
        <input type="hidden" name="action" value="aysa_save_wizard_data">
        <input type="hidden" name="step" value="seo-settings">
        <input type="hidden" name="nonce" value="<?php echo esc_attr(wp_create_nonce('aysa_nonce')); ?>">

        <div class="aysa-form-container">
            <!-- Search Engine Targeting -->
            <div class="aysa-card">
                <div class="aysa-card-header">
                    <span class="dashicons dashicons-search"></span>
                    <h3>Search Engine Targeting</h3>
                </div>

                <div class="aysa-form-group">
                    <label for="targeted_search_engine">Targeted Search Engine<span class="aysa-required">*</span></label>
                    <select name="targeted_search_engine" id="targeted_search_engine" class="aysa-select" required>
                        <option value="">...Select a Search Engine</option>
                        <!-- Search engines will be loaded dynamically -->
                    </select>
                    <p class="aysa-text-muted">Select the search engine where you want to optimize your website's presence.</p>
                </div>

                <div class="aysa-form-group">
                    <label for="targeted_country">Targeted Country<span class="aysa-required">*</span></label>
                    <select name="targeted_country" id="targeted_country" class="aysa-select" required>
                        <option value="">...Select a Country</option>
                        <!-- Countries will be loaded dynamically -->
                    </select>
                    <p class="aysa-text-muted">Choose the country where you want to focus your SEO efforts.</p>
                </div>

                <div class="aysa-form-group">
                    <label for="targeted_region">Targeted Region<span class="aysa-required">*</span></label>
                    <select name="targeted_region" id="targeted_region" class="aysa-select" required>
                        <option value="">...Select a Region</option>
                        <!-- Regions will be loaded dynamically based on country -->
                    </select>
                    <p class="aysa-text-muted">Specify the region or state where your target audience is located.</p>
                </div>

                <div class="aysa-form-group">
                    <label for="targeted_city">Targeted City</label>
                    <input type="text" name="targeted_city" id="targeted_city" class="aysa-input" placeholder="Enter city name">
                    <p class="aysa-text-muted">Enter the city where you want to optimize your SEO for local searches.</p>
                </div>
            </div>

            <!-- Language Settings -->
            <div class="aysa-card">
                <div class="aysa-card-header">
                    <span class="dashicons dashicons-admin-appearance"></span>
                    <h3>Language Settings</h3>
                </div>

                <div class="aysa-form-group">
                    <label for="primary_language">Primary Language<span class="aysa-required">*</span></label>
                    <select name="primary_language" id="primary_language" class="aysa-select" required>
                        <option value="">Select a Language</option>
                        <!-- Languages will be loaded dynamically -->
                    </select>
                    <p class="aysa-text-muted">Choose the primary language of your website's content.</p>
                </div>
            </div>
            
            <!-- Optimization Settings -->
            <div class="aysa-card">
                <div class="aysa-card-header">
                    <span class="dashicons dashicons-performance"></span>
                    <h3>Optimization Settings</h3>
                </div>
                
                <div class="aysa-form-group">
                    <label for="update_frequency">Keyword Refresh Frequency</label>
                    <select name="update_frequency" id="update_frequency" class="aysa-select">
                        <option value="">Select...</option>
                        <option value="daily">Daily</option>
                        <option value="weekly">Weekly</option>
                        <option value="monthly">Monthly</option>
                    </select>
                    <p class="aysa-text-muted">This controls how often AYSA refreshes your Google position tracking and related keyword data for this project, such as search volume and competition. A higher frequency, especially weekly or daily, can consume a lot of credits if you track many keywords, so it is usually not recommended for smaller plans or large keyword lists.</p>
                </div>
                
                <div class="aysa-form-group">
                    <label for="language_optimize">Language Optimization</label>
                    <select name="language_optimize" id="language_optimize" class="aysa-select">
                        <option value="">Select a Language</option>
                        <!-- Languages will be loaded dynamically -->
                    </select>
                    <p class="aysa-text-muted">Specify how your content language should be optimized for search engines.</p>
                </div>
                
                <div class="aysa-form-group">
                    <label for="device_optimize">Device Optimization</label>
                    <select name="device_optimize" id="device_optimize" class="aysa-select">
                        <option value="">Select...</option>
                        <option value="desktop">Desktop</option>
                        <option value="mobile">Mobile</option>
                        <option value="tablet">Tablet</option>
                        <option value="all">All Devices</option>
                    </select>
                    <p class="aysa-text-muted">Choose where your customers matter most to you right now: phone, desktop, tablet, or all devices.</p>
                </div>
            </div>
        </div>
    </form>
</div>

<style>
/* Enhanced styling with modern design */
.aysa-wizard-section {
    max-width: 100%;
    margin: 24px;
    padding: 0;
    font-family: 'Roboto', sans-serif;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.aysa-wizard-header {
    padding: 24px 32px;
    border-bottom: 1px solid #e0e0e0;
    display: block;
}

.aysa-wizard-header h2 {
    font-size: 24px;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 8px;
}

.aysa-text-muted {
    color: #666;
    font-size: 14px;
    line-height: 1.6;
    margin-bottom: 8px;
}

.aysa-info-box {
    background: #f8f9fa;
    border-left: 4px solid #0066ff;
    padding: 16px;
    border-radius: 4px;
    margin: 16px 0 0 0;
    display: flex;
    align-items: flex-start;
    gap: 16px;
}

.aysa-info-box .dashicons {
    font-size: 24px;
    color: #0066ff;
    width: 24px;
    height: 24px;
}

.aysa-info-box p {
    margin: 0;
    font-size: 14px;
    color: #1a1a1a;
    line-height: 1.6;
}

.aysa-form-container {
    padding: 32px;
}

.aysa-card {
    background: transparent;
    border-radius: 0;
    box-shadow: none;
    padding: 0;
    margin-bottom: 32px;
}

.aysa-card:hover {
    transform: none;
    box-shadow: none;
}

.aysa-card-header {
    margin-bottom: 24px;
    padding-bottom: 16px;
    border-bottom: 1px solid #e0e0e0;
    display: flex;
    align-items: center;
    gap: 16px;
}

.aysa-card-header .dashicons {
    font-size: 24px;
    width: 24px;
    height: 24px;
    color: #0066ff;
}

.aysa-card-header h3 {
    font-size: 20px;
    font-weight: 600;
    color: #1a1a1a;
    margin: 0;
}

.aysa-form-group {
    margin-bottom: 24px;
}

.aysa-form-group:last-child {
    margin-bottom: 0;
}

.aysa-form-group label {
    display: block;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 8px;
}

.aysa-required {
    color: #dc3545;
    margin-left: 4px;
}

.aysa-input,
.aysa-select,
.aysa-textarea {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #e0e0e0;
    border-radius: 4px;
    font-size: 14px;
    color: #1a1a1a;
    background-color: #fff;
}

.aysa-textarea {
    resize: vertical;
    min-height: 80px;
}

.aysa-select {
    background-image: none !important;
    background: white !important;
}

select.aysa-select::-ms-expand {
    display: none !important;
}

.aysa-select option::after,
.aysa-select option::before,
.aysa-select::after,
.aysa-select::before {
    display: none !important;
    content: none !important;
}

/* Pentru a elimina posibile icoane din interiorul select */
.aysa-select .dashicons,
.aysa-select span,
.aysa-select i {
    display: none !important;
}

.aysa-char-counter {
    text-align: right;
    font-size: 12px;
    color: #666;
    margin-top: 4px;
}

/* Status indicator styles */
.aysa-status-indicator {
    display: flex;
    align-items: center;
    font-size: 14px;
    font-weight: 500;
    padding: 4px 12px;
    border-radius: 4px;
    background-color: #e9f5ff;
    color: #0066ff;
    margin-bottom: 16px;
}

.aysa-status-indicator .dashicons {
    margin-right: 6px;
}

.aysa-status-error {
    background-color: #ffebee;
    color: #d32f2f;
}

.aysa-spinning {
    animation: aysa-spin 2s linear infinite;
}

@keyframes aysa-spin {
    to { transform: rotate(360deg); }
}

/* Responsive adjustments */
@media (max-width: 768px) {
    .aysa-wizard-section {
        margin: 16px;
    }
    
    .aysa-wizard-header,
    .aysa-form-container {
        padding: 20px;
    }
    
    .aysa-wizard-header h2 {
        font-size: 24px;
    }
    
    .aysa-card-header h3 {
        font-size: 18px;
    }
}
</style>

<script>
jQuery(document).ready(function($) {
    const setupNonce = '<?php echo wp_create_nonce('aysa_nonce'); ?>';
    const allCountries = <?php echo wp_json_encode(array_values($seo_country_options)); ?>;
    const countryRegions = <?php echo wp_json_encode($seo_country_regions); ?>;
    const phpProjectId = '<?php echo intval(get_option('aysa_project_id', 0)); ?>';
    const projectId = localStorage.getItem('aysa_project_id') || phpProjectId || '0';
    if (projectId && Number(projectId) > 0) {
        localStorage.setItem('aysa_project_id', projectId);
    }

    $('#aysa-seo-settings-form').append('<input type="hidden" name="project_id" value="' + String(projectId) + '">');
    $('<div id="settings-status" class="aysa-status-indicator"><span class="dashicons dashicons-yes"></span> Local mode: default SEO settings loaded</div>')
        .insertAfter('h2');

    function fillSelect($select, values) {
        values.forEach(function(v) {
            $select.append($('<option>', { value: v, text: v }));
        });
    }

    function fillLanguageSelect($select, languages) {
        const fullyOptimized = new Set(['Romanian', 'English']);
        const optimizedGroup = $('<optgroup>', { label: 'AI Optimised' });
        const wipGroup = $('<optgroup>', { label: 'AI Optimised (Work in progress)' });

        languages.forEach(function(lang) {
            const option = $('<option>', { value: lang, text: lang });
            if (fullyOptimized.has(lang)) {
                optimizedGroup.append(option);
            } else {
                wipGroup.append(option);
            }
        });

        $select.append(optimizedGroup).append(wipGroup);
    }

    function loadRegions(country) {
        const $region = $('#targeted_region');
        const regions = (country && countryRegions[country]) ? countryRegions[country] : [];
        $region.empty().append('<option value="">...Select a Region</option>');
        (regions.length ? regions : ['National']).forEach(function(region) {
            $region.append($('<option>', { value: region, text: region }));
        });
    }

    const allLanguages = [
        'Afar', 'Afrikaans', 'Akan', 'Albanian', 'Amharic', 'Arabic', 'Aragonese', 'Armenian', 'Assamese',
        'Avaric', 'Avestan', 'Aymara', 'Azerbaijani', 'Bambara', 'Bashkir', 'Basque', 'Belarusian', 'Bengali',
        'Bihari', 'Bislama', 'Bosnian', 'Breton', 'Bulgarian', 'Burmese', 'Catalan', 'Chamorro', 'Chechen',
        'Chichewa', 'Chinese', 'Church Slavic', 'Chuvash', 'Cornish', 'Corsican', 'Cree', 'Croatian', 'Czech',
        'Danish', 'Divehi', 'Dutch', 'Dzongkha', 'English', 'Esperanto', 'Estonian', 'Ewe', 'Faroese',
        'Fijian', 'Finnish', 'French', 'Fulah', 'Galician', 'Ganda', 'Georgian', 'German', 'Greek',
        'Guarani', 'Gujarati', 'Haitian Creole', 'Hausa', 'Hebrew', 'Herero', 'Hindi', 'Hiri Motu',
        'Hungarian', 'Icelandic', 'Ido', 'Igbo', 'Indonesian', 'Interlingua', 'Interlingue', 'Inuktitut',
        'Inupiaq', 'Irish', 'Italian', 'Japanese', 'Javanese', 'Kalaallisut', 'Kannada', 'Kanuri', 'Kashmiri',
        'Kazakh', 'Khmer', 'Kikuyu', 'Kinyarwanda', 'Kirghiz', 'Komi', 'Kongo', 'Korean', 'Kurdish',
        'Kwanyama', 'Lao', 'Latin', 'Latvian', 'Limburgish', 'Lingala', 'Lithuanian', 'Luba-Katanga',
        'Luxembourgish', 'Macedonian', 'Malagasy', 'Malay', 'Malayalam', 'Maltese', 'Manx', 'Maori',
        'Marathi', 'Marshallese', 'Mongolian', 'Nauru', 'Navajo', 'Ndonga', 'Nepali', 'North Ndebele',
        'Northern Sami', 'Norwegian', 'Norwegian Bokmal', 'Norwegian Nynorsk', 'Occitan', 'Ojibwa', 'Oriya',
        'Oromo', 'Ossetian', 'Pali', 'Pashto', 'Persian', 'Polish', 'Portuguese', 'Punjabi', 'Quechua',
        'Romanian', 'Romansh', 'Rundi', 'Russian', 'Samoan', 'Sango', 'Sanskrit', 'Sardinian', 'Scottish Gaelic',
        'Serbian', 'Shona', 'Sichuan Yi', 'Sindhi', 'Sinhala', 'Slovak', 'Slovenian', 'Somali', 'South Ndebele',
        'Southern Sotho', 'Spanish', 'Sundanese', 'Swahili', 'Swati', 'Swedish', 'Tagalog', 'Tahitian',
        'Tajik', 'Tamil', 'Tatar', 'Telugu', 'Thai', 'Tibetan', 'Tigrinya', 'Tonga', 'Tsonga', 'Tswana',
        'Turkish', 'Turkmen', 'Twi', 'Uighur', 'Ukrainian', 'Urdu', 'Uzbek', 'Venda', 'Vietnamese',
        'Volapuk', 'Walloon', 'Welsh', 'Western Frisian', 'Wolof', 'Xhosa', 'Yiddish', 'Yoruba', 'Zhuang', 'Zulu'
    ];

    // Populate static values (local mode)
    fillSelect($('#targeted_search_engine'), ['Google', 'Bing', 'Yahoo', 'DuckDuckGo']);
    fillLanguageSelect($('#primary_language'), allLanguages);
    fillLanguageSelect($('#language_optimize'), allLanguages);
    fillSelect($('#targeted_country'), allCountries);
    const defaultCountry = allCountries.indexOf('Romania') !== -1 ? 'Romania' : (allCountries[0] || '');
    loadRegions(defaultCountry);
    $('#targeted_country').val(defaultCountry);
    $('#targeted_search_engine').val('Google');
    $('#primary_language').val('Romanian');
    $('#language_optimize').val('Romanian');

    $('#targeted_country').on('change', function() {
        loadRegions($(this).val());
    });
    
    // Handle form submission
    if (!window.aysaWizardUseGlobalNavigation) {
    $('#aysa-next-step').on('click', function(e) {
        e.preventDefault();
        
        // Show loading state
        $(this).html('<span class="dashicons dashicons-update aysa-spinning"></span> Saving...').prop('disabled', true);

        const formData = $('#aysa-seo-settings-form').serialize();
        $.ajax({
            url: ajaxurl,
            type: 'POST',
            dataType: 'json',
            data: formData + '&action=aysa_save_wizard_data&step=seo-settings&nonce=' + encodeURIComponent(setupNonce),
            success: function(response) {
                if (!response || !response.success) {
                    const msg = response && response.data && response.data.message ? response.data.message : 'Failed to save SEO settings.';
                    alert(msg);
                    $('#aysa-next-step').html('Next <span class="dashicons dashicons-arrow-right-alt"></span>').prop('disabled', false);
                    return;
                }
                $('#aysa-next-step').html('<span class="dashicons dashicons-yes"></span> Saved!');
                setTimeout(function() {
                    window.location.href = '?page=aysa-setup-seo-profile&step=competition';
                }, 500);
            },
            error: function() {
                alert('Failed to save SEO settings. Please try again.');
                $('#aysa-next-step').html('Next <span class="dashicons dashicons-arrow-right-alt"></span>').prop('disabled', false);
            }
        });
    });
    
    // Handle previous button
    $('.prev-button, .prev, button:contains("Previous"), a:contains("Previous")').on('click', function(e) {
        e.preventDefault();
        window.location.href = '?page=aysa-setup-seo-profile&step=objectives';
    });
    
    // Last resort - add a direct click handler to the document for capturing clicks on the buttons
    $(document).on('click', 'button, a', function(e) {
        const buttonText = $(this).text().trim().toLowerCase();
        if (buttonText === 'next') {
            $('.next-button, .next, button:contains("Next"), a:contains("Next")').first().trigger('click');
        } else if (buttonText === 'previous') {
            $('.prev-button, .prev, button:contains("Previous"), a:contains("Previous")').first().trigger('click');
        }
    });
    }
});
</script>
