<?php
// phpcs:disable PluginCheck.Security.DirectDB.UnescapedDBParameter, WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- Booking form reads plugin-managed service data from custom tables.
if ( ! defined( 'ABSPATH' ) ) { exit; }
$yatoon_booking_template = sanitize_key((string) get_option('yatoon_booking_template', 'beauty'));
if (!in_array($yatoon_booking_template, array('clean', 'beauty', 'luxury'), true)) {
    $yatoon_booking_template = 'beauty';
}
$yatoon_policy_enabled = get_option('yatoon_policy_enabled', '0') === '1';
$yatoon_policy_require_ack = get_option('yatoon_policy_require_ack', '1') === '1';
$yatoon_policy_title = get_option('yatoon_policy_title', __('Cancellation & No-Show Policy', 'yatoon-booking-system'));
$yatoon_policy_text = get_option('yatoon_policy_text', __('Please let us know as soon as possible if you need to cancel or reschedule. This helps us offer the time to another customer.', 'yatoon-booking-system'));
$yatoon_policy_ack_label = get_option('yatoon_policy_ack_label', __('I have read and understand the cancellation and no-show policy.', 'yatoon-booking-system'));
?>
<div class="sbs-booking-container yatoon-template-<?php echo esc_attr($yatoon_booking_template); ?>">
    <?php if (get_option('yatoon_turnstile_enabled', '0') === '1' && get_option('yatoon_turnstile_site_key', '')) : ?>
    <div id="yatoon-turnstile-widget" class="cf-turnstile" data-sitekey="<?php echo esc_attr(get_option('yatoon_turnstile_site_key')); ?>" data-size="invisible" data-execution="execute" data-callback="yatoonOnTurnstileSolved" data-error-callback="yatoonOnTurnstileError" style="position:absolute;left:-9999px;top:-9999px;"></div>
    <script>
    window.yatoonTurnstileToken = '';
    window.yatoonTurnstileResolvers = [];
    function yatoonOnTurnstileSolved(token) {
        window.yatoonTurnstileToken = token;
        window.yatoonTurnstileResolvers.forEach(function(r) { r(token); });
        window.yatoonTurnstileResolvers = [];
    }
    function yatoonOnTurnstileError() {
        window.yatoonTurnstileResolvers.forEach(function(r) { r(''); });
        window.yatoonTurnstileResolvers = [];
    }
    // Runs the invisible check right when the customer submits - never stale,
    // never blocked by a hidden container. If Cloudflare doesn't respond within
    // 8 seconds (network hiccup, ad blocker, etc.) we fail OPEN so a real
    // customer is never stuck: the booking still goes through, just without
    // this extra layer for that one submission.
    window.yatoonGetTurnstileToken = function() {
        return new Promise(function(resolve) {
            if (typeof turnstile === 'undefined' || !document.getElementById('yatoon-turnstile-widget')) {
                resolve('');
                return;
            }
            var settled = false;
            var finish = function(token) {
                if (settled) return;
                settled = true;
                resolve(token || '');
            };
            window.yatoonTurnstileResolvers.push(finish);
            setTimeout(function() { finish(''); }, 8000);
            try {
                turnstile.execute('#yatoon-turnstile-widget');
            } catch (e) {
                finish('');
            }
        });
    };
    </script>
    <?php endif; ?>
    <div class="sbs-booking-steps" role="list" aria-label="<?php esc_attr_e('Booking steps', 'yatoon-booking-system'); ?>">
        <div class="sbs-step-track"></div>
        <div class="sbs-step-progress" id="sbs-step-progress"></div>
        <div class="sbs-step active" data-step="1" role="listitem">
            <div class="sbs-step-bubble">
                <span class="sbs-step-number">1</span>
                <svg class="sbs-step-check" width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2.5 7L5.5 10L11.5 4" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <span class="sbs-step-title"><?php esc_html_e('Service', 'yatoon-booking-system'); ?></span>
        </div>
        <div class="sbs-step" data-step="2" role="listitem">
            <div class="sbs-step-bubble">
                <span class="sbs-step-number">2</span>
                <svg class="sbs-step-check" width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2.5 7L5.5 10L11.5 4" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <span class="sbs-step-title"><?php esc_html_e('Options', 'yatoon-booking-system'); ?></span>
        </div>
        <div class="sbs-step" data-step="3" role="listitem">
            <div class="sbs-step-bubble">
                <span class="sbs-step-number">3</span>
                <svg class="sbs-step-check" width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2.5 7L5.5 10L11.5 4" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <span class="sbs-step-title"><?php esc_html_e('Staff', 'yatoon-booking-system'); ?></span>
        </div>
        <div class="sbs-step" data-step="4" role="listitem">
            <div class="sbs-step-bubble">
                <span class="sbs-step-number">4</span>
                <svg class="sbs-step-check" width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2.5 7L5.5 10L11.5 4" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <span class="sbs-step-title"><?php esc_html_e('Date & Time', 'yatoon-booking-system'); ?></span>
        </div>
        <div class="sbs-step" data-step="5" role="listitem">
            <div class="sbs-step-bubble">
                <span class="sbs-step-number">5</span>
                <svg class="sbs-step-check" width="14" height="14" viewBox="0 0 14 14" fill="none"><path d="M2.5 7L5.5 10L11.5 4" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>
            </div>
            <span class="sbs-step-title"><?php esc_html_e('Details', 'yatoon-booking-system'); ?></span>
        </div>
    </div>

    <div class="sbs-booking-form">
        <!-- Step 1: Select Service -->
        <div class="sbs-form-step sbs-step-1 active">
            <h3><?php esc_html_e('Select a Service', 'yatoon-booking-system'); ?></h3>
            <?php if (get_option('yatoon_ai_service_helper_enabled', '1') === '1') : ?>
                <?php
                $yatoon_ai_available = class_exists('YATOON_AI') && YATOON_AI::is_text_available();
                $yatoon_ai_status    = class_exists('YATOON_AI') ? YATOON_AI::status_message() : __('AI requires WordPress 7.0 or newer.', 'yatoon-booking-system');
                $yatoon_ai_display_mode = get_option('yatoon_ai_display_mode', 'collapsed');
                $yatoon_ai_frontend_title = trim((string) get_option('yatoon_ai_frontend_title', __('AI Style Assistant', 'yatoon-booking-system')));
                if ($yatoon_ai_frontend_title === '') { $yatoon_ai_frontend_title = __('AI Style Assistant', 'yatoon-booking-system'); }
                $yatoon_ai_font_size = min(24, max(11, absint(get_option('yatoon_ai_frontend_font_size', 14))));
                $yatoon_ai_text_color = sanitize_hex_color(get_option('yatoon_ai_frontend_text_color', '#111827')) ?: '#111827';
                $yatoon_ai_bg_color = sanitize_hex_color(get_option('yatoon_ai_frontend_bg_color', '#f8fafc')) ?: '#f8fafc';
                $yatoon_ai_privacy_note = trim((string) get_option('yatoon_ai_privacy_note', __('Privacy note: Please avoid sensitive, medical, or payment details.', 'yatoon-booking-system')));
                $yatoon_ai_style_attr = sprintf('--yatoon-ai-title-size:%dpx;--yatoon-ai-title-color:%s;--yatoon-ai-toggle-bg:%s;', $yatoon_ai_font_size, $yatoon_ai_text_color, $yatoon_ai_bg_color);
                ?>
                <div class="yatoon-ai-helper yatoon-ai-collapsible <?php echo $yatoon_ai_display_mode === 'collapsed' ? 'is-collapsed' : 'is-expanded'; ?>" id="yatoon-ai-service-helper" style="<?php echo esc_attr($yatoon_ai_style_attr); ?>">
                    <div class="yatoon-ai-helper-header">
                        <strong><?php echo esc_html($yatoon_ai_frontend_title); ?></strong>
                        <button type="button" class="yatoon-ai-collapse" aria-label="<?php esc_attr_e('Collapse AI Assistant', 'yatoon-booking-system'); ?>">&times;</button>
                        <span><?php esc_html_e('Tell us the style, length, occasion, budget, or concerns you have. Our AI assistant will suggest services from this menu.', 'yatoon-booking-system'); ?></span>
                    </div>
                    <?php if ($yatoon_ai_display_mode === 'collapsed') : ?>
                    <button type="button" class="yatoon-ai-toggle" aria-expanded="false"><?php echo esc_html($yatoon_ai_frontend_title); ?></button>
                    <?php endif; ?>
                    <div class="yatoon-ai-helper-body">
                    <?php if (!$yatoon_ai_available) : ?>
                        <p class="yatoon-ai-notice"><?php echo esc_html($yatoon_ai_status); ?></p>
                    <?php endif; ?>
                    <textarea id="yatoon-ai-service-need" rows="2" placeholder="<?php esc_attr_e('Example: soft pink almond nails for a wedding, medium length, with simple nail art', 'yatoon-booking-system'); ?>" <?php disabled(!$yatoon_ai_available); ?>></textarea>
                    <?php if ($yatoon_ai_privacy_note !== '') : ?>
                        <p class="yatoon-ai-privacy-note"><?php echo esc_html($yatoon_ai_privacy_note); ?></p>
                    <?php endif; ?>
                    <div class="yatoon-ai-helper-actions">
                        <button type="button" class="sbs-btn" id="yatoon-ai-service-submit" <?php disabled(!$yatoon_ai_available); ?>><?php esc_html_e('Ask AI for Recommendations', 'yatoon-booking-system'); ?></button>
                        <span id="yatoon-ai-service-status" aria-live="polite"></span>
                    </div>
                    <div class="yatoon-ai-result" id="yatoon-ai-service-result" style="display:none;"></div>
                                    </div>
                </div>
            <?php endif; ?>
            
            <?php
            // Get all unique categories
            $categories = array(); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
            foreach ($services as $service) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                if ($service->category && !in_array($service->category, $categories)) {
                    $categories[] = $service->category; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                }
            }
            
            // Sort categories by admin-configured order
            $co_saved = get_option('yatoon_category_order', array()); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
            if (!empty($co_saved) && is_array($co_saved)) {
                usort($categories, function($a, $b) use ($co_saved) {
                    $ia = isset($co_saved[$a]) ? intval($co_saved[$a]) : 999;
                    $ib = isset($co_saved[$b]) ? intval($co_saved[$b]) : 999;
                    return $ia - $ib;
                });
            }

            // If categories exist, show category tabs
            if (!empty($categories)) :
            ?>
                <div class="sbs-category-tabs">
                    <button type="button" class="sbs-category-tab active" data-category="all">
                        <?php esc_html_e('Featured', 'yatoon-booking-system'); ?>
                    </button>
                    <?php // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
                    <?php foreach ($categories as $category) : ?>
                        <button type="button" class="sbs-category-tab" data-category="<?php echo esc_attr($category); ?>">
                            <?php echo esc_html($category); ?>
                        </button>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
            
            <div class="sbs-services-list">
                <?php if (!empty($services)) :
                    // -- Bulk-fetch service ratings (one query for all services) --
                    // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared
                    $yatoon_ratings_table = esc_sql( $wpdb->prefix . 'yatoon_reviews' );
                    $yatoon_show_ratings  = get_option('yatoon_show_ratings_on_cards', '1') === '1';
                    $yatoon_show_next_op  = get_option('yatoon_show_next_opening', '1') === '1';
                    $yatoon_ratings_map   = array();
                    if ($yatoon_show_ratings) {
                        $yatoon_rating_rows = yatoon_db_get_results(
                            "SELECT service_name, AVG(rating) AS avg_rating, COUNT(*) AS rating_count
                             FROM {$yatoon_ratings_table}
                             WHERE status = 'approved' AND rating > 0
                             GROUP BY service_name"
                        );
                        if (is_array($yatoon_rating_rows)) {
                            foreach ($yatoon_rating_rows as $yatoon_rating_row) {
                                $yatoon_ratings_map[$yatoon_rating_row->service_name] = array(
                                    'avg'   => round((float)$yatoon_rating_row->avg_rating, 1),
                                    'count' => (int)$yatoon_rating_row->rating_count,
                                );
                            }
                        }
                    }
                    // phpcs:enable
                ?>
                    <?php // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound ?>
                    <?php foreach ($services as $service) :
                        $yatoon_service_rating = $yatoon_ratings_map[$service->name] ?? null;
                    ?>
                        <div class="sbs-service-item ybs-svc-card has-hero-image<?php echo empty($service->image_url) ? ' ybs-svc-card-placeholder' : ''; ?>"
                             data-service-id="<?php echo esc_attr($service->id); ?>" 
                             data-service-name="<?php echo esc_attr($service->name); ?>"
                             data-service-price="<?php echo esc_attr($service->price); ?>"
                             data-service-duration="<?php echo esc_attr($service->duration_minutes); ?>"
                             data-service-desc="<?php echo esc_attr( wp_strip_all_tags( $service->description ?? '' ) ); ?>"
                             data-service-image="<?php echo esc_url( $service->image_url ?? '' ); ?>"
                             data-allow-design-upload="<?php echo esc_attr( !empty($service->allow_design_upload) ? '1' : '0' ); ?>"
                             data-category="<?php echo esc_attr($service->category ?: 'uncategorized'); ?>">
                            <div class="ybs-svc-hero">
                                <?php if (!empty($service->image_url)) : ?>
                                    <img src="<?php echo esc_url($service->image_url); ?>" alt="<?php echo esc_attr($service->name); ?>" loading="lazy">
                                <?php else : ?>
                                    <div class="ybs-svc-hero-fallback" aria-hidden="true">
                                        <span><?php echo esc_html( mb_substr( trim( (string) $service->name ), 0, 1 ) ); ?></span>
                                    </div>
                                <?php endif; ?>
                                <?php if (!empty($service->is_featured)) : ?>
                                    <span class="ybs-svc-popular-overlay"><?php esc_html_e('Popular', 'yatoon-booking-system'); ?></span>
                                <?php endif; ?>
                            </div>
                            <div class="sbs-service-layout">
                                <div class="sbs-service-content">
                                    <div class="sbs-service-header">
                                        <h4 class="sbs-service-name"><?php echo esc_html($service->name); ?></h4>
                                        <button type="button" class="sbs-book-btn ybs-pill-btn">
                                            <?php esc_html_e('Book', 'yatoon-booking-system'); ?>
                                        </button>
                                    </div>
                                    <div class="ybs-svc-pills">
                                        <span class="ybs-pill ybs-pill-duration"><?php echo esc_html($service->duration_minutes); ?> min</span>
                                        <?php if ($yatoon_service_rating && $yatoon_service_rating['count'] > 0) : ?>
                                            <span class="ybs-pill ybs-pill-rating"><?php esc_html_e('Rating', 'yatoon-booking-system'); ?> <?php echo esc_html($yatoon_service_rating['avg']); ?> <span class="ybs-pill-count">(<?php echo esc_html($yatoon_service_rating['count']); ?>)</span></span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="sbs-service-details">
                                        <span class="sbs-service-duration" style="display:none;">
                                            <?php echo esc_html($service->duration_minutes); ?> min
                                        </span>
                                    </div>
                                    <?php if ($service->description) : ?>
                                        <?php
                                        $full_desc  = esc_html($service->description); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                        $char_limit = 90; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                        $need_more  = mb_strlen($service->description) > $char_limit; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                        $short_desc = $need_more // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                            ? esc_html(mb_substr($service->description, 0, $char_limit)) . '...'
                                            : $full_desc;
                                        ?>
                                        <div class="sbs-service-desc-wrap">
                                            <span class="sbs-desc-short"><?php echo esc_html( $short_desc ); ?></span>
                                            <?php if ($need_more) : ?>
                                                <span class="sbs-desc-full" style="display:none;"><?php echo esc_html( $full_desc ); ?></span>
                                                <a href="#" class="sbs-read-more" onclick="(function(el){var w=el.closest('.sbs-service-desc-wrap');var s=w.querySelector('.sbs-desc-short');var f=w.querySelector('.sbs-desc-full');var open=f.style.display!=='none';s.style.display=open?'':'none';f.style.display=open?'none':'';el.textContent=open?' <?php echo esc_js(__('Read more', 'yatoon-booking-system')); ?>':' <?php echo esc_js(__('Show less', 'yatoon-booking-system')); ?>';return false;})(this);return false;"> <?php esc_html_e('Read more', 'yatoon-booking-system'); ?></a>
                                            <?php endif; ?>
                                        </div>
                                    <?php endif; ?>
                                    <div class="sbs-service-price-row">
                                        <?php 
                                        $min_price = $service->price; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                        $max_price = $service->price; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                        
                                        // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
                                        // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                        $service_options = yatoon_db_get_results($wpdb->prepare(
                                            "SELECT price_modifier FROM {$wpdb->prefix}yatoon_service_options WHERE service_id = %d",
                                            $service->id
                                        ));
                                        
                                        if (!empty($service_options)) {
                                            foreach ($service_options as $opt) { // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                                $option_price = $service->price + $opt->price_modifier; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                                if ($option_price < $min_price) $min_price = $option_price; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                                if ($option_price > $max_price) $max_price = $option_price; // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                            }
                                        }
                                        
                                        if ($min_price == $max_price) {
                                            echo '<span class="sbs-service-price">$' . number_format($service->price, 0) . '</span>';
                                        } else {
                                            echo '<span class="sbs-service-price">from $' . number_format($min_price, 0) . '</span>';
                                        }
                                        ?>
                                    </div>
                                    <?php if ($yatoon_show_next_op): ?>
                                    <div class="ybs-next-opening" data-svc-id="<?php echo esc_attr($service->id); ?>" aria-live="polite">
                                        <span class="ybs-next-opening-dot"></span>
                                        <span class="ybs-next-opening-text"><?php esc_html_e('Checking availability...', 'yatoon-booking-system'); ?></span>
                                    </div>
                                    <?php endif; ?>
                                </div>
                                <?php if (empty($service->image_url)) : ?>
                                    <!-- Image already shown as hero above; no thumb needed -->
                                <?php endif; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else : ?>
                    <p class="sbs-no-services"><?php esc_html_e('No services available at this time.', 'yatoon-booking-system'); ?></p>
                <?php endif; ?>
            </div>
        </div>

        <!-- Step 2: Select Options (Fresha-style) -->
        <div class="sbs-form-step sbs-step-2">
            <h3><?php esc_html_e('Select Options', 'yatoon-booking-system'); ?></h3>
            <div class="sbs-options-container">
                <div class="sbs-loading">
                    <span class="spinner"></span>
                    <?php esc_html_e('Loading options...', 'yatoon-booking-system'); ?>
                </div>
            </div>
            <?php if (get_option('yatoon_allow_design_upload', '1') === '1') : ?>
            <div class="yatoon-design-upload-group yatoon-design-upload-card">
                <div class="yatoon-design-upload-copy">
                    <strong><?php esc_html_e('Upload a reference photo', 'yatoon-booking-system'); ?></strong>
                    <span><?php esc_html_e('Optional - choose a photo that shows the color, shape, or nail art you want. JPG, PNG, GIF, or WebP, up to 10 MB.', 'yatoon-booking-system'); ?></span>
                </div>
                <label class="yatoon-design-file-button" for="sbs-design-reference"><?php esc_html_e('Choose reference photo', 'yatoon-booking-system'); ?></label>
                <input type="file" id="sbs-design-reference" name="design_reference" accept="image/jpeg,image/png,image/gif,image/webp">
                <div id="sbs-design-preview" class="yatoon-design-preview" style="display:none;"></div>
            </div>
            <?php endif; ?>
            <div class="sbs-navigation-buttons">
                <button type="button" class="sbs-btn sbs-btn-back"><?php esc_html_e('Back', 'yatoon-booking-system'); ?></button>
                <button type="button" class="sbs-btn sbs-btn-next"><?php esc_html_e('Continue', 'yatoon-booking-system'); ?></button>
            </div>
        </div>

        <!-- Step 3: Select Staff -->
        <div class="sbs-form-step sbs-step-3">
            <h3><?php esc_html_e('Select Staff Member', 'yatoon-booking-system'); ?></h3>
            <div class="sbs-staff-grid">
                <div class="sbs-loading">
                    <span class="spinner"></span>
                    <?php esc_html_e('Loading staff...', 'yatoon-booking-system'); ?>
                </div>
            </div>
            <div class="sbs-navigation-buttons">
                <button type="button" class="sbs-btn sbs-btn-back"><?php esc_html_e('Back', 'yatoon-booking-system'); ?></button>
            </div>
        </div>

        <!-- Step 4: Select Date & Time -->
        <div class="sbs-form-step sbs-step-4">
            <h3><?php esc_html_e('Select Date & Time', 'yatoon-booking-system'); ?></h3>
            <div class="sbs-datetime-container">
                <div class="sbs-calendar-container">
                    <div class="sbs-calendar-header">
                        <button type="button" class="sbs-view-toggle active" data-view="week"><?php esc_html_e('Week', 'yatoon-booking-system'); ?></button>
                        <button type="button" class="sbs-view-toggle sbs-month-opener" data-view="month"><?php esc_html_e('Month', 'yatoon-booking-system'); ?></button>
                    </div>
                    <div class="sbs-week-view active">
                        <div class="sbs-week-navigation">
                            <button type="button" class="sbs-week-prev" aria-label="Previous week">&lt;</button>
                            <span class="sbs-week-range"></span>
                            <button type="button" class="sbs-week-next" aria-label="Next week">&gt;</button>
                        </div>
                        <div class="sbs-week-days"></div>
                    </div>
                    <div class="sbs-month-view">
                        <!-- Month calendar rendered by JS -->
                    </div>
                </div>
                <div id="sbs-next-openings" class="sbs-next-openings" style="display:none;"></div>
                <div class="sbs-time-slots">
                    <p class="sbs-times-hint"><?php esc_html_e('Select a date above to see available times', 'yatoon-booking-system'); ?></p>
                </div>
                <!-- Hidden legacy date input for code that still references it -->
                <input type="hidden" id="sbs-date-picker">
            </div>
            <div class="sbs-navigation-buttons">
                <button type="button" class="sbs-btn sbs-btn-back"><?php esc_html_e('Back', 'yatoon-booking-system'); ?></button>
            </div>
        </div>

        <!-- Step 5: Customer Details -->
        <div class="sbs-form-step sbs-step-5">
            <h3><?php esc_html_e('Your Information', 'yatoon-booking-system'); ?></h3>
            
            <div class="sbs-booking-summary">
                <h4><?php esc_html_e('Booking Summary', 'yatoon-booking-system'); ?></h4>
                <div class="sbs-summary-item">
                    <strong><?php esc_html_e('Service:', 'yatoon-booking-system'); ?></strong>
                    <span id="sbs-summary-service">-</span>
                </div>
                <div class="sbs-summary-item" id="sbs-summary-options-container" style="display: none;">
                    <strong><?php esc_html_e('Options:', 'yatoon-booking-system'); ?></strong>
                    <span id="sbs-summary-options">-</span>
                </div>
                <div class="sbs-summary-item">
                    <strong><?php esc_html_e('Staff:', 'yatoon-booking-system'); ?></strong>
                    <span id="sbs-summary-staff">-</span>
                </div>
                <div class="sbs-summary-item">
                    <strong><?php esc_html_e('Date & Time:', 'yatoon-booking-system'); ?></strong>
                    <span id="sbs-summary-datetime">-</span>
                </div>
                <div class="sbs-summary-item">
                    <strong><?php esc_html_e('Duration:', 'yatoon-booking-system'); ?></strong>
                    <span id="sbs-summary-duration">-</span>
                </div>
                <div class="sbs-summary-item sbs-summary-total">
                    <strong><?php esc_html_e('Total:', 'yatoon-booking-system'); ?></strong>
                    <span id="sbs-summary-total">$0.00</span>
                </div>
            </div>

            <div class="sbs-checkout-trust-grid" aria-label="<?php esc_attr_e('Booking confidence', 'yatoon-booking-system'); ?>">
                <div>
                    <strong><?php esc_html_e('Instant confirmation', 'yatoon-booking-system'); ?></strong>
                    <span><?php esc_html_e('You will receive booking details after the appointment is submitted.', 'yatoon-booking-system'); ?></span>
                </div>
                <div>
                    <strong><?php esc_html_e('Easy to manage', 'yatoon-booking-system'); ?></strong>
                    <span><?php esc_html_e('Use your confirmation link to reschedule or cancel when the salon allows it.', 'yatoon-booking-system'); ?></span>
                </div>
                <div>
                    <strong><?php esc_html_e('Salon-ready policies', 'yatoon-booking-system'); ?></strong>
                    <span><?php esc_html_e('Cancellation and no-show rules can be reviewed before you book.', 'yatoon-booking-system'); ?></span>
                </div>
            </div>

            <form id="sbs-customer-form" class="sbs-customer-form">
                <div class="sbs-hp-field" aria-hidden="true" style="position:absolute;left:-9999px;top:-9999px;width:1px;height:1px;overflow:hidden;">
                    <label for="sbs-website">Leave this field empty</label>
                    <input type="text" id="sbs-website" name="website" tabindex="-1" autocomplete="off">
                </div>
                <input type="hidden" id="sbs-form-rendered-at" name="form_rendered_at" value="<?php echo esc_attr( (string) time() ); ?>">
                <div class="sbs-form-group">
                    <label for="sbs-customer-name"><?php esc_html_e('Full Name', 'yatoon-booking-system'); ?> *</label>
                    <input type="text" id="sbs-customer-name" name="customer_name" required>
                </div>

                <div class="sbs-form-group">
                    <label for="sbs-customer-email"><?php esc_html_e('Email', 'yatoon-booking-system'); ?> *</label>
                    <input type="email" id="sbs-customer-email" name="customer_email" required>
                </div>

                <?php
                $yatoon_phone_required = get_option('yatoon_phone_required','1') === '1';
                $yatoon_phone_mode     = get_option('yatoon_phone_mode','us_only');
                $yatoon_phone_country  = get_option('yatoon_phone_preset_country','us');
                $yatoon_verify_email   = get_option('yatoon_verify_email_otp','0') === '1';
                $yatoon_verify_sms     = get_option('yatoon_verify_sms_otp','0') === '1';
                ?>
                <div class="sbs-form-group">
                    <label for="sbs-customer-phone"><?php esc_html_e('Phone', 'yatoon-booking-system'); ?><?php if($yatoon_phone_required): ?> *<?php endif; ?></label>
                    <?php if ($yatoon_phone_mode === 'us_only'): ?>
                        <input type="tel" id="sbs-customer-phone" name="customer_phone"
                               placeholder="(555) 000-0000"
                               <?php if($yatoon_phone_required) echo 'required'; ?>>
                    <?php else: ?>
                        <div id="sbs-phone-intl-wrap" style="display:flex;align-items:stretch;gap:0;">
                            <input type="hidden" id="sbs-customer-phone" name="customer_phone">
                            <input type="tel" id="sbs-phone-display"
                                   autocomplete="tel"
                                   placeholder="<?php echo $yatoon_phone_mode==='intl_picker' ? esc_attr__('Phone number','yatoon-booking-system') : ''; ?>"
                                   style="flex:1;"
                                   <?php if($yatoon_phone_required) echo 'required'; ?>>
                        </div>
                        <script>
                        document.addEventListener('DOMContentLoaded',function(){
                            var display = document.getElementById('sbs-phone-display');
                            var hidden  = document.getElementById('sbs-customer-phone');
                            var mode    = '<?php echo esc_js($yatoon_phone_mode); ?>';
                            var preset  = '<?php echo esc_js($yatoon_phone_country); ?>';
                            if(typeof intlTelInput === 'undefined'){ return; }
                            var useIpGeo = !!(window.yatoonData && window.yatoonData.useIpGeo);
                            var iti = intlTelInput(display, {
                                initialCountry: mode==='intl_preset' ? preset : (useIpGeo ? 'auto' : 'us'),
                                onlyCountries: [],
                                separateDialCode: true,
                                allowDropdown: mode !== 'intl_preset'
                            });
                            function syncHidden(){
                                if(iti.isValidNumber()){
                                    hidden.value = iti.getNumber(); // E.164 e.g. +8613800138000
                                } else {
                                    hidden.value = iti.getNumber() || display.value;
                                }
                            }
                            display.addEventListener('input', syncHidden);
                            display.addEventListener('countrychange', syncHidden);
                            // Hook form submit to sync
                            var form = display.closest('form');
                            if(form){ form.addEventListener('submit', syncHidden, true); }
                        });
                        </script>
                    <?php endif; ?>
                    <?php if($yatoon_verify_email || $yatoon_verify_sms): ?>
                    <div id="sbs-otp-section" style="display:none;margin-top:10px;">
                        <div id="sbs-otp-prompt" style="font-size:13px;color:#374151;margin-bottom:6px;"></div>
                        <div style="display:flex;gap:8px;align-items:center;">
                            <input type="text" id="sbs-otp-input" maxlength="6" placeholder="6-digit code"
                                   style="width:130px;padding:8px 10px;border:1px solid #d1d5db;border-radius:6px;font-size:14px;letter-spacing:2px;">
                            <button type="button" id="sbs-otp-verify-btn" class="sbs-btn" style="padding:8px 16px;font-size:13px;">Verify</button>
                            <button type="button" id="sbs-otp-resend-btn" class="sbs-btn" style="padding:8px 14px;font-size:13px;display:none;">Resend</button>
                        </div>
                        <div id="sbs-otp-msg" style="font-size:12px;margin-top:5px;"></div>
                    </div>
                    <?php endif; ?>
                </div>

                <div class="sbs-form-group">
                    <label for="sbs-customer-notes"><?php esc_html_e('Additional Notes', 'yatoon-booking-system'); ?></label>
                    <textarea id="sbs-customer-notes" name="notes" rows="3"></textarea>
                </div>

                <div class="sbs-form-group sbs-policy-box" data-global-policy="<?php echo esc_attr($yatoon_policy_enabled ? '1' : '0'); ?>" data-global-policy-ack="<?php echo esc_attr($yatoon_policy_require_ack ? '1' : '0'); ?>" style="display:none;">
                    <h3><?php echo esc_html($yatoon_policy_title); ?></h3>
                    <div><?php echo nl2br(esc_html($yatoon_policy_text)); ?></div>
                    <label>
                        <input type="checkbox" id="sbs-policy-acknowledged" name="policy_acknowledged" value="1">
                        <span><?php echo esc_html($yatoon_policy_ack_label); ?></span>
                    </label>
                </div>

                <div class="sbs-navigation-buttons">
                    <button type="button" class="sbs-btn sbs-btn-back"><?php esc_html_e('Back', 'yatoon-booking-system'); ?></button>
                    <button type="submit" class="sbs-btn sbs-btn-submit">
                        <?php esc_html_e('Confirm Booking', 'yatoon-booking-system'); ?>
                    </button>
                </div>
            </form>
        </div>

        <!-- Success Message -->
        <div class="sbs-form-step sbs-step-success" style="display: none;">
            <div class="sbs-success-message">
                <div class="sbs-success-icon">
                    <svg width="36" height="36" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M7 18L14.5 25.5L29 10" stroke="#fff" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"/>
                    </svg>
                </div>
                <h3><?php esc_html_e('You\'re all set!', 'yatoon-booking-system'); ?></h3>
                <p class="sbs-success-sub"><?php esc_html_e('A confirmation email is on its way. We look forward to seeing you!', 'yatoon-booking-system'); ?></p>

                <div id="sbs-success-actions" class="sbs-success-actions" style="display:none;"></div>

                <div class="sbs-success-cal-row" id="sbs-success-cal-row" style="display:none;">
                    <p class="sbs-success-cal-label"><?php esc_html_e('Add to your calendar', 'yatoon-booking-system'); ?></p>
                    <div class="sbs-success-cal-btns">
                        <a id="sbs-cal-google" href="#" target="_blank" rel="noopener" class="sbs-cal-btn sbs-cal-google">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><rect x="3" y="4" width="18" height="16" rx="2" stroke="currentColor" stroke-width="1.8"/><path d="M3 9h18" stroke="currentColor" stroke-width="1.8"/><path d="M8 2v4M16 2v4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
                            <?php esc_html_e('Google Calendar', 'yatoon-booking-system'); ?>
                        </a>
                        <a id="sbs-cal-ics" href="#" class="sbs-cal-btn sbs-cal-apple">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none"><rect x="3" y="4" width="18" height="16" rx="2" stroke="currentColor" stroke-width="1.8"/><path d="M3 9h18" stroke="currentColor" stroke-width="1.8"/><path d="M8 2v4M16 2v4" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>
                            <?php esc_html_e('Apple / Outlook (.ics)', 'yatoon-booking-system'); ?>
                        </a>
                    </div>
                </div>

                <?php
                $yatoon_whatsapp_enabled = get_option('yatoon_whatsapp_enabled', '0') === '1';
                $yatoon_whatsapp_raw     = get_option('yatoon_whatsapp_number', get_option('yatoon_business_phone', ''));
                $yatoon_whatsapp_number  = preg_replace('/[^0-9+]/', '', $yatoon_whatsapp_raw);
                $yatoon_whatsapp_label   = get_option('yatoon_whatsapp_label', 'Message us on WhatsApp');
                $yatoon_whatsapp_prefill = get_option('yatoon_whatsapp_prefill', 'Hi! I just booked an appointment.');
                if ($yatoon_whatsapp_enabled && $yatoon_whatsapp_number): ?>
                <div class="sbs-success-whatsapp">
                    <a href="https://wa.me/<?php echo esc_attr(ltrim($yatoon_whatsapp_number, '+')); ?>?text=<?php echo rawurlencode($yatoon_whatsapp_prefill); ?>" target="_blank" rel="noopener" class="sbs-whatsapp-btn">
                        <svg width="17" height="17" viewBox="0 0 24 24" fill="currentColor" style="flex-shrink:0;"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
                        <?php echo esc_html($yatoon_whatsapp_label); ?>
                    </a>
                </div>
                <?php endif; ?>

                <div class="sbs-rebooking-nudge" id="sbs-rebooking-nudge" style="display:none;">
                    <div class="sbs-rebooking-inner">
                        <span class="sbs-rebooking-icon">
                            <svg width="18" height="18" viewBox="0 0 24 24" fill="none"><path d="M12 2a10 10 0 1 0 10 10A10 10 0 0 0 12 2zm0 18a8 8 0 1 1 8-8 8 8 0 0 1-8 8zm.5-13H11v6l5.25 3.15.75-1.23-4.5-2.67z" fill="currentColor"/></svg>
                        </span>
                        <span class="sbs-rebooking-text"><?php echo esc_html(get_option('yatoon_rebooking_nudge_text', 'Most clients rebook every 2-3 weeks. Want us to remind you?')); ?></span>
                        <button type="button" class="sbs-rebooking-btn sbs-success-book-again"><?php echo esc_html(get_option('yatoon_rebooking_nudge_btn', 'Book next visit')); ?></button>
                    </div>
                </div>

                <?php if (class_exists('YATOON_License') && YATOON_License::is_pro()) : ?>
                <div class="sbs-recurring-setup" id="sbs-recurring-setup" style="display:none;">
                    <div class="sbs-recurring-inner">
                        <p class="sbs-recurring-title">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" style="vertical-align:middle;margin-right:6px;"><path d="M12 4V1L8 5l4 4V6c3.31 0 6 2.69 6 6s-2.69 6-6 6-6-2.69-6-6H4c0 4.42 3.58 8 8 8s8-3.58 8-8-3.58-8-8-8z" fill="currentColor"/></svg>
                            <?php esc_html_e('Make this a recurring appointment?', 'yatoon-booking-system'); ?>
                        </p>
                        <div class="sbs-recurring-options">
                            <label><?php esc_html_e('Repeat every', 'yatoon-booking-system'); ?></label>
                            <div class="sbs-recurring-freq-btns">
                                <button type="button" class="sbs-freq-btn" data-weeks="1"><?php esc_html_e('1 week', 'yatoon-booking-system'); ?></button>
                                <button type="button" class="sbs-freq-btn active" data-weeks="2"><?php esc_html_e('2 weeks', 'yatoon-booking-system'); ?></button>
                                <button type="button" class="sbs-freq-btn" data-weeks="3"><?php esc_html_e('3 weeks', 'yatoon-booking-system'); ?></button>
                                <button type="button" class="sbs-freq-btn" data-weeks="4"><?php esc_html_e('4 weeks', 'yatoon-booking-system'); ?></button>
                            </div>
                            <label style="margin-top:10px;"><?php esc_html_e('For how many visits?', 'yatoon-booking-system'); ?></label>
                            <select id="sbs-recurring-count" class="sbs-recurring-count-select">
                                <option value="3">3 visits</option>
                                <option value="6" selected>6 visits</option>
                                <option value="9">9 visits</option>
                                <option value="12">12 visits</option>
                            </select>
                        </div>
                        <button type="button" class="sbs-recurring-confirm-btn" id="sbs-recurring-confirm">
                            <?php esc_html_e('Set up recurring appointments', 'yatoon-booking-system'); ?>
                        </button>
                        <div id="sbs-recurring-result" style="display:none;"></div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Hidden inputs to store selected data -->
    <input type="hidden" id="sbs-selected-service-id" value="">
    <input type="hidden" id="sbs-selected-staff-id" value="">
    <input type="hidden" id="sbs-selected-start-at" value="">
    <input type="hidden" id="sbs-selected-options" value="">
</div>
