<?php
/**
 * Safari Booking Form WordPress Shortcode
 * Usage: [safari_booking_form]
 * 
 * Add this code to your theme's functions.php file or create a custom plugin
 */

// Register the shortcode
add_shortcode('safari_booking_form', 'safari_booking_form_shortcode');

function safari_booking_form_shortcode($atts = array()) {
    // Extract attributes with defaults
    $atts = shortcode_atts(array(
        'admin_email' => get_option('admin_email'),
        'form_title' => 'Plan Your Dream Safari',
        'form_subtitle' => 'Tell us about your interests and we\'ll craft the perfect adventure for you'
    ), $atts);

    // Start output buffering
    ob_start();
    ?>
    
    <div id="safari-booking-form-container" class="safari-form-container">
        <style>
            
        </style>

        <div class="safari-form-wrapper">
            <!-- Header -->
            <div class="safari-header">
                <h1><?php echo esc_html($atts['form_title']); ?></h1>
                <p><?php echo esc_html($atts['form_subtitle']); ?></p>
            </div>

            <form id="safari-booking-form" method="post" action="">
                <?php wp_nonce_field('safari_booking_form', 'safari_nonce'); ?>
                
                <!-- Contact Information -->
                <div class="safari-section">
                    <h2>Contact Information</h2>
                    <div class="safari-grid">
                        <div class="safari-form-group">
                            <label class="safari-label">First Name <span class="required">*</span></label>
                            <input type="text" name="first_name" required class="safari-input">
                        </div>
                        <div class="safari-form-group">
                            <label class="safari-label">Last Name <span class="required">*</span></label>
                            <input type="text" name="last_name" required class="safari-input">
                        </div>
                        <div class="safari-form-group">
                            <label class="safari-label">Email Address <span class="required">*</span></label>
                            <input type="email" name="email" required class="safari-input">
                        </div>
                        <div class="safari-form-group">
                            <label class="safari-label">Phone Number <span class="required">*</span></label>
                            <input type="tel" name="phone" required class="safari-input">
                        </div>
                    </div>
                    <div class="safari-form-group">
                        <label class="safari-label">Your Country</label>
                        <input type="text" name="visitor_country" placeholder="Where are you traveling from?" class="safari-input">
                    </div>
                </div>

                <!-- Trip Details -->
                <div class="safari-section">
                    <h2>Trip Details</h2>
                    <div class="safari-grid">
                        <div class="safari-form-group">
                            <label class="safari-label">Preferred Country <span class="required">*</span></label>
                            <select name="preferred_country" required class="safari-select" id="preferred-country">
                                <option value="">Select a country</option>
                                <option value="Uganda">Uganda</option>
                                <option value="Rwanda">Rwanda</option>
                            </select>
                        </div>
                        <div class="safari-form-group">
                            <label class="safari-label">Budget Range</label>
                            <select name="budget" class="safari-select">
                                <option value="">Select budget range</option>
                                <option value="Under $1,000">Under $1,000</option>
                                <option value="$1,000 - $2,500">$1,000 - $2,500</option>
                                <option value="$2,500 - $5,000">$2,500 - $5,000</option>
                                <option value="$5,000 - $10,000">$5,000 - $10,000</option>
                                <option value="Over $10,000">Over $10,000</option>
                                <option value="Flexible/Discuss with agent">Flexible/Discuss with agent</option>
                            </select>
                        </div>
                        <div class="safari-form-group">
                            <label class="safari-label">Preferred Start Date</label>
                            <input type="date" name="start_date" class="safari-input">
                        </div>
                        <div class="safari-form-group">
                            <label class="safari-label">Preferred End Date</label>
                            <input type="date" name="end_date" class="safari-input">
                        </div>
                        <div class="safari-form-group">
                            <label class="safari-label">Group Size</label>
                            <select name="group_size" class="safari-select">
                                <?php for($i = 1; $i <= 20; $i++): ?>
                                <option value="<?php echo $i; ?>"><?php echo $i; ?> <?php echo $i === 1 ? 'person' : 'people'; ?></option>
                                <?php endfor; ?>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Experience Selection -->
                <div class="safari-section">
                    <h2>Choose Your Safari Experiences</h2>
                    <p style="color: #6b7280; margin-bottom: 1.5rem;">Select the activities that interest you most. We'll ask follow-up questions to customize each experience.</p>
                    
                    <div class="experience-grid">
                        <div class="experience-card" onclick="toggleExperience('cultural-tours')">
                            <div style="display: flex; align-items: center; gap: 0.75rem;">
                                <span style="font-size: 1.5rem;">🎭</span>
                                <span style="font-weight: 600;">Cultural Tours</span>
                            </div>
                        </div>
                        <div class="experience-card" onclick="toggleExperience('city-tours')">
                            <div style="display: flex; align-items: center; gap: 0.75rem;">
                                <span style="font-size: 1.5rem;">🏙️</span>
                                <span style="font-weight: 600;">City Tours</span>
                            </div>
                        </div>
                        <div class="experience-card" onclick="toggleExperience('game-drives')">
                            <div style="display: flex; align-items: center; gap: 0.75rem;">
                                <span style="font-size: 1.5rem;">🦁</span>
                                <span style="font-weight: 600;">Game Drives</span>
                            </div>
                        </div>
                        <div class="experience-card" onclick="toggleExperience('bird-watching')">
                            <div style="display: flex; align-items: center; gap: 0.75rem;">
                                <span style="font-size: 1.5rem;">🦅</span>
                                <span style="font-weight: 600;">Bird Watching</span>
                            </div>
                        </div>
                        <div class="experience-card" onclick="toggleExperience('water-rafting')">
                            <div style="display: flex; align-items: center; gap: 0.75rem;">
                                <span style="font-size: 1.5rem;">🚣</span>
                                <span style="font-weight: 600;">Water Rafting</span>
                            </div>
                        </div>
                        <div class="experience-card" onclick="toggleExperience('gorilla-trekking')">
                            <div style="display: flex; align-items: center; gap: 0.75rem;">
                                <span style="font-size: 1.5rem;">🦍</span>
                                <span style="font-weight: 600;">Gorilla Trekking</span>
                            </div>
                        </div>
                    </div>

                    <!-- Experience Details Sections -->
                    <div id="cultural-tours-details" class="experience-details" style="display: none;">
                        <h3>🎭 Cultural Tours - Tell us more</h3>
                        <div class="safari-grid">
                            <div class="safari-form-group">
                                <label class="safari-label">What aspects of local culture interest you most?</label>
                                <select name="cultural_interest" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Traditional ceremonies">Traditional ceremonies</option>
                                    <option value="Local crafts and markets">Local crafts and markets</option>
                                    <option value="Music and dance">Music and dance</option>
                                    <option value="Historical sites">Historical sites</option>
                                    <option value="Community interaction">Community interaction</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">How many days would you like to dedicate to cultural experiences?</label>
                                <select name="cultural_duration" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="1 day">1 day</option>
                                    <option value="2-3 days">2-3 days</option>
                                    <option value="4-5 days">4-5 days</option>
                                    <option value="More than 5 days">More than 5 days</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">What level of community interaction do you prefer?</label>
                                <select name="cultural_interaction" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Observational visits">Observational visits</option>
                                    <option value="Hands-on participation">Hands-on participation</option>
                                    <option value="Homestay experience">Homestay experience</option>
                                    <option value="Mixed approach">Mixed approach</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div id="city-tours-details" class="experience-details" style="display: none;">
                        <h3>🏙️ City Tours - Tell us more</h3>
                        <div class="safari-grid">
                            <div class="safari-form-group">
                                <label class="safari-label">What city attractions interest you most?</label>
                                <select name="city_focus" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Historical landmarks">Historical landmarks</option>
                                    <option value="Museums and galleries">Museums and galleries</option>
                                    <option value="Local markets">Local markets</option>
                                    <option value="Modern architecture">Modern architecture</option>
                                    <option value="Nightlife and restaurants">Nightlife and restaurants</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">How would you prefer to explore the city?</label>
                                <select name="city_transport" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Walking tours">Walking tours</option>
                                    <option value="Private vehicle">Private vehicle</option>
                                    <option value="Public transport">Public transport</option>
                                    <option value="Bicycle tours">Bicycle tours</option>
                                    <option value="Mixed transportation">Mixed transportation</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">What pace do you prefer for city exploration?</label>
                                <select name="city_pace" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Relaxed and leisurely">Relaxed and leisurely</option>
                                    <option value="Moderate with breaks">Moderate with breaks</option>
                                    <option value="Comprehensive and active">Comprehensive and active</option>
                                    <option value="Flexible based on energy">Flexible based on energy</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div id="game-drives-details" class="experience-details" style="display: none;">
                        <h3>🦁 Game Drives - Tell us more</h3>
                        <div class="safari-grid">
                            <div class="safari-form-group">
                                <label class="safari-label">Which wildlife are you most excited to see?</label>
                                <select name="wildlife_priority" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Big Five">Big Five (Lion, Leopard, Elephant, Buffalo, Rhino)</option>
                                    <option value="Primates">Primates</option>
                                    <option value="Birds">Birds</option>
                                    <option value="All wildlife equally">All wildlife equally</option>
                                    <option value="Specific animals">Specific animals (please specify in comments)</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">What time of day do you prefer for game drives?</label>
                                <select name="drive_time" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Early morning">Early morning</option>
                                    <option value="Late afternoon/evening">Late afternoon/evening</option>
                                    <option value="Full day drives">Full day drives</option>
                                    <option value="Night drives">Night drives</option>
                                    <option value="Flexible timing">Flexible timing</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">What type of safari vehicle do you prefer?</label>
                                <select name="vehicle_type" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Open-sided 4WD">Open-sided 4WD</option>
                                    <option value="Closed 4WD with pop-up roof">Closed 4WD with pop-up roof</option>
                                    <option value="Luxury safari vehicle">Luxury safari vehicle</option>
                                    <option value="No preference">No preference</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div id="bird-watching-details" class="experience-details" style="display: none;">
                        <h3>🦅 Bird Watching - Tell us more</h3>
                        <div class="safari-grid">
                            <div class="safari-form-group">
                                <label class="safari-label">What is your bird watching experience level?</label>
                                <select name="birding_level" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Beginner">Beginner</option>
                                    <option value="Intermediate">Intermediate</option>
                                    <option value="Advanced">Advanced</option>
                                    <option value="Professional/Serious birder">Professional/Serious birder</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">Which habitats interest you most for birding?</label>
                                <select name="bird_habitat" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Tropical forests">Tropical forests</option>
                                    <option value="Wetlands and lakes">Wetlands and lakes</option>
                                    <option value="Savannah grasslands">Savannah grasslands</option>
                                    <option value="Mountain forests">Mountain forests</option>
                                    <option value="All habitats">All habitats</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">Do you need birding equipment provided?</label>
                                <select name="birding_equipment" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Binoculars only">Binoculars only</option>
                                    <option value="Binoculars and field guide">Binoculars and field guide</option>
                                    <option value="Complete birding kit">Complete birding kit</option>
                                    <option value="I have my own equipment">I have my own equipment</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div id="water-rafting-details" class="experience-details" style="display: none;">
                        <h3>🚣 Water Rafting - Tell us more</h3>
                        <div class="safari-grid">
                            <div class="safari-form-group">
                                <label class="safari-label">What is your white water rafting experience?</label>
                                <select name="rafting_experience" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Complete beginner">Complete beginner</option>
                                    <option value="Some experience">Some experience</option>
                                    <option value="Experienced rafter">Experienced rafter</option>
                                    <option value="Expert level">Expert level</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">What grade of rapids are you comfortable with?</label>
                                <select name="rapids_grade" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Grade 1-2 (Easy)">Grade 1-2 (Easy)</option>
                                    <option value="Grade 3-4 (Moderate)">Grade 3-4 (Moderate)</option>
                                    <option value="Grade 5+ (Extreme)">Grade 5+ (Extreme)</option>
                                    <option value="Let the guide decide">Let the guide decide</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">How long would you like your rafting experience?</label>
                                <select name="rafting_duration" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Half day">Half day</option>
                                    <option value="Full day">Full day</option>
                                    <option value="Multi-day expedition">Multi-day expedition</option>
                                    <option value="Flexible">Flexible</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <div id="gorilla-trekking-details" class="experience-details" style="display: none;">
                        <h3>🦍 Gorilla Trekking - Tell us more</h3>
                        <div class="safari-grid">
                            <div class="safari-form-group">
                                <label class="safari-label">How would you rate your fitness level?</label>
                                <select name="fitness_level" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Low - prefer easy walks">Low - prefer easy walks</option>
                                    <option value="Moderate - can handle some hiking">Moderate - can handle some hiking</option>
                                    <option value="High - enjoy challenging treks">High - enjoy challenging treks</option>
                                    <option value="Very high - extreme adventures welcome">Very high - extreme adventures welcome</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">What type of gorilla trekking interests you?</label>
                                <select name="trekking_preference" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Mountain gorillas">Mountain gorillas</option>
                                    <option value="Lowland gorillas">Lowland gorillas</option>
                                    <option value="Both if possible">Both if possible</option>
                                    <option value="Whatever is available">Whatever is available</option>
                                </select>
                            </div>
                            <div class="safari-form-group">
                                <label class="safari-label">What size trekking group do you prefer?</label>
                                <select name="group_preference" class="safari-select">
                                    <option value="">Please select an option</option>
                                    <option value="Small group (2-4 people)">Small group (2-4 people)</option>
                                    <option value="Medium group (5-6 people)">Medium group (5-6 people)</option>
                                    <option value="Large group (7-8 people)">Large group (7-8 people)</option>
                                    <option value="Private trekking">Private trekking</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <input type="hidden" name="selected_experiences" id="selected-experiences" value="">
                </div>

                <!-- Additional Information -->
                <div class="safari-section">
                    <h2>Additional Information</h2>
                    <div class="safari-form-group">
                        <label class="safari-label">Special Requests or Interests</label>
                        <textarea name="special_requests" rows="4" class="safari-textarea" placeholder="Tell us about any specific wildlife you'd like to see, photography interests, celebration occasions, or other special requests..."></textarea>
                    </div>
                    <div class="safari-grid">
                        <div class="safari-form-group">
                            <label class="safari-label">Dietary Requirements</label>
                            <input type="text" name="dietary_requirements" class="safari-input" placeholder="Vegetarian, vegan, allergies, etc.">
                        </div>
                        <div class="safari-form-group">
                            <label class="safari-label">Accessibility Needs</label>
                            <input type="text" name="accessibility" class="safari-input" placeholder="Any mobility, vision, hearing, or other accessibility considerations">
                        </div>
                    </div>
                </div>

                <!-- Submit Button -->
                <div class="submit-section">
                    <button type="submit" name="submit_safari_form" class="safari-btn">
                        Submit Safari Inquiry
                    </button>
                    <p class="submit-note">
                        We'll review your preferences and contact you within 24 hours with a customized safari proposal
                    </p>
                </div>
            </form>
        </div>

        <script>
            // Global variables
            let countries = ['Uganda', 'Rwanda'];
            let selectedExperiences = [];

            // Admin functions
            function toggleAdmin() {
                const content = document.getElementById('admin-content');
                const arrow = document.getElementById('admin-arrow');
                
                if (content.style.display === 'none' || content.style.display === '') {
                    content.style.display = 'block';
                    content.classList.add('active');
                    arrow.textContent = '▲';
                } else {
                    content.style.display = 'none';
                    content.classList.remove('active');
                    arrow.textContent = '▼';
                }
            }

            function addCountry() {
                const input = document.getElementById('new-country');
                const newCountry = input.value.trim();
                
                if (newCountry && !countries.includes(newCountry)) {
                    countries.push(newCountry);
                    updateCountryTags();
                    updateCountrySelect();
                    input.value = '';
                }
            }

            function removeCountry(countryToRemove) {
                if (countries.length > 1) {
                    countries = countries.filter(country => country !== countryToRemove);
                    updateCountryTags();
                    updateCountrySelect();
                    
                    // Reset preferred country if it was removed
                    const preferredSelect = document.getElementById('preferred-country');
                    if (preferredSelect.value === countryToRemove) {
                        preferredSelect.value = '';
                    }
                }
            }

            function updateCountryTags() {
                const tagsContainer = document.getElementById('country-tags');
                tagsContainer.innerHTML = '';
                
                countries.forEach(country => {
                    const tag = document.createElement('span');
                    tag.className = 'country-tag';
                    tag.innerHTML = `
                        ${country}
                        ${countries.length > 1 ? `<button type="button" class="country-remove" onclick="removeCountry('${country}')">×</button>` : ''}
                    `;
                    tagsContainer.appendChild(tag);
                });
            }

            function updateCountrySelect() {
                const select = document.getElementById('preferred-country');
                const currentValue = select.value;
                
                // Clear existing options except the first one
                select.innerHTML = '<option value="">Select a country</option>';
                
                // Add countries
                countries.forEach(country => {
                    const option = document.createElement('option');
                    option.value = country;
                    option.textContent = country;
                    if (country === currentValue) {
                        option.selected = true;
                    }
                    select.appendChild(option);
                });
            }

            // Experience functions
            function toggleExperience(experienceId) {
                const card = event.currentTarget;
                const detailsSection = document.getElementById(experienceId + '-details');
                
                if (selectedExperiences.includes(experienceId)) {
                    // Remove experience
                    selectedExperiences = selectedExperiences.filter(exp => exp !== experienceId);
                    card.classList.remove('selected');
                    detailsSection.style.display = 'none';
                } else {
                    // Add experience
                    selectedExperiences.push(experienceId);
                    card.classList.add('selected');
                    detailsSection.style.display = 'block';
                }
                
                // Update hidden field
                document.getElementById('selected-experiences').value = selectedExperiences.join(',');
            }

            // Event listeners
            document.getElementById('new-country').addEventListener('keypress', function(e) {
                if (e.key === 'Enter') {
                    e.preventDefault();
                    addCountry();
                }
            });

            // Form validation
            document.getElementById('safari-booking-form').addEventListener('submit', function(e) {
                if (selectedExperiences.length === 0) {
                    e.preventDefault();
                    alert('Please select at least one safari experience.');
                    return false;
                }
            });
        </script>
    </div>

    <?php
    return ob_get_clean();
}

// Handle form submission
add_action('init', 'handle_safari_form_submission');

function handle_safari_form_submission() {
    if (isset($_POST['submit_safari_form']) && wp_verify_nonce($_POST['safari_nonce'], 'safari_booking_form')) {
        
        // Sanitize form data
        $form_data = array(
            'first_name' => sanitize_text_field($_POST['first_name']),
            'last_name' => sanitize_text_field($_POST['last_name']),
            'email' => sanitize_email($_POST['email']),
            'phone' => sanitize_text_field($_POST['phone']),
            'visitor_country' => sanitize_text_field($_POST['visitor_country']),
            'preferred_country' => sanitize_text_field($_POST['preferred_country']),
            'budget' => sanitize_text_field($_POST['budget']),
            'start_date' => sanitize_text_field($_POST['start_date']),
            'end_date' => sanitize_text_field($_POST['end_date']),
            'group_size' => intval($_POST['group_size']),
            'selected_experiences' => sanitize_text_field($_POST['selected_experiences']),
            'special_requests' => sanitize_textarea_field($_POST['special_requests']),
            'dietary_requirements' => sanitize_text_field($_POST['dietary_requirements']),
            'accessibility' => sanitize_text_field($_POST['accessibility']),
        );

        // Sanitize experience-specific data
        $experience_fields = array(
            'cultural_interest', 'cultural_duration', 'cultural_interaction',
            'city_focus', 'city_transport', 'city_pace',
            'wildlife_priority', 'drive_time', 'vehicle_type',
            'birding_level', 'bird_habitat', 'birding_equipment',
            'rafting_experience', 'rapids_grade', 'rafting_duration',
            'fitness_level', 'trekking_preference', 'group_preference'
        );

        foreach ($experience_fields as $field) {
            if (isset($_POST[$field])) {
                $form_data[$field] = sanitize_text_field($_POST[$field]);
            }
        }

        // Save to database (optional)
        safari_save_booking_data($form_data);

        // Send email notification
        safari_send_booking_email($form_data);

        // Redirect with success message
        wp_redirect(add_query_arg('safari_submitted', '1', wp_get_referer()));
        exit;
    }
}

// Save booking data to database
function safari_save_booking_data($form_data) {
    global $wpdb;
    
    // Create table if it doesn't exist
    $table_name = $wpdb->prefix . 'safari_bookings';
    
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        first_name varchar(100) NOT NULL,
        last_name varchar(100) NOT NULL,
        email varchar(100) NOT NULL,
        phone varchar(50) NOT NULL,
        visitor_country varchar(100),
        preferred_country varchar(100) NOT NULL,
        budget varchar(100),
        start_date date,
        end_date date,
        group_size int(3),
        selected_experiences text,
        experience_details longtext,
        special_requests longtext,
        dietary_requirements text,
        accessibility text,
        submission_date datetime DEFAULT CURRENT_TIMESTAMP,
        status varchar(20) DEFAULT 'pending',
        PRIMARY KEY (id)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
    // Prepare experience details JSON
    $experience_details = array();
    $experience_fields = array(
        'cultural_interest', 'cultural_duration', 'cultural_interaction',
        'city_focus', 'city_transport', 'city_pace',
        'wildlife_priority', 'drive_time', 'vehicle_type',
        'birding_level', 'bird_habitat', 'birding_equipment',
        'rafting_experience', 'rapids_grade', 'rafting_duration',
        'fitness_level', 'trekking_preference', 'group_preference'
    );

    foreach ($experience_fields as $field) {
        if (!empty($form_data[$field])) {
            $experience_details[$field] = $form_data[$field];
        }
    }

    // Insert data
    $wpdb->insert(
        $table_name,
        array(
            'first_name' => $form_data['first_name'],
            'last_name' => $form_data['last_name'],
            'email' => $form_data['email'],
            'phone' => $form_data['phone'],
            'visitor_country' => $form_data['visitor_country'],
            'preferred_country' => $form_data['preferred_country'],
            'budget' => $form_data['budget'],
            'start_date' => !empty($form_data['start_date']) ? $form_data['start_date'] : null,
            'end_date' => !empty($form_data['end_date']) ? $form_data['end_date'] : null,
            'group_size' => $form_data['group_size'],
            'selected_experiences' => $form_data['selected_experiences'],
            'experience_details' => json_encode($experience_details),
            'special_requests' => $form_data['special_requests'],
            'dietary_requirements' => $form_data['dietary_requirements'],
            'accessibility' => $form_data['accessibility']
        ),
        array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s', '%s', '%s', '%s')
    );
}

// Send email notification
function safari_send_booking_email($form_data) {
    $admin_email = get_option('admin_email');
    $site_name = get_bloginfo('name');
    
    // Prepare email content
    $subject = "New Safari Booking Inquiry - {$form_data['first_name']} {$form_data['last_name']}";
    
    $message = "New safari booking inquiry received:\n\n";
    $message .= "CONTACT INFORMATION:\n";
    $message .= "Name: {$form_data['first_name']} {$form_data['last_name']}\n";
    $message .= "Email: {$form_data['email']}\n";
    $message .= "Phone: {$form_data['phone']}\n";
    $message .= "Country: {$form_data['visitor_country']}\n\n";
    
    $message .= "TRIP DETAILS:\n";
    $message .= "Preferred Country: {$form_data['preferred_country']}\n";
    $message .= "Budget: {$form_data['budget']}\n";
    $message .= "Start Date: {$form_data['start_date']}\n";
    $message .= "End Date: {$form_data['end_date']}\n";
    $message .= "Group Size: {$form_data['group_size']} people\n\n";
    
    $message .= "SELECTED EXPERIENCES: {$form_data['selected_experiences']}\n\n";
    
    if (!empty($form_data['special_requests'])) {
        $message .= "SPECIAL REQUESTS:\n{$form_data['special_requests']}\n\n";
    }
    
    if (!empty($form_data['dietary_requirements'])) {
        $message .= "DIETARY REQUIREMENTS: {$form_data['dietary_requirements']}\n";
    }
    
    if (!empty($form_data['accessibility'])) {
        $message .= "ACCESSIBILITY NEEDS: {$form_data['accessibility']}\n";
    }
    
    $message .= "\n---\nSubmitted from: " . home_url();
    
    // Send to admin
    wp_mail($admin_email, $subject, $message);
    
    // Send confirmation to customer
    $customer_subject = "Thank you for your Safari Inquiry - $site_name";
    $customer_message = "Dear {$form_data['first_name']},\n\n";
    $customer_message .= "Thank you for your safari inquiry! We have received your request and will review your preferences carefully.\n\n";
    $customer_message .= "We will contact you within 24 hours with a customized safari proposal based on your interests.\n\n";
    $customer_message .= "Your inquiry details:\n";
    $customer_message .= "Preferred Country: {$form_data['preferred_country']}\n";
    $customer_message .= "Selected Experiences: {$form_data['selected_experiences']}\n";
    $customer_message .= "Group Size: {$form_data['group_size']} people\n\n";
    $customer_message .= "If you have any immediate questions, please don't hesitate to contact us.\n\n";
    $customer_message .= "Best regards,\n$site_name Team";
    
    wp_mail($form_data['email'], $customer_subject, $customer_message);
}

// Display success message
add_action('wp_head', 'safari_success_message_script');

function safari_success_message_script() {
    if (isset($_GET['safari_submitted'])) {
        echo "
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            alert('Thank you! Your safari inquiry has been submitted successfully. We will contact you within 24 hours with a customized proposal.');
        });
        </script>
        ";
    }
}

// Add admin menu for viewing bookings
function safari_admin_menu() {
    add_menu_page(
        'Safari Bookings',
        'Safari Bookings',
        'manage_options',
        'safari-bookings',
        'safari_admin_dashboard',
        'dashicons-palmtree',
        30
    );
    
    add_submenu_page(
        'safari-bookings',
        'Custom Bookings',
        'Custom Bookings',
        'manage_options',
        'safari-custom-bookings',
        'safari_custom_bookings_page'
    );
    
    add_submenu_page(
        'safari-bookings',
        'Standard Bookings',
        'Standard Bookings',
        'manage_options',
        'safari-standard-bookings',
        'safari_standard_bookings_page'
    );
}

// Main dashboard page
function safari_admin_dashboard() {
    global $wpdb;
    
    // Get statistics
    $custom_table = $wpdb->prefix . 'safari_bookings';
    $standard_table = $wpdb->prefix . 'safari_standard_bookings';
    
    $custom_total = $wpdb->get_var("SELECT COUNT(*) FROM $custom_table");
    $standard_total = $wpdb->get_var("SELECT COUNT(*) FROM $standard_table");
    $custom_pending = $wpdb->get_var("SELECT COUNT(*) FROM $custom_table WHERE status = 'pending'");
    $standard_pending = $wpdb->get_var("SELECT COUNT(*) FROM $standard_table WHERE status = 'pending'");
    
    // Get recent bookings
    $recent_custom = $wpdb->get_results("SELECT * FROM $custom_table ORDER BY submission_date DESC LIMIT 5");
    $recent_standard = $wpdb->get_results("SELECT * FROM $standard_table ORDER BY submission_date DESC LIMIT 5");
    
    ?>
    <div class="wrap safari-admin-wrap">
        <h1>Safari Bookings Dashboard</h1>
        
        <style>
        .safari-admin-wrap {
            background: #f1f1f1;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
        }
        
        .safari-stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .safari-stat-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 25px;
            border-radius: 12px;
            text-align: center;
            box-shadow: 0 8px 16px rgba(0,0,0,0.1);
            transform: translateY(0);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .safari-stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 24px rgba(0,0,0,0.15);
        }
        
        .safari-stat-card.custom {
            background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%);
        }
        
        .safari-stat-card.standard {
            background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
        }
        
        .safari-stat-card.pending {
            background: linear-gradient(135deg, #ffa726 0%, #fb8c00 100%);
        }
        
        .safari-stat-number {
            font-size: 3em;
            font-weight: bold;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }
        
        .safari-stat-label {
            font-size: 1.1em;
            text-transform: uppercase;
            letter-spacing: 1px;
            opacity: 0.9;
        }
        
        .safari-recent-section {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-top: 30px;
        }
        
        .safari-recent-card {
            background: white;
            border-radius: 12px;
            padding: 25px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
            border-top: 4px solid;
        }
        
        .safari-recent-card.custom {
            border-top-color: #ff6b6b;
        }
        
        .safari-recent-card.standard {
            border-top-color: #4ecdc4;
        }
        
        .safari-recent-card h3 {
            margin-top: 0;
            color: #2c3e50;
            display: flex;
            align-items: center;
            gap: 10px;
        }
        
        .safari-recent-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }
        
        .safari-recent-list li {
            padding: 12px 0;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .safari-recent-list li:last-child {
            border-bottom: none;
        }
        
        .safari-booking-info {
            flex: 1;
        }
        
        .safari-booking-name {
            font-weight: 600;
            color: #2c3e50;
        }
        
        .safari-booking-details {
            font-size: 0.9em;
            color: #7f8c8d;
            margin-top: 3px;
        }
        
        .safari-status-badge {
            padding: 4px 12px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .safari-status-badge.pending {
            background: #fff3cd;
            color: #856404;
        }
        
        .safari-status-badge.confirmed {
            background: #d4edda;
            color: #155724;
        }
        
        .safari-status-badge.completed {
            background: #cce5ff;
            color: #004085;
        }
        
        .safari-status-badge.cancelled {
            background: #f8d7da;
            color: #721c24;
        }
        
        .safari-action-buttons {
            margin-top: 20px;
            text-align: center;
        }
        
        .safari-action-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 12px 25px;
            border: none;
            border-radius: 25px;
            text-decoration: none;
            display: inline-block;
            margin: 0 10px;
            font-weight: 600;
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .safari-action-btn:hover {
            color: white;
            transform: translateY(-2px);
            box-shadow: 0 6px 16px rgba(0,0,0,0.2);
        }
        
        .safari-action-btn.custom {
            background: linear-gradient(135deg, #ff6b6b 0%, #ff8e53 100%);
        }
        
        .safari-action-btn.standard {
            background: linear-gradient(135deg, #4ecdc4 0%, #44a08d 100%);
        }
        </style>
        
        <!-- Statistics Cards -->
        <div class="safari-stats-grid">
            <div class="safari-stat-card custom">
                <div class="safari-stat-number"><?php echo $custom_total; ?></div>
                <div class="safari-stat-label">Custom Bookings</div>
            </div>
            
            <div class="safari-stat-card standard">
                <div class="safari-stat-number"><?php echo $standard_total; ?></div>
                <div class="safari-stat-label">Standard Bookings</div>
            </div>
            
            <div class="safari-stat-card pending">
                <div class="safari-stat-number"><?php echo $custom_pending + $standard_pending; ?></div>
                <div class="safari-stat-label">Pending Reviews</div>
            </div>
        </div>
        
        <!-- Recent Bookings -->
        <div class="safari-recent-section">
            <div class="safari-recent-card custom">
                <h3>
                    <span style="color: #ff6b6b; font-size: 1.2em;">🎨</span>
                    Recent Custom Bookings
                </h3>
                <?php if ($recent_custom): ?>
                    <ul class="safari-recent-list">
                        <?php foreach ($recent_custom as $booking): ?>
                            <li>
                                <div class="safari-booking-info">
                                    <div class="safari-booking-name"><?php echo esc_html($booking->first_name . ' ' . $booking->last_name); ?></div>
                                    <div class="safari-booking-details"><?php echo esc_html($booking->preferred_country); ?> • <?php echo esc_html($booking->selected_experiences); ?></div>
                                </div>
                                <span class="safari-status-badge <?php echo $booking->status; ?>"><?php echo ucfirst($booking->status); ?></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p>No custom bookings yet.</p>
                <?php endif; ?>
            </div>
            
            <div class="safari-recent-card standard">
                <h3>
                    <span style="color: #4ecdc4; font-size: 1.2em;">📦</span>
                    Recent Standard Bookings
                </h3>
                <?php if ($recent_standard): ?>
                    <ul class="safari-recent-list">
                        <?php foreach ($recent_standard as $booking): ?>
                            <li>
                                <div class="safari-booking-info">
                                    <div class="safari-booking-name"><?php echo esc_html($booking->first_name . ' ' . $booking->last_name); ?></div>
                                    <div class="safari-booking-details"><?php echo esc_html($booking->package_name); ?> • <?php echo $booking->group_size; ?> people</div>
                                </div>
                                <span class="safari-status-badge <?php echo $booking->status; ?>"><?php echo ucfirst($booking->status); ?></span>
                            </li>
                        <?php endforeach; ?>
                    </ul>
                <?php else: ?>
                    <p>No standard bookings yet.</p>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Action Buttons -->
        <div class="safari-action-buttons">
            <a href="<?php echo admin_url('admin.php?page=safari-custom-bookings'); ?>" class="safari-action-btn custom">
                View All Custom Bookings
            </a>
            <a href="<?php echo admin_url('admin.php?page=safari-standard-bookings'); ?>" class="safari-action-btn standard">
                View All Standard Bookings
            </a>
        </div>
    </div>
    <?php
}

// Custom bookings page (existing functionality)
function safari_custom_bookings_page() {
    // Your existing admin page code goes here
    // Just rename the function call in the existing code
    safari_display_bookings_table('custom');
}

// Standard bookings page
function safari_standard_bookings_page() {
    safari_display_bookings_table('standard');
}

// Generic function to display bookings table
function safari_display_bookings_table($type) {
    global $wpdb;
    
    $table_name = $type === 'custom' ? 
        $wpdb->prefix . 'safari_bookings' : 
        $wpdb->prefix . 'safari_standard_bookings';
    
    $page_title = $type === 'custom' ? 'Custom Bookings' : 'Standard Bookings';
    
    // Handle actions
    safari_handle_booking_actions($type);
    
    // Setup pagination
    $items_per_page = 20;
    $current_page = max(1, isset($_GET['paged']) ? absint($_GET['paged']) : 1);
    $offset = ($current_page - 1) * $items_per_page;
    
    // Build query
    $where = '';
    if (isset($_GET['s']) && !empty($_GET['s'])) {
        $search = sanitize_text_field($_GET['s']);
        $where = $wpdb->prepare(" WHERE first_name LIKE %s OR last_name LIKE %s OR email LIKE %s", 
            "%{$search}%", "%{$search}%", "%{$search}%");
    }
    
    $total_items = $wpdb->get_var("SELECT COUNT(*) FROM $table_name $where");
    $total_pages = ceil($total_items / $items_per_page);
    
    $bookings = $wpdb->get_results("SELECT * FROM $table_name $where ORDER BY submission_date DESC LIMIT $offset, $items_per_page");
    
    // Define available statuses
    $status_options = array(
        'pending' => 'Pending',
        'confirmed' => 'Confirmed',
        'completed' => 'Completed',
        'cancelled' => 'Cancelled'
    );
    
    echo '<div class="wrap safari-booking-wrap">';
    echo '<h1 class="wp-heading-inline">' . $page_title . '</h1>';
    
    // Add lively styling
    echo '<style>
        .safari-booking-wrap {
            background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
            padding: 30px;
            border-radius: 15px;
            margin: 20px 0;
            min-height: 80vh;
        }
        
        .safari-booking-wrap h1 {
            color: #2c3e50;
            text-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        .safari-search-section {
            background: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 25px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        
        .safari-table-container {
            background: white;
            border-radius: 12px;
            overflow: hidden;
            box-shadow: 0 8px 24px rgba(0,0,0,0.1);
        }
        
        .safari-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .safari-table th {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px 12px;
            text-align: left;
            font-weight: 600;
            text-transform: uppercase;
            font-size: 0.85em;
            letter-spacing: 0.5px;
        }
        
        .safari-table td {
            padding: 15px 12px;
            border-bottom: 1px solid #eef2f7;
            vertical-align: middle;
        }
        
        .safari-table tbody tr {
            transition: background-color 0.3s ease;
            cursor: pointer;
        }
        
        .safari-table tbody tr:hover {
            background: linear-gradient(135deg, #f8f9ff 0%, #e8f4fd 100%);
        }
        
        .safari-status-badge {
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.8em;
            font-weight: 600;
            text-transform: uppercase;
            display: inline-block;
        }
        
        .safari-action-btn {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 8px 16px;
            border-radius: 20px;
            text-decoration: none;
            font-size: 0.85em;
            font-weight: 600;
            margin: 2px;
            transition: all 0.3s ease;
            display: inline-block;
        }
        
        .safari-action-btn:hover {
            color: white;
            transform: scale(1.05);
            box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        }
        
        .safari-action-btn.delete {
            background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
        }
        
        .safari-bulk-actions {
            background: white;
            padding: 15px 20px;
            border-radius: 10px 10px 0 0;
            border-bottom: 2px solid #f0f0f0;
        }
        
        .safari-pagination {
            background: white;
            padding: 15px 20px;
            border-radius: 0 0 10px 10px;
            text-align: center;
        }
        </style>';
    
    // Search form
    echo '<div class="safari-search-section">';
    echo '<form method="get" style="display: flex; align-items: center; gap: 15px;">';
    echo '<input type="hidden" name="page" value="' . ($type === 'custom' ? 'safari-custom-bookings' : 'safari-standard-bookings') . '" />';
    echo '<input type="search" name="s" value="' . (isset($_GET['s']) ? esc_attr($_GET['s']) : '') . '" placeholder="Search bookings..." style="padding: 8px 15px; border-radius: 20px; border: 1px solid #ddd; width: 300px;" />';
    echo '<button type="submit" class="safari-action-btn">Search</button>';
    if (isset($_GET['s'])) {
        echo '<a href="' . admin_url('admin.php?page=' . ($type === 'custom' ? 'safari-custom-bookings' : 'safari-standard-bookings')) . '" class="safari-action-btn" style="background: linear-gradient(135deg, #95a5a6 0%, #7f8c8d 100%);">Clear</a>';
    }
    echo '</form>';
    echo '</div>';
    
    // Display bookings table
    if ($bookings) {
        echo '<div class="safari-table-container">';
        
        echo '<form method="post" action="' . admin_url('admin.php?page=' . ($type === 'custom' ? 'safari-custom-bookings' : 'safari-standard-bookings')) . '">';
        echo '<input type="hidden" name="page" value="' . ($type === 'custom' ? 'safari-custom-bookings' : 'safari-standard-bookings') . '" />';
        wp_nonce_field('safari_bulk_action', 'safari_nonce');
        
        // Bulk actions
        echo '<div class="safari-bulk-actions">';
        echo '<select name="bulk_action" style="padding: 6px 10px; border-radius: 5px; border: 1px solid #ddd;">';
        echo '<option value="">Bulk Actions</option>';
        echo '<option value="delete">Delete</option>';
        foreach ($status_options as $status_value => $status_label) {
            echo '<option value="' . $status_value . '">Mark as ' . $status_label . '</option>';
        }
        echo '</select>';
        submit_button('Apply', 'action', 'bulk_submit', false, array('class' => 'safari-action-btn', 'style' => 'margin-left: 10px;'));
        echo '</div>';
        
        echo '<table class="safari-table">';
        echo '<thead>';
        echo '<tr>';
        echo '<th><input type="checkbox" id="select-all-bookings" /></th>';
        echo '<th>Date</th>';
        echo '<th>Name</th>';
        echo '<th>Email</th>';
        if ($type === 'custom') {
            echo '<th>Country</th>';
            echo '<th>Experiences</th>';
        } else {
            echo '<th>Package</th>';
            echo '<th>Group Size</th>';
        }
        echo '<th>Status</th>';
        echo '<th>Actions</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
        
        foreach ($bookings as $booking) {
            echo '<tr class="booking-row" data-booking-id="' . $booking->id . '" data-type="' . $type . '">';
            echo '<td><input type="checkbox" name="booking_ids[]" value="' . $booking->id . '" /></td>';
            echo '<td>' . date('M j, Y', strtotime($booking->submission_date)) . '</td>';
            echo '<td class="view-booking-details" data-booking-id="' . $booking->id . '" data-type="' . $type . '">' . esc_html($booking->first_name . ' ' . $booking->last_name) . '</td>';
            echo '<td><a href="mailto:' . esc_attr($booking->email) . '">' . esc_html($booking->email) . '</a></td>';
            
            if ($type === 'custom') {
                echo '<td>' . esc_html($booking->preferred_country) . '</td>';
                echo '<td>' . esc_html($booking->selected_experiences) . '</td>';
            } else {
                echo '<td>' . esc_html($booking->package_name) . '</td>';
                echo '<td>' . esc_html($booking->group_size) . ' people</td>';
            }
            
            // Status
            echo '<td><span class="safari-status-badge ' . $booking->status . '">' . ucfirst($booking->status) . '</span></td>';
            
            echo '<td>';
            echo '<a href="#" class="safari-action-btn view-booking-details" data-booking-id="' . $booking->id . '" data-type="' . $type . '">View</a>';
            echo '<a href="' . admin_url('admin.php?page=' . ($type === 'custom' ? 'safari-custom-bookings' : 'safari-standard-bookings') . '&action=delete&booking_id=' . $booking->id . '&type=' . $type . '&_wpnonce=' . wp_create_nonce('safari_delete_booking')) . '" 
                   class="safari-action-btn delete" 
                   onclick="return confirm(\'Are you sure you want to delete this booking?\')">Delete</a>';
            echo '</td>';
            echo '</tr>';
        }
        
        echo '</tbody></table>';
        
        // Pagination
        if ($total_pages > 1) {
            echo '<div class="safari-pagination">';
            echo paginate_links(array(
                'base' => add_query_arg('paged', '%#%'),
                'format' => '',
                'prev_text' => '« Previous',
                'next_text' => 'Next »',
                'total' => $total_pages,
                'current' => $current_page
            ));
            echo '</div>';
        }
        
        echo '</form>';
        echo '</div>';
    } else {
        echo '<div style="background: white; padding: 40px; text-align: center; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.1);">';
        echo '<p style="font-size: 1.2em; color: #7f8c8d;">No bookings found.</p>';
        echo '</div>';
    }
    
    // Add the modal popup
    safari_add_booking_modal();
    
    // Add JavaScript
    safari_add_admin_scripts($type);
    
    echo '</div>';
}

// Handle form submission for standard bookings
add_action('init', 'handle_standard_safari_form_submission');

function handle_standard_safari_form_submission() {
    if (isset($_POST['submit_standard_safari_form']) && wp_verify_nonce($_POST['standard_safari_nonce'], 'standard_safari_booking_form')) {
        
        // Sanitize form data
        $form_data = array(
            'first_name' => sanitize_text_field($_POST['first_name']),
            'last_name' => sanitize_text_field($_POST['last_name']),
            'email' => sanitize_email($_POST['email']),
            'phone' => sanitize_text_field($_POST['phone']),
            'visitor_country' => sanitize_text_field($_POST['visitor_country']),
            'package_name' => sanitize_text_field($_POST['package_name']),
            'package_url' => esc_url_raw($_POST['package_url']),
            'start_date' => sanitize_text_field($_POST['start_date']),
            'group_size' => intval($_POST['group_size']),
            'dietary_requirements' => sanitize_text_field($_POST['dietary_requirements']),
            'additional_needs' => sanitize_textarea_field($_POST['additional_needs']),
        );

        // Save to database
        safari_save_standard_booking_data($form_data);

        // Send email notification
        safari_send_standard_booking_email($form_data);

        // Redirect with success message
        wp_redirect(add_query_arg('standard_safari_submitted', '1', wp_get_referer()));
        exit;
    }
}

// Create standard bookings table
function safari_create_standard_bookings_table() {
    global $wpdb;
    
    $table_name = $wpdb->prefix . 'safari_standard_bookings';
    $charset_collate = $wpdb->get_charset_collate();
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id mediumint(9) NOT NULL AUTO_INCREMENT,
        first_name varchar(100) NOT NULL,
        last_name varchar(100) NOT NULL,
        email varchar(100) NOT NULL,
        phone varchar(50) NOT NULL,
        visitor_country varchar(100),
        package_name varchar(200) NOT NULL,
        package_url text,
        start_date date,
        group_size int(3) DEFAULT 1,
        dietary_requirements text,
        additional_needs longtext,
        submission_date datetime DEFAULT CURRENT_TIMESTAMP,
        status varchar(20) DEFAULT 'pending',
        PRIMARY KEY (id)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
}

// Save standard booking data
function safari_save_standard_booking_data($form_data) {
    global $wpdb;
    
    // Create table if needed
    safari_create_standard_bookings_table();
    
    $table_name = $wpdb->prefix . 'safari_standard_bookings';
    
    // Insert data
    $wpdb->insert(
        $table_name,
        array(
            'first_name' => $form_data['first_name'],
            'last_name' => $form_data['last_name'],
            'email' => $form_data['email'],
            'phone' => $form_data['phone'],
            'visitor_country' => $form_data['visitor_country'],
            'package_name' => $form_data['package_name'],
            'package_url' => $form_data['package_url'],
            'start_date' => !empty($form_data['start_date']) ? $form_data['start_date'] : null,
            'group_size' => $form_data['group_size'],
            'dietary_requirements' => $form_data['dietary_requirements'],
            'additional_needs' => $form_data['additional_needs']
        ),
        array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%s', '%s')
    );
}

// Send standard booking email
function safari_send_standard_booking_email($form_data) {
    $admin_email = get_option('admin_email');
    $site_name = get_bloginfo('name');
    
    // Admin email
    $subject = "New Standard Safari Booking - {$form_data['first_name']} {$form_data['last_name']}";
    
    $message = "New standard safari booking received:\n\n";
    $message .= "CONTACT INFORMATION:\n";
    $message .= "Name: {$form_data['first_name']} {$form_data['last_name']}\n";
    $message .= "Email: {$form_data['email']}\n";
    $message .= "Phone: {$form_data['phone']}\n";
    $message .= "Country: {$form_data['visitor_country']}\n\n";
    
    $message .= "BOOKING DETAILS:\n";
    $message .= "Package: {$form_data['package_name']}\n";
    $message .= "Package URL: {$form_data['package_url']}\n";
    $message .= "Preferred Start Date: {$form_data['start_date']}\n";
    $message .= "Group Size: {$form_data['group_size']} people\n\n";
    
    if (!empty($form_data['dietary_requirements'])) {
        $message .= "DIETARY REQUIREMENTS: {$form_data['dietary_requirements']}\n";
    }
    
    if (!empty($form_data['additional_needs'])) {
        $message .= "ADDITIONAL NEEDS:\n{$form_data['additional_needs']}\n\n";
    }
    
    $message .= "\n---\nSubmitted from: " . home_url();
    
    wp_mail($admin_email, $subject, $message);
    
    // Customer confirmation
    $customer_subject = "Your Safari Booking Confirmation - $site_name";
    $customer_message = "Dear {$form_data['first_name']},\n\n";
    $customer_message .= "Thank you for booking the '{$form_data['package_name']}' safari package!\n\n";
    $customer_message .= "Your booking details:\n";
    $customer_message .= "Package: {$form_data['package_name']}\n";
    $customer_message .= "Preferred Start Date: {$form_data['start_date']}\n";
    $customer_message .= "Group Size: {$form_data['group_size']} people\n\n";
    $customer_message .= "We will contact you within 24 hours to confirm availability and provide detailed itinerary information.\n\n";
    $customer_message .= "If you have any questions, please don't hesitate to contact us.\n\n";
    $customer_message .= "Best regards,\n$site_name Team";
    
    wp_mail($form_data['email'], $customer_subject, $customer_message);
}

// Generic action handler for both booking types
function safari_handle_booking_actions($type) {
    global $wpdb;
    
    $table_name = $type === 'custom' ? 
        $wpdb->prefix . 'safari_bookings' : 
        $wpdb->prefix . 'safari_standard_bookings';
    
    // Handle single delete
    if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['booking_id']) && isset($_GET['type']) && $_GET['type'] === $type) {
        if (!isset($_GET['_wpnonce']) || !wp_verify_nonce($_GET['_wpnonce'], 'safari_delete_booking')) {
            wp_die('Security check failed');
        }
        
        $booking_id = absint($_GET['booking_id']);
        safari_delete_generic_booking($booking_id, $type);
    }
    
    // Handle bulk actions
    if (isset($_POST['bulk_submit'])) {
        if (!isset($_POST['safari_nonce']) || !wp_verify_nonce($_POST['safari_nonce'], 'safari_bulk_action')) {
            wp_die('Security check failed');
        }
        
        $bulk_action = sanitize_text_field($_POST['bulk_action']);
        
        if ($bulk_action === 'delete' && !empty($_POST['booking_ids'])) {
            $deleted = 0;
            foreach ($_POST['booking_ids'] as $booking_id) {
                $result = safari_delete_generic_booking(absint($booking_id), $type);
                if ($result) $deleted++;
            }
            
            $page_slug = $type === 'custom' ? 'safari-custom-bookings' : 'safari-standard-bookings';
            wp_redirect(admin_url('admin.php?page=' . $page_slug . '&deleted=' . $deleted));
            exit;
        }
        
        // Handle status updates
        $valid_statuses = array('pending', 'confirmed', 'completed', 'cancelled');
        if (in_array($bulk_action, $valid_statuses) && !empty($_POST['booking_ids'])) {
            $updated = 0;
            foreach ($_POST['booking_ids'] as $booking_id) {
                $result = safari_update_generic_booking_status(absint($booking_id), $bulk_action, $type);
                if ($result) $updated++;
            }
            
            $page_slug = $type === 'custom' ? 'safari-custom-bookings' : 'safari-standard-bookings';
            wp_redirect(admin_url('admin.php?page=' . $page_slug . '&status_updated=1'));
            exit;
        }
    }
}

// Generic delete function
function safari_delete_generic_booking($booking_id, $type) {
    global $wpdb;
    
    if (!current_user_can('manage_options')) {
        return false;
    }
    
    $table_name = $type === 'custom' ? 
        $wpdb->prefix . 'safari_bookings' : 
        $wpdb->prefix . 'safari_standard_bookings';
    
    $result = $wpdb->delete($table_name, array('id' => $booking_id), array('%d'));
    return $result !== false;
}

// Generic status update function
function safari_update_generic_booking_status($booking_id, $status, $type) {
    global $wpdb;
    
    if (!current_user_can('manage_options')) {
        return false;
    }
    
    $valid_statuses = array('pending', 'confirmed', 'completed', 'cancelled');
    if (!in_array($status, $valid_statuses)) {
        return false;
    }
    
    $table_name = $type === 'custom' ? 
        $wpdb->prefix . 'safari_bookings' : 
        $wpdb->prefix . 'safari_standard_bookings';
    
    $result = $wpdb->update(
        $table_name,
        array('status' => $status),
        array('id' => $booking_id),
        array('%s'),
        array('%d')
    );
    
    return $result !== false;
}

// Add modal popup function
function safari_add_booking_modal() {
    echo '
    <div id="booking-details-modal" class="safari-modal" style="display: none;">
        <div class="safari-modal-content">
            <div class="safari-modal-header">
                <h2>Booking Details</h2>
                <span class="safari-modal-close">&times;</span>
            </div>
            <div class="safari-modal-body" id="booking-details-content">
                <!-- Content will be loaded via AJAX -->
            </div>
            <div class="safari-modal-footer">
                <button type="button" class="safari-action-btn safari-modal-close">Close</button>
            </div>
        </div>
    </div>
    ';
}

// Add JavaScript for admin functionality
function safari_add_admin_scripts($type) {
    ?>
    <script type="text/javascript">
    jQuery(document).ready(function($) {
        // Select all functionality
        $("#select-all-bookings").change(function() {
            $('input[name="booking_ids[]"]').prop('checked', this.checked);
        });
        
        // Open modal when clicking view details
        $(".view-booking-details").on("click", function(e) {
            e.preventDefault();
            e.stopPropagation();
            
            var bookingId = $(this).data("booking-id");
            var bookingType = $(this).data("type") || "<?php echo $type; ?>";
            
            if (bookingId) {
                $("#booking-details-content").html('<div style="text-align: center; padding: 40px;"><div class="spinner is-active" style="float: none; margin: 0 auto;"></div><p>Loading booking details...</p></div>');
                $("#booking-details-modal").show();
                
                $.post(ajaxurl, {
                    action: "safari_get_booking_details",
                    booking_id: bookingId,
                    booking_type: bookingType,
                    _wpnonce: "<?php echo wp_create_nonce('safari_get_booking_details'); ?>"
                }, function(response) {
                    if (response.success) {
                        $("#booking-details-content").html(response.data);
                    } else {
                        $("#booking-details-content").html('<div class="error"><p>Error loading booking details: ' + response.data + '</p></div>');
                    }
                }).fail(function() {
                    $("#booking-details-content").html('<div class="error"><p>Error loading booking details. Please try again.</p></div>');
                });
            }
        });
        
        // Close modal
        $(".safari-modal-close, .safari-modal").on("click", function(e) {
            if ($(e.target).hasClass("safari-modal") || $(e.target).hasClass("safari-modal-close")) {
                $("#booking-details-modal").hide();
            }
        });
        
        $(".safari-modal-content").on("click", function(e) {
            e.stopPropagation();
        });
        
        // Row hover effects
        $(".booking-row").hover(
            function() { $(this).addClass("row-hover"); },
            function() { $(this).removeClass("row-hover"); }
        );
    });
    </script>
    
    <style>
    .safari-modal {
        display: none;
        position: fixed;
        z-index: 10000;
        left: 0;
        top: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.6);
        backdrop-filter: blur(3px);
    }

    .safari-modal-content {
        background: white;
        margin: 3% auto;
        padding: 0;
        border-radius: 15px;
        width: 85%;
        max-width: 1000px;
        max-height: 85vh;
        overflow-y: auto;
        box-shadow: 0 20px 60px rgba(0,0,0,0.3);
        animation: modalSlideIn 0.3s ease-out;
    }
    
    @keyframes modalSlideIn {
        from { opacity: 0; transform: translateY(-50px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .safari-modal-header {
        padding: 25px;
        border-bottom: 1px solid #e9ecef;
        display: flex;
        justify-content: space-between;
        align-items: center;
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px 15px 0 0;
    }

    .safari-modal-header h2 {
        margin: 0;
        font-weight: 600;
    }

    .safari-modal-close {
        color: white;
        font-size: 28px;
        font-weight: bold;
        cursor: pointer;
        line-height: 1;
        opacity: 0.8;
        transition: opacity 0.3s ease;
    }

    .safari-modal-close:hover {
        opacity: 1;
    }

    .safari-modal-body {
        padding: 25px;
        max-height: 60vh;
        overflow-y: auto;
    }

    .safari-modal-footer {
        padding: 20px 25px;
        border-top: 1px solid #e9ecef;
        text-align: right;
        background: #f8f9fa;
        border-radius: 0 0 15px 15px;
    }
    
    .row-hover {
        background: linear-gradient(135deg, #fff5f5 0%, #f0f9ff 100%) !important;
        transform: scale(1.01);
        transition: all 0.2s ease;
    }
    </style>
    <?php
}

// Updated AJAX handler for booking details (supports both types)
add_action('wp_ajax_safari_get_booking_details', 'safari_handle_ajax_booking_details_updated');
function safari_handle_ajax_booking_details_updated() {
    if (!isset($_POST['_wpnonce']) || !wp_verify_nonce($_POST['_wpnonce'], 'safari_get_booking_details')) {
        wp_send_json_error('Security check failed');
    }
    
    if (!current_user_can('manage_options')) {
        wp_send_json_error('Insufficient permissions');
    }
    
    if (!isset($_POST['booking_id']) || !isset($_POST['booking_type'])) {
        wp_send_json_error('Missing parameters');
    }
    
    $booking_id = absint($_POST['booking_id']);
    $booking_type = sanitize_text_field($_POST['booking_type']);
    
    $booking = safari_get_generic_booking_details($booking_id, $booking_type);
    
    if ($booking) {
        $output = safari_format_generic_booking_details($booking, $booking_type);
        wp_send_json_success($output);
    } else {
        wp_send_json_error('Booking not found');
    }
}

// Generic function to get booking details
function safari_get_generic_booking_details($booking_id, $type) {
    global $wpdb;
    
    $table_name = $type === 'custom' ? 
        $wpdb->prefix . 'safari_bookings' : 
        $wpdb->prefix . 'safari_standard_bookings';
    
    $booking = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM $table_name WHERE id = %d", $booking_id
    ));
    
    return $booking;
}

// Generic function to format booking details
function safari_format_generic_booking_details($booking, $type) {
    $output = '';
    
    // Contact Information
    $output .= '<div class="booking-details-section">';
    $output .= '<h3>Contact Information</h3>';
    $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Name:</span><span class="booking-detail-value">' . esc_html($booking->first_name . ' ' . $booking->last_name) . '</span></div>';
    $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Email:</span><span class="booking-detail-value"><a href="mailto:' . esc_attr($booking->email) . '">' . esc_html($booking->email) . '</a></span></div>';
    $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Phone:</span><span class="booking-detail-value">' . esc_html($booking->phone) . '</span></div>';
    $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Country:</span><span class="booking-detail-value">' . esc_html($booking->visitor_country) . '</span></div>';
    $output .= '</div>';
    
    if ($type === 'custom') {
        // Custom booking details
        $output .= '<div class="booking-details-section">';
        $output .= '<h3>Trip Details</h3>';
        $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Preferred Country:</span><span class="booking-detail-value">' . esc_html($booking->preferred_country) . '</span></div>';
        $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Budget Range:</span><span class="booking-detail-value">' . esc_html($booking->budget) . '</span></div>';
        $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Start Date:</span><span class="booking-detail-value">' . ($booking->start_date ? date('M j, Y', strtotime($booking->start_date)) : 'Not specified') . '</span></div>';
        $output .= '<div class="booking-detail-row"><span class="booking-detail-label">End Date:</span><span class="booking-detail-value">' . ($booking->end_date ? date('M j, Y', strtotime($booking->end_date)) : 'Not specified') . '</span></div>';
        $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Group Size:</span><span class="booking-detail-value">' . esc_html($booking->group_size) . ' people</span></div>';
        $output .= '</div>';
        
        $output .= '<div class="booking-details-section">';
        $output .= '<h3>Selected Experiences</h3>';
        $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Experiences:</span><span class="booking-detail-value">' . esc_html($booking->selected_experiences) . '</span></div>';
        $output .= '</div>';
        
        // Experience Details
        if (!empty($booking->experience_details)) {
            $experience_details = json_decode($booking->experience_details, true);
            if ($experience_details && is_array($experience_details)) {
                $output .= '<div class="booking-details-section">';
                $output .= '<h3>Experience Details</h3>';
                foreach ($experience_details as $key => $value) {
                    if (!empty($value)) {
                        $label = ucfirst(str_replace('_', ' ', $key));
                        $output .= '<div class="booking-detail-row"><span class="booking-detail-label">' . esc_html($label) . ':</span><span class="booking-detail-value">' . esc_html($value) . '</span></div>';
                    }
                }
                $output .= '</div>';
            }
        }
        
        // Additional Information
        $output .= '<div class="booking-details-section">';
        $output .= '<h3>Additional Information</h3>';
        if (!empty($booking->special_requests)) {
            $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Special Requests:</span><span class="booking-detail-value">' . nl2br(esc_html($booking->special_requests)) . '</span></div>';
        }
        if (!empty($booking->dietary_requirements)) {
            $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Dietary Requirements:</span><span class="booking-detail-value">' . esc_html($booking->dietary_requirements) . '</span></div>';
        }
        if (!empty($booking->accessibility)) {
            $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Accessibility Needs:</span><span class="booking-detail-value">' . esc_html($booking->accessibility) . '</span></div>';
        }
        $output .= '</div>';
    } else {
        // Standard booking details
        $output .= '<div class="booking-details-section">';
        $output .= '<h3>Package Details</h3>';
        $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Package Name:</span><span class="booking-detail-value">' . esc_html($booking->package_name) . '</span></div>';
        if (!empty($booking->package_url)) {
            $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Package URL:</span><span class="booking-detail-value"><a href="' . esc_url($booking->package_url) . '" target="_blank">View Package</a></span></div>';
        }
        $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Preferred Start Date:</span><span class="booking-detail-value">' . ($booking->start_date ? date('M j, Y', strtotime($booking->start_date)) : 'Not specified') . '</span></div>';
        $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Group Size:</span><span class="booking-detail-value">' . esc_html($booking->group_size) . ' people</span></div>';
        $output .= '</div>';
        
        // Requirements
        $output .= '<div class="booking-details-section">';
        $output .= '<h3>Requirements & Special Needs</h3>';
        if (!empty($booking->dietary_requirements)) {
            $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Dietary Requirements:</span><span class="booking-detail-value">' . esc_html($booking->dietary_requirements) . '</span></div>';
        }
        if (!empty($booking->additional_needs)) {
            $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Additional Needs:</span><span class="booking-detail-value">' . nl2br(esc_html($booking->additional_needs)) . '</span></div>';
        }
        $output .= '</div>';
    }
    
    // Submission Details
    $output .= '<div class="booking-details-section">';
    $output .= '<h3>Submission Details</h3>';
    $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Submission Date:</span><span class="booking-detail-value">' . date('M j, Y g:i a', strtotime($booking->submission_date)) . '</span></div>';
    $output .= '<div class="booking-detail-row"><span class="booking-detail-label">Status:</span><span class="booking-detail-value"><span class="safari-status-badge ' . $booking->status . '">' . ucfirst($booking->status) . '</span></span></div>';
    $output .= '</div>';
    
    return $output;
}

// Create standard bookings table on plugin activation
register_activation_hook(__FILE__, 'safari_create_standard_bookings_table');

// Success message for standard bookings
add_action('wp_head', 'safari_standard_success_message_script');
function safari_standard_success_message_script() {
    if (isset($_GET['standard_safari_submitted'])) {
        echo "
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            alert('Thank you! Your safari booking has been submitted successfully. We will contact you within 24 hours to confirm availability.');
        });
        </script>
        ";
    }
}

// Add CSS for modal booking details
function safari_add_modal_styles() {
    echo '<style>
    .booking-details-section {
        margin-bottom: 25px;
        padding: 20px;
        border-radius: 10px;
        border-left: 4px solid #667eea;
    }

    .booking-details-section h3 {
        margin-top: 0;
        color: #2c3e50;
        font-weight: 600;
        margin-bottom: 15px;
    }

    .booking-detail-row {
        display: flex;
        margin-bottom: 10px;
        align-items: flex-start;
    }

    .booking-detail-label {
        font-weight: 600;
        min-width: 180px;
        color: #495057;
        flex-shrink: 0;
    }

    .booking-detail-value {
        flex: 1;
        color: #212529;
        word-wrap: break-word;
    }
    </style>';
}

add_action('admin_head', 'safari_add_modal_styles');
add_action('admin_menu', 'safari_admin_menu');
?>