<?php
/**
 * Template Name: Contact Us Page
 * Description: Custom contact page template
 * UPDATED VERSION - Fixed Google Maps Display
 */

get_header();

// Get customizer settings for contact info
$contact_phone = get_theme_mod('contact_phone', '+1 836 483 384');
$contact_email = get_theme_mod('contact_email', 'info@travel.com');

// Get contact page specific settings
$agency_address_line1 = get_theme_mod('contact_agency_address_line1', '3104 Michigan Ave, Miami Beach');
$agency_address_line2 = get_theme_mod('contact_agency_address_line2', 'FL 33139, United States');
$agency_phone = get_theme_mod('contact_agency_phone', 'Paul Davis "Tour Consultant" +1 629 592 593');
$agency_phone2 = get_theme_mod('contact_agency_phone2', 'Amy Moore "Local Guide" +1 483 832 205');

$operator_address_line1 = get_theme_mod('contact_operator_address_line1', '3081 Biscayne Blvd, Miami');
$operator_address_line2 = get_theme_mod('contact_operator_address_line2', 'FL 33137, United States');
$operator_phone = get_theme_mod('contact_operator_phone', 'Administration: +1 184 016 482');
$operator_phone2 = get_theme_mod('contact_operator_phone2', 'Technical Office: +1 863 826 836');

$quotes_email = get_theme_mod('contact_quotes_email', 'quote@travel.com');
$quotes_text = get_theme_mod('contact_quotes_text', 'Write to this email for a detailed quotation and information.');

$consulting_email = get_theme_mod('contact_consulting_email', 'info@travel.com');
$consulting_text = get_theme_mod('contact_consulting_text', 'Our free consultation service can be requested here every day.');

$form_title = get_theme_mod('contact_form_title', 'Get in Touch');
$form_subtitle = get_theme_mod('contact_form_subtitle', 'Plan Your Next Trip');
$form_description = get_theme_mod('contact_form_description', 'Write to us for personalized travel advice or for information on group travel and best minute travel, all travel is insured and safe.');

// Get map embed code and extract URL
$map_embed = get_theme_mod('contact_map_embed', '');
$map_url = '';

if (!empty($map_embed)) {
    // Clean up the embed code
    $map_embed = trim($map_embed);

    // Check if it's already a URL (direct embed URL)
    if (filter_var($map_embed, FILTER_VALIDATE_URL)) {
        $map_url = $map_embed;
    }
    // Try to extract URL from iframe with multiple patterns
    elseif (preg_match('/src=["\']([^"\']+)["\']/', $map_embed, $matches)) {
        $map_url = $matches[1];
    }
    // Alternative pattern for src without quotes
    elseif (preg_match('/src=([^\s>]+)/', $map_embed, $matches)) {
        $map_url = $matches[1];
    }

    // Ensure the URL is using HTTPS for Google Maps
    if (!empty($map_url) && strpos($map_url, 'google.com/maps') !== false) {
        $map_url = str_replace('http://', 'https://', $map_url);
    }
}

while (have_posts()):
    the_post();
    ?>

    <!-- Contact Hero Section -->
    <section class="contact-hero"
        style="position: relative; min-height: 40vh; display: flex; align-items: center; <?php if (has_post_thumbnail()): ?>background-image: url('<?php echo get_the_post_thumbnail_url(get_the_ID(), 'full'); ?>');<?php else: ?>background: linear-gradient(135deg, var(--primary) 0%, var(--primary-dark) 100%);<?php endif; ?> background-size: cover; background-position: center;">
        <div
            style="position: absolute; inset: 0; background: linear-gradient(to bottom, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0.2) 50%, rgba(0,0,0,0.6) 100%);">
        </div>
        <div class="container" style="position: relative; z-index: 2;">
            <div style="max-width: 800px; text-align: center; margin: 0 auto; color: white;">
                <h1
                    style="color: white; font-size: clamp(2.5rem, 5vw, 4rem); margin-bottom: 20px; text-shadow: 0 2px 15px rgba(0,0,0,0.5);">
                    <?php the_title(); ?>
                </h1>
                <?php if (get_the_excerpt()): ?>
                    <p style="font-size: 18px; opacity: 0.95; text-shadow: 0 2px 10px rgba(0,0,0,0.5);">
                        <?php echo get_the_excerpt(); ?>
                    </p>
                <?php endif; ?>
            </div>
        </div>
    </section>

    <!-- Contact Information Cards -->
    <section style="padding: 80px 0; background: white;">
        <div class="container">
            <div
                style="display: grid; grid-template-columns: repeat(auto-fit, minmax(300px, 1fr)); gap: 40px; margin-bottom: 80px;">

                <!-- Location Card -->
                <div style="text-align: center;">
                    <div
                        style="width: 80px; height: 80px; background: var(--primary); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 25px; font-size: 35px;">
                        <i class="fas fa-map-marker-alt"></i>
                    </div>
                    <h3 style="font-size: 22px; color: var(--dark); margin-bottom: 25px; font-weight: 600;">
                        <?php _e('Location', 'travel-mountain'); ?>
                    </h3>

                    <div>
                        <h4 style="font-size: 16px; color: var(--dark); font-weight: 600; margin-bottom: 8px;">
                            <?php _e('Travel Agency', 'travel-mountain'); ?>
                        </h4>
                        <p style="font-size: 14px; color: var(--medium-gray); line-height: 1.6;">
                            <?php echo esc_html($agency_address_line1); ?><br>
                            <?php echo esc_html($agency_address_line2); ?>
                        </p>
                    </div>
                </div>

                <!-- Phone Card -->
                <div style="text-align: center;">
                    <div
                        style="width: 80px; height: 80px; background: var(--primary); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 25px; font-size: 35px;">
                        <i class="fas fa-phone-alt"></i>
                    </div>
                    <h3 style="font-size: 22px; color: var(--dark); margin-bottom: 25px; font-weight: 600;">
                        <?php _e('Give us a call', 'travel-mountain'); ?>
                    </h3>

                    <div>
                        <h4 style="font-size: 16px; color: var(--dark); font-weight: 600; margin-bottom: 8px;">
                            <?php _e('Mobile Number', 'travel-mountain'); ?>
                        </h4>
                        <p style="font-size: 14px; color: var(--medium-gray); line-height: 1.8;">
                            <?php echo esc_html($agency_phone); ?><br>
                            <?php echo esc_html($agency_phone2); ?>
                        </p>
                    </div>
                </div>

                <!-- Email Card -->
                <div style="text-align: center;">
                    <div
                        style="width: 80px; height: 80px; background: var(--primary); color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; margin: 0 auto 25px; font-size: 35px;">
                        <i class="fas fa-envelope"></i>
                    </div>
                    <h3 style="font-size: 22px; color: var(--dark); margin-bottom: 25px; font-weight: 600;">
                        <?php _e('Write for anything', 'travel-mountain'); ?>
                    </h3>

                    <div>
                        <h4 style="font-size: 16px; color: var(--dark); font-weight: 600; margin-bottom: 8px;">
                            <?php _e('Quotes', 'travel-mountain'); ?>
                        </h4>
                        <p style="font-size: 14px; color: var(--medium-gray); line-height: 1.6; margin-bottom: 8px;">
                            <?php echo esc_html($quotes_text); ?>
                        </p>
                        <a href="mailto:<?php echo esc_attr($quotes_email); ?>"
                            style="color: var(--primary); text-decoration: none; font-weight: 600; font-size: 14px;">
                            <?php echo esc_html($quotes_email); ?>
                        </a>
                    </div>
                </div>

            </div>
        </div>
    </section>

    <!-- Contact Form Section -->
    <section style="padding: 80px 0; background: var(--cream);">
        <div class="container">
            <div style="max-width: 700px; margin: 0 auto; text-align: center; margin-bottom: 50px;">
                <span
                    style="display: inline-block; color: var(--primary); font-family: 'Dancing Script', cursive; font-size: 24px; margin-bottom: 15px;">
                    <?php echo esc_html($form_subtitle); ?>
                </span>
                <h2 style="font-size: clamp(2rem, 4vw, 3rem); color: var(--dark); margin-bottom: 20px;">
                    <?php echo esc_html($form_title); ?>
                </h2>
                <p style="font-size: 16px; color: var(--medium-gray); line-height: 1.7;">
                    <?php echo esc_html($form_description); ?>
                </p>
            </div>

            <div
                style="max-width: 700px; margin: 0 auto; background: white; padding: 50px; border-radius: 12px; box-shadow: 0 10px 40px rgba(0,0,0,0.08);">
                <form id="contact-form" method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
                    <input type="hidden" name="action" value="submit_contact_form">
                    <?php wp_nonce_field('contact_form_submit', 'contact_form_nonce'); ?>

                    <div style="margin-bottom: 25px;">
                        <input type="text" name="contact_name"
                            placeholder="<?php _e('Type your name', 'travel-mountain'); ?>" required
                            style="width: 100%; padding: 18px 20px; border: 2px solid var(--light-gray); border-radius: 8px; font-size: 15px; transition: all 0.3s ease;">
                    </div>

                    <div style="margin-bottom: 25px;">
                        <input type="email" name="contact_email"
                            placeholder="<?php _e('Insert your email', 'travel-mountain'); ?>" required
                            style="width: 100%; padding: 18px 20px; border: 2px solid var(--light-gray); border-radius: 8px; font-size: 15px; transition: all 0.3s ease;">
                    </div>

                    <div style="margin-bottom: 25px;">
                        <input type="tel" name="contact_phone" placeholder="<?php _e('Phone Number', 'travel-mountain'); ?>"
                            required
                            style="width: 100%; padding: 18px 20px; border: 2px solid var(--light-gray); border-radius: 8px; font-size: 15px; transition: all 0.3s ease;">
                    </div>

                    <div style="margin-bottom: 25px;">
                        <input type="text" name="contact_nationality"
                            placeholder="<?php _e('Nationality', 'travel-mountain'); ?>" required
                            style="width: 100%; padding: 18px 20px; border: 2px solid var(--light-gray); border-radius: 8px; font-size: 15px; transition: all 0.3s ease;">
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 25px;">
                        <div>

                            <input type="date" id="contact_start_date" name="contact_start_date" required
                                min="<?php echo date('Y-m-d'); ?>"
                                style="width: 100%; padding: 18px 20px; border: 2px solid var(--light-gray); border-radius: 8px; font-size: 15px; transition: all 0.3s ease; cursor: pointer;">
                        </div>
                        <div>

                            <input type="date" id="contact_end_date" name="contact_end_date" required
                                min="<?php echo date('Y-m-d'); ?>"
                                style="width: 100%; padding: 18px 20px; border: 2px solid var(--light-gray); border-radius: 8px; font-size: 15px; transition: all 0.3s ease; cursor: pointer;">
                        </div>
                    </div>

                    <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-bottom: 25px;">
                        <div>
                            <input type="number" name="contact_adults"
                                placeholder="<?php _e('No of Adult Travellers', 'travel-mountain'); ?>" min="0" required
                                style="width: 100%; padding: 18px 20px; border: 2px solid var(--light-gray); border-radius: 8px; font-size: 15px; transition: all 0.3s ease;">
                        </div>
                        <div>
                            <input type="number" name="contact_children"
                                placeholder="<?php _e('No of Children', 'travel-mountain'); ?>" min="0" required
                                style="width: 100%; padding: 18px 20px; border: 2px solid var(--light-gray); border-radius: 8px; font-size: 15px; transition: all 0.3s ease;">
                        </div>
                    </div>

                    <div style="margin-bottom: 25px;">
                        <select name="contact_service" required
                            style="width: 100%; padding: 18px 20px; border: 2px solid var(--light-gray); border-radius: 8px; font-size: 15px; transition: all 0.3s ease; background: white; cursor: pointer;">
                            <option value=""><?php _e('Select a Service', 'travel-mountain'); ?></option>
                            <option value="Adventure Tours"><?php _e('Adventure Tours', 'travel-mountain'); ?></option>
                            <option value="Beach Holidays"><?php _e('Beach Holidays', 'travel-mountain'); ?></option>
                            <option value="City Tours"><?php _e('City Tours', 'travel-mountain'); ?></option>
                            <option value="Cultural Tours"><?php _e('Cultural Tours', 'travel-mountain'); ?></option>
                            <option value="Honeymoon Packages"><?php _e('Honeymoon Packages', 'travel-mountain'); ?>
                            </option>
                            <option value="Mountain Trekking"><?php _e('Mountain Trekking', 'travel-mountain'); ?></option>
                            <option value="Safari Tours"><?php _e('Safari Tours', 'travel-mountain'); ?></option>
                            <option value="Custom Package"><?php _e('Custom Package', 'travel-mountain'); ?></option>
                            <option value="Other"><?php _e('Other', 'travel-mountain'); ?></option>
                        </select>
                    </div>

                    <div style="margin-bottom: 30px;">
                        <textarea name="contact_message" rows="6"
                            placeholder="<?php _e('Your Message (Optional)', 'travel-mountain'); ?>"
                            style="width: 100%; padding: 18px 20px; border: 2px solid var(--light-gray); border-radius: 8px; font-size: 15px; resize: vertical; transition: all 0.3s ease;"></textarea>
                    </div>

                    <div style="margin-bottom: 30px;">
                        <label
                            style="display: flex; align-items: flex-start; cursor: pointer; font-size: 14px; color: var(--medium-gray); line-height: 1.6;">
                            <input type="checkbox" name="contact_privacy" required
                                style="margin-right: 12px; margin-top: 3px; width: 18px; height: 18px; cursor: pointer; accent-color: var(--primary);">
                            <span>
                                <?php _e('I have read the', 'travel-mountain'); ?>
                                <a href="<?php echo get_privacy_policy_url(); ?>" target="_blank"
                                    style="color: var(--primary); text-decoration: none; font-weight: 600;">
                                    <?php _e('Privacy Policy', 'travel-mountain'); ?>
                                </a>
                                <?php _e('and agree to its terms.', 'travel-mountain'); ?>
                            </span>
                        </label>
                    </div>

                    <button type="submit" class="contact-submit-btn"
                        style="width: 100%; background: var(--primary); color: white; border: none; padding: 18px; font-size: 16px; font-weight: 700; text-transform: uppercase; letter-spacing: 1px; border-radius: 8px; cursor: pointer; transition: all 0.3s ease;">
                        <?php _e('Submit', 'travel-mountain'); ?>
                    </button>

                    <div id="form-message" style="margin-top: 20px; padding: 15px; border-radius: 8px; display: none;">
                    </div>
                </form>
            </div>
        </div>
    </section>

    <!-- Map Section - ENHANCED VERSION -->
    <?php if (!empty($map_url)): ?>
        <section class="contact-map"
            style="position: relative; height: 450px; overflow: hidden; background: var(--light-gray);">
            <iframe src="<?php echo esc_url($map_url); ?>" width="100%" height="450"
                style="border:0; width: 100%; height: 100%; display: block; position: absolute; top: 0; left: 0;"
                allowfullscreen="" loading="lazy" referrerpolicy="no-referrer-when-downgrade"
                title="<?php _e('Location Map', 'travel-mountain'); ?>">
            </iframe>
            <!-- Fallback if iframe doesn't load -->
            <noscript>
                <div style="padding: 40px; text-align: center;">
                    <p><?php _e('Please enable JavaScript to view the map.', 'travel-mountain'); ?></p>
                </div>
            </noscript>
        </section>
    <?php else: ?>
        <section class="contact-map"
            style="position: relative; height: 450px; overflow: hidden; background: var(--light-gray); display: flex; align-items: center; justify-content: center;">
            <div style="text-align: center; padding: 40px;">
                <i class="fas fa-map-marked-alt"
                    style="font-size: 60px; color: var(--primary); opacity: 0.3; margin-bottom: 20px;"></i>
                <h3 style="font-size: 24px; color: var(--dark); margin-bottom: 15px;">
                    <?php _e('Add Your Map', 'travel-mountain'); ?>
                </h3>
                <p style="font-size: 16px; color: var(--medium-gray); margin-bottom: 15px; max-width: 600px; line-height: 1.6;">
                    <?php _e('To add a Google Map:', 'travel-mountain'); ?>
                </p>
                <ol
                    style="font-size: 14px; color: var(--medium-gray); margin-bottom: 25px; max-width: 600px; margin-left: auto; margin-right: auto; text-align: left; line-height: 1.8;">
                    <li><?php _e('Go to Google Maps (maps.google.com)', 'travel-mountain'); ?></li>
                    <li><?php _e('Search for your location', 'travel-mountain'); ?></li>
                    <li><?php _e('Click "Share" → "Embed a map"', 'travel-mountain'); ?></li>
                    <li><?php _e('Copy the entire &lt;iframe&gt; code OR just the src URL', 'travel-mountain'); ?></li>
                    <li><?php _e('Paste it in: Appearance → Customize → Contact Page Settings', 'travel-mountain'); ?></li>
                </ol>
                <?php if (current_user_can('customize')): ?>
                    <a href="<?php echo admin_url('customize.php?autofocus[section]=contact_settings'); ?>" class="btn btn-primary"
                        style="display: inline-block; background: var(--primary); color: white; padding: 15px 30px; text-decoration: none; border-radius: 4px; font-weight: 600;">
                        <?php _e('Add Map Now', 'travel-mountain'); ?>
                    </a>
                <?php endif; ?>

                <?php if (current_user_can('manage_options') && !empty($map_embed)): ?>
                    <div
                        style="margin-top: 20px; padding: 15px; background: #fff3cd; border: 1px solid #ffc107; border-radius: 4px; font-size: 12px; text-align: left; max-width: 600px; margin-left: auto; margin-right: auto;">
                        <strong>Debug Info (Admin only):</strong><br>
                        Map embed code found but URL extraction failed.<br>
                        Embed code length: <?php echo strlen($map_embed); ?> characters<br>
                        First 100 chars: <?php echo esc_html(substr($map_embed, 0, 100)); ?>...
                    </div>
                <?php endif; ?>
            </div>
        </section>
    <?php endif; ?>

    <style>
        /* Form Input Focus */
        #contact-form input:focus,
        #contact-form textarea:focus,
        #contact-form select:focus {
            outline: none;
            border-color: var(--primary);
        }

        /* Select Dropdown Arrow */
        #contact-form select {
            appearance: none;
            -webkit-appearance: none;
            -moz-appearance: none;
            background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");
            background-repeat: no-repeat;
            background-position: right 15px center;
            background-size: 20px;
            padding-right: 45px !important;
        }

        /* Submit Button Hover */
        .contact-submit-btn:hover {
            background: var(--primary-dark);
            transform: translateY(-2px);
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
        }

        /* Form Messages */
        #form-message.success {
            background: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
            display: block;
        }

        #form-message.error {
            background: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
            display: block;
        }

        /* Email Links Hover */
        a[href^="mailto:"]:hover {
            color: var(--secondary) !important;
        }

        /* Privacy Policy Link Hover */
        #contact-form label a:hover {
            text-decoration: underline;
        }

        /* Responsive */
        @media (max-width: 768px) {
            section>.container>div[style*="grid-template-columns"] {
                grid-template-columns: 1fr !important;
            }

            #contact-form div[style*="grid-template-columns"] {
                grid-template-columns: 1fr !important;
            }

            .contact-map {
                height: 350px !important;
            }

            .contact-map iframe {
                height: 350px !important;
            }
        }
    </style>

    <script>
        jQuery(document).ready(function ($) {
            // Date Range Validation
            var startDateInput = $('#contact_start_date');
            var endDateInput = $('#contact_end_date');

            // Update end date minimum when start date changes
            startDateInput.on('change', function () {
                var startDate = $(this).val();
                if (startDate) {
                    endDateInput.attr('min', startDate);

                    // If end date is before start date, clear it
                    var endDate = endDateInput.val();
                    if (endDate && endDate < startDate) {
                        endDateInput.val('');
                    }
                }
            });

            // Validate dates on end date change
            endDateInput.on('change', function () {
                var startDate = startDateInput.val();
                var endDate = $(this).val();

                if (startDate && endDate && endDate < startDate) {
                    alert('<?php _e('End date must be after start date', 'travel-mountain'); ?>');
                    $(this).val('');
                }
            });

            // Contact Form Handler
            $('#contact-form').on('submit', function (e) {
                e.preventDefault();

                var $form = $(this);
                var $button = $form.find('button[type="submit"]');
                var $message = $('#form-message');
                var buttonText = $button.text();

                // Disable button and show loading
                $button.prop('disabled', true).text('<?php _e('Sending...', 'travel-mountain'); ?>');
                $message.removeClass('success error').hide();

                $.ajax({
                    url: $form.attr('action'),
                    type: 'POST',
                    data: $form.serialize(),
                    success: function (response) {
                        if (response.success) {
                            var successMsg = response.data.message;

                            // Add WhatsApp notification if URL is provided
                            if (response.data.whatsapp_url) {
                                successMsg += ' <?php _e('Opening WhatsApp...', 'travel-mountain'); ?>';
                            }

                            // Show email note if email failed (for development)
                            if (response.data.email_sent === false && response.data.email_note) {
                                console.log('Note: ' + response.data.email_note);
                            }

                            $message.addClass('success').text(successMsg).show();
                            $form[0].reset();

                            // Open WhatsApp if URL is provided
                            if (response.data.whatsapp_url) {
                                setTimeout(function () {
                                    window.open(response.data.whatsapp_url, '_blank');
                                }, 1000); // Wait 1 second to show success message first
                            }
                        } else {
                            $message.addClass('error').text(response.data.message).show();
                        }
                    },
                    error: function () {
                        $message.addClass('error').text('<?php _e('An error occurred. Please try again.', 'travel-mountain'); ?>').show();
                    },
                    complete: function () {
                        $button.prop('disabled', false).text(buttonText);
                    }
                });
            });

            // Google Maps iframe error handler
            <?php if (!empty($map_url)): ?>
                var mapIframe = $('.contact-map iframe');
                if (mapIframe.length) {
                    // Add load event listener
                    mapIframe.on('load', function () {
                        console.log('Map loaded successfully');
                    });

                    // Check if iframe is blocked after a timeout
                    setTimeout(function () {
                        try {
                            if (mapIframe[0].contentWindow) {
                                console.log('Map iframe is accessible');
                            }
                        } catch (e) {
                            console.warn('Map iframe may be blocked by browser or extension');
                        }
                    }, 2000);
                }
            <?php endif; ?>
        });
    </script>

    <?php
endwhile;
get_footer();
?>