<?php

function visa_support_services_shortcode() {
    $options = get_option('visa_services_options');
    $countries = get_option('visa_countries_list', []);
    
    // Default countries if none exist
    if (empty($countries)) {
        $countries = [
            'usa' => ['label' => 'USA', 'code' => 'us'],
            'canada' => ['label' => 'Canada', 'code' => 'ca'],
            'uk' => ['label' => 'UK', 'code' => 'gb'],
            'schengen' => ['label' => 'Schengen', 'code' => 'eu'],
            'south_africa' => ['label' => 'South Africa', 'code' => 'za'],
            'india' => ['label' => 'India', 'code' => 'in'],
            'thailand' => ['label' => 'Thailand', 'code' => 'th'],
            'china' => ['label' => 'China', 'code' => 'cn'],
        ];
    }
    
    ob_start(); ?>
    <style>
        .visa-services-panel {display: flex; max-height: 500px;}
        .visa-sidebar {flex-shrink: 0;}
        .visa-content {flex: 1; overflow-y: auto; max-height: 500px; padding-right: 10px;}
        .visa-content::-webkit-scrollbar {width: 8px;}
        .visa-content::-webkit-scrollbar-track {background: #f1f1f1; border-radius: 4px;}
        .visa-content::-webkit-scrollbar-thumb {background: #c1c1c1; border-radius: 4px;}
        .visa-content::-webkit-scrollbar-thumb:hover {background: #a8a8a8;}

        .visa-country-flag {width: 24px; height: auto; margin-right: 8px; border-radius: 2px; box-shadow: 0 1px 3px rgba(0,0,0,0.2);}
        .visa-content .content-item h1, .visa-content .content-item h2, .visa-content .content-item h3, .visa-content .content-item h4, .visa-content .content-item h5, .visa-content .content-item h6 {color: #1e3a8a; font-weight: 600; line-height: 1.3; margin: 12px 0 8px 0; border-bottom: 2px solid #e5e7eb; padding-bottom: 6px;}
        .visa-content .content-item h1 {font-size: 24px;}
        .visa-content .content-item h2 {font-size: 22px;}
        .visa-content .content-item h3 {font-size: 20px;}
        .visa-content .content-item h4 {font-size: 18px;}
        .visa-content .content-item h5 {font-size: 16px;}
        .visa-content .content-item h6 {font-size: 14px;}
        .visa-content .content-item p {line-height: 1.5; margin: 0 0 8px 0; color: #374151; font-size: 17px; text-align: justify; word-spacing: 0.1em;}
        .visa-content .content-item p + p {margin-top: 4px;}
        .visa-content .content-item ul {margin: 8px 0; padding-left: 0; list-style: none;}
        .visa-content .content-item ul li {position: relative; padding-left: 25px; margin-bottom: 4px; line-height: 1.4; color: #374151; font-size: 17px;}
        .visa-content .content-item ul li::before {content: "★"; color: #fbbf24; font-size: 17px; position: absolute; left: 0; top: 0;}
        .visa-content .content-item ol {margin: 8px 0; padding-left: 20px; counter-reset: item;}
        .visa-content .content-item ol li {display: block; margin-bottom: 4px; padding-left: 15px; line-height: 1.4; color: #374151; font-size: 17px; position: relative; counter-increment: item;}
        .visa-content .content-item ol li::before {content: counter(item) "."; color: #1e3a8a; font-weight: bold; position: absolute; left: -15px; top: 0;}
        .visa-content .content-item ul ul li::before {content: "☆"; color: #94a3b8;}
        .visa-content .content-item strong, .visa-content .content-item b {color: #1e3a8a; font-weight: 600;}
        .visa-content .content-item em, .visa-content .content-item i {color: #6b7280; font-style: italic;}
        .visa-content .content-item a {color: #2563eb; text-decoration: none; border-bottom: 1px solid transparent; transition: all 0.2s ease;}
        .visa-content .content-item a:hover {color: #1d4ed8; border-bottom-color: #1d4ed8;}
        .visa-content .content-item blockquote {border-left: 4px solid #1e3a8a; margin: 20px 0; padding: 15px 20px; background: #f8fafc; font-style: italic; color: #4b5563; border-radius: 0 4px 4px 0;}
        .visa-content .content-item table {width: 100%; border-collapse: collapse; margin: 20px 0; font-size: 17px;}
        .visa-content .content-item table th, .visa-content .content-item table td {border: 1px solid #e5e7eb; padding: 10px; text-align: left;}
        .visa-content .content-item table th {background-color: #1e3a8a; color: white; font-weight: 600;}
        .visa-content .content-item table tr:nth-child(even) {background-color: #f9fafb;}
        .visa-content .content-item code {background-color: #f3f4f6; color: #dc2626; padding: 2px 6px; border-radius: 3px; font-size: 17px;}
        .visa-content .content-item pre {background-color: #1f2937; color: #f9fafb; padding: 15px; border-radius: 5px; overflow-x: auto; margin: 20px 0; font-size: 17px; line-height: 1.4;}
        .visa-content .content-item img {max-width: 100%; height: auto; border-radius: 5px; margin: 10px 0; box-shadow: 0 2px 8px rgba(0,0,0,0.1);}
        .visa-content .content-item hr {border: none; height: 2px; background: linear-gradient(90deg, #1e3a8a, transparent); margin: 25px 0;}
        .visa-content .content-item .wp-caption-text {font-size: 17px; color: #6b7280; font-style: italic; text-align: center; margin-top: 5px;}
        .content-item {display: none;}
        .content-item.active {display: block;}
        @media (max-width: 768px) {
    .visa-services-panel {flex-direction: column; max-height: none;}
    .visa-sidebar {display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 20px; width: 100%;}
    .visa-content {max-height: none; padding-right: 0; overflow-y: visible;}
    .sidebar-item {flex: 0 0 auto; min-width: 120px;}
}
    </style>
    <div class="visa-services-panel">
        <div class="visa-sidebar">
            <?php
            $first = true;
            foreach ($countries as $key => $country) {
                $flag_url = "https://flagcdn.com/w40/" . strtolower($country['code']) . ".png";
                echo '<div class="sidebar-item ' . ($first ? 'active' : '') . '" data-tab="' . esc_attr($key) . '">
                        <img class="visa-country-flag" src="' . esc_url($flag_url) . '" alt="' . esc_attr($country['label']) . ' flag" onerror="this.style.display=\'none\'">
                        <span>' . esc_html($country['label']) . '</span>
                    </div>';
                $first = false;
            }
            ?>
        </div>
        <div class="visa-content">
            <?php
            $first = true;
            foreach ($countries as $key => $country) {
                $title = $options[$key . '_title'] ?? $country['label'];
                $content = $options[$key . '_content'] ?? 'Details coming soon...';
                echo '<div id="' . esc_attr($key) . '" class="content-item ' . ($first ? 'active' : '') . '">
                        <a href="https://lwegatech.net/beaute-sauvage-safaris/get-in-touch/" target="_blank" style="display: inline-block; margin-bottom: 15px; padding: 10px 20px; background-color: #1e3a8a; color: white; text-decoration: none; border-radius: 5px; font-weight: bold;">Get in touch with Consultant</a>
                        <h3>' . esc_html($title) . '</h3>
                        ' . wpautop(wp_kses_post($content)) . '
                      </div>';
                $first = false;
            }
            ?>
        </div>
    </div>

    <script>
        jQuery(document).ready(function($) {
            $('.sidebar-item').click(function() {
                $('.sidebar-item').removeClass('active');
                $(this).addClass('active');
                var tab = $(this).data('tab');
                $('.content-item').removeClass('active');
                $('#' + tab).addClass('active');
            });
        });
    </script>
    <?php
    return ob_get_clean();
}
add_shortcode('visa_support_services', 'visa_support_services_shortcode');

function visa_services_admin_menu() {
    add_options_page(
        'Visa Support Settings',
        'Visa Services',
        'manage_options',
        'visa-support-settings',
        'visa_services_admin_page'
    );
}
add_action('admin_menu', 'visa_services_admin_menu');

function visa_services_admin_page() {
    // Increase limits for this operation
    ini_set('memory_limit', '256M');
    set_time_limit(300);
    
    if (isset($_GET['updated']) && $_GET['updated'] === 'true') {
        echo '<div class="notice notice-success is-dismissible"><p>Settings saved successfully!</p></div>';
    }
    
    // Handle country management
    if (isset($_POST['action'])) {
        if ($_POST['action'] === 'add_country' && wp_verify_nonce($_POST['visa_country_nonce'], 'visa_country_action')) {
            $countries = get_option('visa_countries_list', []);
            $new_key = sanitize_key($_POST['country_key']);
            $new_label = sanitize_text_field($_POST['country_label']);
            $new_code = sanitize_text_field($_POST['country_code']);
            
            if (!empty($new_key) && !empty($new_label) && !empty($new_code)) {
                $countries[$new_key] = ['label' => $new_label, 'code' => $new_code];
                update_option('visa_countries_list', $countries);
                echo '<div class="notice notice-success is-dismissible"><p>Country added successfully!</p></div>';
            }
        } elseif ($_POST['action'] === 'remove_country' && wp_verify_nonce($_POST['visa_country_nonce'], 'visa_country_action')) {
            $countries = get_option('visa_countries_list', []);
            $remove_key = sanitize_key($_POST['country_to_remove']);
            
            if (isset($countries[$remove_key])) {
                unset($countries[$remove_key]);
                update_option('visa_countries_list', $countries);
                
                // Also remove related content
                $options = get_option('visa_services_options', []);
                unset($options[$remove_key . '_title']);
                unset($options[$remove_key . '_content']);
                update_option('visa_services_options', $options);
                
                echo '<div class="notice notice-success is-dismissible"><p>Country removed successfully!</p></div>';
            }
        }
    }
    
    $countries = get_option('visa_countries_list', []);
    
    // Default countries if none exist
    if (empty($countries)) {
        $countries = [
            'usa' => ['label' => 'USA', 'code' => 'us'],
            'canada' => ['label' => 'Canada', 'code' => 'ca'],
            'uk' => ['label' => 'UK', 'code' => 'gb'],
            'schengen' => ['label' => 'Schengen', 'code' => 'eu'],
            'south_africa' => ['label' => 'South Africa', 'code' => 'za'],
            'india' => ['label' => 'India', 'code' => 'in'],
            'thailand' => ['label' => 'Thailand', 'code' => 'th'],
            'china' => ['label' => 'China', 'code' => 'cn'],
        ];
        update_option('visa_countries_list', $countries);
    }
    ?>
    <div class="wrap">
        <h1>Visa Support Services Settings</h1>
        
        <!-- Country Management Section -->
        <div style="background: white; padding: 20px; margin: 20px 0; border: 1px solid #ccd0d4; border-radius: 4px;">
            <h2>Manage Countries</h2>
            
            <!-- Add New Country -->
            <h3>Add New Country</h3>
            <form method="post" style="margin-bottom: 20px;">
                <input type="hidden" name="action" value="add_country">
                <?php wp_nonce_field('visa_country_action', 'visa_country_nonce'); ?>
                <table class="form-table">
                    <tr>
                        <th scope="row">Country Key</th>
                        <td><input type="text" name="country_key" placeholder="e.g., australia" required style="width: 200px;"></td>
                    </tr>
                    <tr>
                        <th scope="row">Country Label</th>
                        <td><input type="text" name="country_label" placeholder="e.g., Australia" required style="width: 200px;"></td>
                    </tr>
                    <tr>
                        <th scope="row">Country Code</th>
                        <td><input type="text" name="country_code" placeholder="e.g., au (ISO 3166-1 alpha-2)" required style="width: 200px;"></td>
                    </tr>
                </table>
                <?php submit_button('Add Country', 'secondary'); ?>
            </form>
            
            <!-- Existing Countries -->
            <h3>Existing Countries</h3>
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th>Flag</th>
                        <th>Key</th>
                        <th>Label</th>
                        <th>Code</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($countries as $key => $country): 
                        $flag_url = "https://flagcdn.com/w40/" . strtolower($country['code']) . ".png";
                    ?>
                    <tr>
                        <td><img src="<?php echo esc_url($flag_url); ?>" alt="<?php echo esc_attr($country['label']); ?> flag" style="width: 24px; height: auto; border-radius: 2px;"></td>
                        <td><?php echo esc_html($key); ?></td>
                        <td><?php echo esc_html($country['label']); ?></td>
                        <td><?php echo esc_html($country['code']); ?></td>
                        <td>
                            <form method="post" style="display: inline;">
                                <input type="hidden" name="action" value="remove_country">
                                <input type="hidden" name="country_to_remove" value="<?php echo esc_attr($key); ?>">
                                <?php wp_nonce_field('visa_country_action', 'visa_country_nonce'); ?>
                                <input type="submit" class="button button-small" value="Remove" onclick="return confirm('Are you sure you want to remove this country? This will also delete all related content.');">
                            </form>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- Content Settings -->
        <form method="post" action="options.php">
            <?php
            settings_fields('visa_services_options');
            do_settings_sections('visa-support-settings');
            wp_nonce_field('visa_services_save', 'visa_services_nonce');
            submit_button();
            ?>
        </form>
    </div>
    <?php
}

function visa_services_settings_init() {
    register_setting('visa_services_options', 'visa_services_options', [
        'sanitize_callback' => 'visa_services_sanitize',
        'show_in_rest' => false
    ]);

    $countries = get_option('visa_countries_list', []);
    
    // Default countries if none exist
    if (empty($countries)) {
        $countries = [
            'usa' => ['label' => 'USA', 'code' => 'us'],
            'canada' => ['label' => 'Canada', 'code' => 'ca'],
            'uk' => ['label' => 'UK', 'code' => 'gb'],
            'schengen' => ['label' => 'Schengen', 'code' => 'eu'],
            'south_africa' => ['label' => 'South Africa', 'code' => 'za'],
            'india' => ['label' => 'India', 'code' => 'in'],
            'thailand' => ['label' => 'Thailand', 'code' => 'th'],
            'china' => ['label' => 'China', 'code' => 'cn'],
        ];
    }

    foreach ($countries as $key => $country) {
        add_settings_section("visa_services_{$key}", $country['label'], null, 'visa-support-settings');

        add_settings_field(
            "{$key}_title",
            'Title',
            'visa_services_text_field',
            'visa-support-settings',
            "visa_services_{$key}",
            ['name' => "{$key}_title", 'default' => $country['label']]
        );

        add_settings_field(
            "{$key}_content",
            'Content',
            'visa_services_editor_field',
            'visa-support-settings',
            "visa_services_{$key}",
            ['name' => "{$key}_content"]
        );
    }
}
add_action('admin_init', 'visa_services_settings_init');

function visa_services_text_field($args) {
    $options = get_option('visa_services_options');
    $value = $options[$args['name']] ?? $args['default'] ?? '';
    echo '<input type="text" class="regular-text" name="visa_services_options[' . esc_attr($args['name']) . ']" value="' . esc_attr($value) . '">';
}

function visa_services_editor_field($args) {
    $options = get_option('visa_services_options');
    $content = $options[$args['name']] ?? '';
    
    wp_editor(
        wp_kses_post($content),
        'visa_services_' . $args['name'],
        [
            'textarea_name' => 'visa_services_options[' . esc_attr($args['name']) . ']',
            'textarea_rows' => 8,
            'media_buttons' => true,
            'teeny' => false,
            'wpautop' => true,
            'tinymce' => [
                'toolbar1' => 'formatselect,bold,italic,underline,strikethrough,|,bullist,numlist,|,link,unlink,|,undo,redo',
                'toolbar2' => 'alignleft,aligncenter,alignright,alignjustify,|,outdent,indent,|,forecolor,backcolor,|,removeformat'
            ]
        ]
    );
}

function visa_services_sanitize($input) {
    // Verify nonce for security
    if (!wp_verify_nonce($_POST['visa_services_nonce'] ?? '', 'visa_services_save')) {
        wp_die('Security check failed. Please try again.');
    }
    
    if (!current_user_can('manage_options')) {
        wp_die('You do not have sufficient permissions to access this page.');
    }
    
    $sanitized = [];
    
    // Define allowed HTML tags for content fields
    $allowed_html = wp_kses_allowed_html('post');
    $allowed_html['style'] = [];
    $allowed_html['script'] = [];
    
    foreach ($input as $key => $value) {
        if (strpos($key, 'content') !== false) {
            // Use more permissive filtering for content fields
            $sanitized[$key] = wp_kses($value, $allowed_html);
        } else {
            // Sanitize text fields
            $sanitized[$key] = sanitize_text_field($value);
        }
    }
    
    return $sanitized;
}

function visa_services_save_custom() {
    // Additional security checks
    if (!current_user_can('manage_options')) {
        wp_die('Unauthorized access.');
    }
    
    if (!wp_verify_nonce($_POST['visa_services_nonce'] ?? '', 'visa_services_save')) {
        wp_die('Security check failed.');
    }
    
    // Process and save the data
    $options = visa_services_sanitize($_POST['visa_services_options'] ?? []);
    update_option('visa_services_options', $options);
    
    // Redirect with success message
    wp_redirect(admin_url('options-general.php?page=visa-support-settings&updated=true'));
    exit;
}

function visa_support_enqueue_assets() {
    // No longer need Font Awesome as we're using country flags
    
    // Enqueue jQuery if not already loaded
    wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'visa_support_enqueue_assets');

// Add admin styles for better editor experience
function visa_services_admin_styles() {
    $current_screen = get_current_screen();
    if ($current_screen && $current_screen->id === 'settings_page_visa-support-settings') {
        ?>
        <style>
            .form-table th {width: 150px; vertical-align: top; padding-top: 20px;}
            .form-table td {padding: 15px 10px;}
            .wp-editor-container {margin-top: 10px;}
        </style>
        <?php
    }
}
add_action('admin_head', 'visa_services_admin_styles');