<?php
/**
 * Standard Safari Booking Form WordPress Shortcode
 * Usage: [standard_safari_booking_form package_name="Package Name"]
 * 
 * Add this code to your theme's functions.php file or create a custom plugin
 */

// Register the shortcode for standard bookings
add_shortcode('standard_safari_booking_form', 'standard_safari_booking_form_shortcode');

function standard_safari_booking_form_shortcode($atts = array()) {
    // Extract attributes with defaults
    $atts = shortcode_atts(array(
        'package_name' => 'Safari Package',
        'form_title' => 'Book This Safari',
        'form_subtitle' => 'Secure your spot on this amazing adventure'
    ), $atts);

    // Get current page URL
    $current_url = is_admin() ? home_url() : get_permalink();

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


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

            <!-- Package Info -->
            <div class="standard-safari-package-info">
                <h2 class="standard-safari-package-name"><?php echo esc_html($atts['package_name']); ?></h2>
            </div>

            <!-- Form Content -->
            <div class="standard-safari-form-content">
                <?php 
                // Display success message
                if (isset($_GET['standard_safari_submitted']) && $_GET['standard_safari_submitted'] == '1'): 
                ?>
                    <div class="standard-safari-success-message">
                        Thank you! Your safari booking has been submitted successfully. We will contact you within 24 hours to confirm availability and provide detailed information.
                    </div>
                <?php endif; ?>

                <form method="post" action="<?php echo esc_url($current_url); ?>" id="standard-safari-booking-form">
                    <?php wp_nonce_field('standard_safari_booking_form', 'standard_safari_nonce'); ?>
                    <input type="hidden" name="package_name" value="<?php echo esc_attr($atts['package_name']); ?>" />
                    <input type="hidden" name="package_url" value="<?php echo esc_url($current_url); ?>" />

                    <!-- Personal Information Section -->
                    <div class="standard-form-section">
                        <h3>Personal Information</h3>
                        
                        <div class="standard-safari-grid">
                            <div class="standard-safari-form-group">
                                <label class="standard-safari-label" for="first_name">
                                    First Name <span class="required">*</span>
                                </label>
                                <input type="text" 
                                       id="first_name" 
                                       name="first_name" 
                                       class="standard-safari-input" 
                                       required 
                                       value="<?php echo isset($_POST['first_name']) ? esc_attr($_POST['first_name']) : ''; ?>" />
                            </div>

                            <div class="standard-safari-form-group">
                                <label class="standard-safari-label" for="last_name">
                                    Last Name <span class="required">*</span>
                                </label>
                                <input type="text" 
                                       id="last_name" 
                                       name="last_name" 
                                       class="standard-safari-input" 
                                       required 
                                       value="<?php echo isset($_POST['last_name']) ? esc_attr($_POST['last_name']) : ''; ?>" />
                            </div>
                        </div>

                        <div class="standard-safari-grid">
                            <div class="standard-safari-form-group">
                                <label class="standard-safari-label" for="email">
                                    Email Address <span class="required">*</span>
                                </label>
                                <input type="email" 
                                       id="email" 
                                       name="email" 
                                       class="standard-safari-input" 
                                       required 
                                       value="<?php echo isset($_POST['email']) ? esc_attr($_POST['email']) : ''; ?>" />
                            </div>

                            <div class="standard-safari-form-group">
                                <label class="standard-safari-label" for="phone">
                                    Phone Number <span class="required">*</span>
                                </label>
                                <input type="tel" 
                                       id="phone" 
                                       name="phone" 
                                       class="standard-safari-input" 
                                       required 
                                       placeholder="+1 (555) 123-4567"
                                       value="<?php echo isset($_POST['phone']) ? esc_attr($_POST['phone']) : ''; ?>" />
                            </div>
                        </div>

                        <div class="standard-safari-form-group">
                            <label class="standard-safari-label" for="visitor_country">
                                Country of Origin <span class="required">*</span>
                            </label>
                            <select id="visitor_country" 
                                    name="visitor_country" 
                                    class="standard-safari-select" 
                                    required>
                                <option value="">Select your country</option>
                                <option value="United States" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'United States'); ?>>United States</option>
                                <option value="Canada" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'Canada'); ?>>Canada</option>
                                <option value="United Kingdom" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'United Kingdom'); ?>>United Kingdom</option>
                                <option value="Germany" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'Germany'); ?>>Germany</option>
                                <option value="France" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'France'); ?>>France</option>
                                <option value="Australia" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'Australia'); ?>>Australia</option>
                                <option value="South Africa" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'South Africa'); ?>>South Africa</option>
                                <option value="Netherlands" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'Netherlands'); ?>>Netherlands</option>
                                <option value="Switzerland" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'Switzerland'); ?>>Switzerland</option>
                                <option value="Sweden" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'Sweden'); ?>>Sweden</option>
                                <option value="Norway" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'Norway'); ?>>Norway</option>
                                <option value="Denmark" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'Denmark'); ?>>Denmark</option>
                                <option value="Italy" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'Italy'); ?>>Italy</option>
                                <option value="Spain" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'Spain'); ?>>Spain</option>
                                <option value="Other" <?php selected(isset($_POST['visitor_country']) ? $_POST['visitor_country'] : '', 'Other'); ?>>Other</option>
                            </select>
                        </div>
                    </div>

                    <!-- Booking Details Section -->
                    <div class="standard-form-section">
                        <h3>Booking Details</h3>
                        
                        <div class="standard-safari-grid">
                            <div class="standard-safari-form-group">
                                <label class="standard-safari-label" for="start_date">
                                    Preferred Start Date
                                </label>
                                <input type="date" 
                                       id="start_date" 
                                       name="start_date" 
                                       class="standard-safari-input"
                                       min="<?php echo date('Y-m-d'); ?>"
                                       value="<?php echo isset($_POST['start_date']) ? esc_attr($_POST['start_date']) : ''; ?>" />
                            </div>

                            <div class="standard-safari-form-group">
                                <label class="standard-safari-label" for="group_size">
                                    Group Size <span class="required">*</span>
                                </label>
                                <select id="group_size" 
                                        name="group_size" 
                                        class="standard-safari-select" 
                                        required>
                                    <option value="">Select group size</option>
                                    <?php for ($i = 1; $i <= 20; $i++): ?>
                                        <option value="<?php echo $i; ?>" <?php selected(isset($_POST['group_size']) ? $_POST['group_size'] : '', $i); ?>>
                                            <?php echo $i; ?> <?php echo $i == 1 ? 'person' : 'people'; ?>
                                        </option>
                                    <?php endfor; ?>
                                    <option value="20+" <?php selected(isset($_POST['group_size']) ? $_POST['group_size'] : '', '20+'); ?>>20+ people</option>
                                </select>
                            </div>
                        </div>
                    </div>

                    <!-- Special Requirements Section -->
                    <div class="standard-form-section">
                        <h3>Special Requirements</h3>
                        
                        <div class="standard-safari-form-group">
                            <label class="standard-safari-label" for="dietary_requirements">
                                Dietary Requirements
                            </label>
                            <input type="text" 
                                   id="dietary_requirements" 
                                   name="dietary_requirements" 
                                   class="standard-safari-input"
                                   placeholder="e.g., Vegetarian, Vegan, Gluten-free, Allergies"
                                   value="<?php echo isset($_POST['dietary_requirements']) ? esc_attr($_POST['dietary_requirements']) : ''; ?>" />
                        </div>

                        <div class="standard-safari-form-group">
                            <label class="standard-safari-label" for="additional_needs">
                                Additional Needs or Special Requests
                            </label>
                            <textarea id="additional_needs" 
                                      name="additional_needs" 
                                      class="standard-safari-textarea"
                                      placeholder="Please describe any accessibility needs, special occasions, or other requests..."><?php echo isset($_POST['additional_needs']) ? esc_textarea($_POST['additional_needs']) : ''; ?></textarea>
                        </div>
                    </div>

                    <!-- Submit Section -->
                    <div class="standard-safari-submit-section">
                        <button type="submit" name="submit_standard_safari_form" class="standard-safari-btn">
                            Submit Booking Request
                        </button>
                        <p class="standard-submit-note">
                            We'll contact you within 24 hours to confirm availability and provide detailed itinerary information.
                        </p>
                    </div>
                </form>
            </div>
        </div>

        <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Add form validation
            const form = document.getElementById('standard-safari-booking-form');
            const requiredFields = form.querySelectorAll('[required]');
            
            form.addEventListener('submit', function(e) {
                let isValid = true;
                
                // Remove previous error styling
                requiredFields.forEach(field => {
                    field.classList.remove('standard-field-error');
                    const errorMsg = field.parentNode.querySelector('.error-message');
                    if (errorMsg) {
                        errorMsg.remove();
                    }
                });
                
                // Validate required fields
                requiredFields.forEach(field => {
                    if (!field.value.trim()) {
                        isValid = false;
                        field.classList.add('standard-field-error');
                        
                        const errorDiv = document.createElement('div');
                        errorDiv.className = 'error-message';
                        errorDiv.textContent = 'This field is required';
                        field.parentNode.appendChild(errorDiv);
                    }
                });
                
                // Email validation
                const emailField = document.getElementById('email');
                if (emailField.value && !isValidEmail(emailField.value)) {
                    isValid = false;
                    emailField.classList.add('standard-field-error');
                    
                    const errorDiv = document.createElement('div');
                    errorDiv.className = 'error-message';
                    errorDiv.textContent = 'Please enter a valid email address';
                    emailField.parentNode.appendChild(errorDiv);
                }
                
                if (!isValid) {
                    e.preventDefault();
                    // Scroll to first error
                    const firstError = form.querySelector('.standard-field-error');
                    if (firstError) {
                        firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                        firstError.focus();
                    }
                }
            });
            
            // Email validation function
            function isValidEmail(email) {
                return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
            }
            
            // Real-time validation feedback
            requiredFields.forEach(field => {
                field.addEventListener('blur', function() {
                    if (this.hasAttribute('required') && !this.value.trim()) {
                        this.classList.add('standard-field-error');
                    } else {
                        this.classList.remove('standard-field-error');
                        const errorMsg = this.parentNode.querySelector('.error-message');
                        if (errorMsg) {
                            errorMsg.remove();
                        }
                    }
                });
                
                field.addEventListener('input', function() {
                    if (this.classList.contains('standard-field-error') && this.value.trim()) {
                        this.classList.remove('standard-field-error');
                        const errorMsg = this.parentNode.querySelector('.error-message');
                        if (errorMsg) {
                            errorMsg.remove();
                        }
                    }
                });
            });
            
            // Enhanced button animation
            const submitBtn = document.querySelector('.standard-safari-btn');
            submitBtn.addEventListener('click', function(e) {
                if (form.checkValidity()) {
                    this.style.transform = 'scale(0.95)';
                    setTimeout(() => {
                        this.style.transform = '';
                    }, 150);
                }
            });
        });
        </script>
    </div>

    <?php
    return ob_get_clean();
}

// 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']),
//         );

//         // Validate required fields
//         $errors = array();
//         if (empty($form_data['first_name'])) $errors[] = 'First name is required';
//         if (empty($form_data['last_name'])) $errors[] = 'Last name is required';
//         if (empty($form_data['email']) || !is_email($form_data['email'])) $errors[] = 'Valid email is required';
//         if (empty($form_data['phone'])) $errors[] = 'Phone number is required';
//         if (empty($form_data['visitor_country'])) $errors[] = 'Country is required';
//         if (empty($form_data['group_size'])) $errors[] = 'Group size is required';

//         if (empty($errors)) {
//             // 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;
//         } else {
//             // Store errors in session or handle differently
//             add_action('wp_head', function() use ($errors) {
//                 echo '<script>console.log("Form errors: ", ' . json_encode($errors) . ');</script>';
//             });
//         }
//     }
// }

// 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
//     $result = $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')
//     );
    
//     return $result !== false;
// }

// // 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: " . (!empty($form_data['start_date']) ? $form_data['start_date'] : 'Not specified') . "\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: " . (!empty($form_data['start_date']) ? $form_data['start_date'] : 'Not specified') . "\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);
// }

// // 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() {
//             const container = document.getElementById('standard-safari-booking-container');
//             if (container) {
//                 container.scrollIntoView({ behavior: 'smooth' });
//             }
//         });
//         </script>
//         ";
//     }
// }

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