<?php
declare(strict_types=1);

$this->assign('title', 'Book Your Creative Class');
$identity = $this->request->getAttribute('identity');
$bookingReturnPath = '/booking';
$bookingLoginUrl = $this->Url->build(['controller' => 'Pages', 'action' => 'login', '?' => ['redirect' => $bookingReturnPath]]);
$bookingRegisterUrl = $this->Url->build(['controller' => 'Users', 'action' => 'register', '?' => ['redirect' => $bookingReturnPath]]);
?>

<div class="bg-studio-ivory text-ink-900">
    <!-- Editorial intro: matches home shell (ivory, serif, soft accents). No full bleed photo hero. -->
    <section
        class="relative -mt-[4.75rem] border-b border-neutral-200/60 pt-[4.75rem] sm:-mt-20 sm:pt-20 md:-mt-[5.25rem] md:pt-[5.25rem]"
        aria-labelledby="booking-hero-heading"
    >
        <div class="pointer-events-none absolute inset-0 bg-[radial-gradient(ellipse_65%_45%_at_90%_0%,rgba(117,47,63,0.08),transparent_50%)]" aria-hidden="true"></div>
        <div class="pointer-events-none absolute -left-20 top-1/4 h-56 w-56 rounded-full bg-primary-100/35 blur-3xl" aria-hidden="true"></div>
        <div class="relative z-10 mx-auto max-w-6xl px-6 pb-10 pt-8 md:px-8 md:pb-12 md:pt-10">
            <nav class="text-xs font-medium text-neutral-500" aria-label="Breadcrumb">
                <?= $this->Html->link('Home', '/', ['class' => 'transition hover:text-primary-700']) ?>
                <span class="mx-2 text-neutral-300" aria-hidden="true">/</span>
                <span class="text-ink-900">Book</span>
            </nav>
            <p class="mt-6 text-[0.6875rem] font-semibold uppercase tracking-[0.28em] text-primary-600">
                Reservations
            </p>
            <h1 id="booking-hero-heading" class="mt-3 max-w-2xl font-serif text-3xl font-semibold leading-[1.1] tracking-tight text-ink-900 sm:text-4xl md:text-[2.65rem]">
                Book your creative class
            </h1>
            <p class="mt-4 max-w-xl text-base leading-relaxed text-neutral-600 md:text-lg">
                Three quick steps: workshop, date, then checkout. Small groups and materials are included.
            </p>
            <p class="mt-2 text-xs font-medium text-neutral-500">
                Most people finish in under two minutes.
            </p>
            <a
                href="#booking-form"
                class="mt-6 inline-flex items-center gap-2 text-xs font-semibold uppercase tracking-[0.2em] text-neutral-400 transition hover:text-primary-600"
            >
                <span>Start booking</span>
                <svg class="h-4 w-4 animate-float" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 14l-7 7m0 0l-7-7m7 7V3"/>
                </svg>
            </a>
        </div>
    </section>

    <div class="py-10 md:py-14 lg:py-16" id="booking-form">
    <div class="mx-auto max-w-6xl px-6 lg:px-8">

        <?php if ($identity): ?>
            <div class="mb-6 flex flex-wrap items-center gap-3 rounded-2xl border border-primary-200/60 bg-primary-50/50 px-4 py-3 text-sm text-neutral-800 md:px-5">
                <span class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary-100 text-primary-700" aria-hidden="true">
                    <?= $this->element('ui_icon', ['name' => 'sparkles', 'class' => 'h-4 w-4']) ?>
                </span>
                <span>Signed in as <strong class="font-semibold text-ink-900"><?= h($identity->email ?? 'member') ?></strong>. Complete the steps below to continue to secure checkout.</span>
            </div>
        <?php else: ?>
            <div class="mb-6 flex flex-col gap-3 rounded-2xl border border-amber-200/70 bg-amber-50/70 px-4 py-4 text-sm text-amber-950 sm:flex-row sm:items-center sm:justify-between sm:gap-4 md:px-5">
                <p class="text-amber-950/90">Sign in to confirm and pay. You can choose a workshop and date first.</p>
                <div class="flex flex-wrap gap-2">
                    <?= $this->Html->link(
                        'Sign in',
                        $bookingLoginUrl,
                        ['class' => 'inline-flex items-center justify-center rounded-full bg-ink-900 px-5 py-2 text-xs font-semibold text-white transition hover:bg-ink-800']
                    ) ?>
                    <?= $this->Html->link(
                        'Create account',
                        $bookingRegisterUrl,
                        ['class' => 'inline-flex items-center justify-center rounded-full border border-amber-300/80 bg-white px-5 py-2 text-xs font-semibold text-amber-950 transition hover:bg-amber-100/50']
                    ) ?>
                </div>
            </div>
        <?php endif; ?>

        <div class="grid gap-8 lg:grid-cols-12 lg:gap-10 lg:items-start">

            <!-- Form -->
            <div class="lg:col-span-7">
                <div class="overflow-hidden rounded-[1.75rem] border border-neutral-200/70 bg-white shadow-[0_20px_50px_-12px_rgba(15,23,42,0.08)] ring-1 ring-neutral-900/[0.03]">
                    <!-- Progress -->
                    <div class="border-b border-neutral-100 bg-gradient-to-b from-neutral-50/90 to-white px-5 py-5 sm:px-8 sm:py-6" aria-label="Booking progress">
                        <div class="flex flex-wrap items-end justify-between gap-2">
                            <p class="text-[0.65rem] font-bold uppercase tracking-[0.2em] text-neutral-400">Steps</p>
                            <p id="booking-step-hint" class="text-xs font-medium text-neutral-500" aria-live="polite">Choose your workshop</p>
                        </div>
                        <div class="mt-3 h-1.5 overflow-hidden rounded-full bg-neutral-200/80">
                            <div id="booking-progress-fill" class="h-full w-0 rounded-full bg-gradient-to-r from-primary-500 to-primary-400 transition-all duration-500 ease-out"></div>
                        </div>
                        <div class="mt-5 grid grid-cols-3 gap-2 sm:gap-4">
                            <div class="flex flex-col items-center gap-2 text-center">
                                <span id="booking-step-1" class="booking-step-pill flex h-10 w-10 shrink-0 items-center justify-center rounded-full border-2 border-neutral-200 bg-white transition-all">
                                    <span class="booking-step-num text-[11px] font-bold text-neutral-500">1</span>
                                </span>
                                <span class="text-[10px] font-semibold uppercase tracking-wider text-neutral-500 sm:text-[11px]">Workshop</span>
                            </div>
                            <div class="flex flex-col items-center gap-2 text-center">
                                <span id="booking-step-2" class="booking-step-pill flex h-10 w-10 shrink-0 items-center justify-center rounded-full border-2 border-neutral-200 bg-white transition-all">
                                    <span class="booking-step-num text-[11px] font-bold text-neutral-500">2</span>
                                </span>
                                <span class="text-[10px] font-semibold uppercase tracking-wider text-neutral-500 sm:text-[11px]">Date</span>
                            </div>
                            <div class="flex flex-col items-center gap-2 text-center">
                                <span id="booking-step-3" class="booking-step-pill flex h-10 w-10 shrink-0 items-center justify-center rounded-full border-2 border-neutral-200 bg-white transition-all">
                                    <span class="booking-step-num text-[11px] font-bold text-neutral-500">3</span>
                                </span>
                                <span class="text-[10px] font-semibold uppercase tracking-wider text-neutral-500 sm:text-[11px]">Pay</span>
                            </div>
                        </div>
                    </div>

                    <div class="p-5 md:p-8 md:pt-7">
                        <?= $this->Form->create(null, ['class' => 'space-y-7 md:space-y-8', 'id' => 'booking-main-form']) ?>

                        <div class="rounded-2xl border border-neutral-100 bg-neutral-50/40 p-5 md:p-6">
                            <div class="mb-4 flex items-center gap-2">
                                <span class="flex h-7 w-7 items-center justify-center rounded-lg bg-white text-xs font-bold text-primary-700 shadow-sm ring-1 ring-neutral-200/80">1</span>
                                <span class="text-xs font-bold uppercase tracking-[0.15em] text-neutral-500">Workshop</span>
                            </div>
                            <label for="lessonSelect" class="mb-2 block text-sm font-semibold text-ink-900">
                                Which class are you booking?
                            </label>
                            <div class="relative">
                                <select
                                    name="lesson_id"
                                    id="lessonSelect"
                                    onchange="updateLesson()"
                                    required
                                    class="w-full appearance-none rounded-2xl border border-neutral-200/90 bg-white py-3.5 pl-4 pr-12 text-base text-ink-900 shadow-sm transition focus:border-primary-400 focus:outline-none focus:ring-4 focus:ring-primary-100/80">
                                    <option value="" disabled selected>Select a workshop…</option>
                                    <?php foreach ($lessons as $l): ?>
                                        <option
                                            value="<?= $l->id ?>"
                                            data-desc="<?= h($l->description ?? '') ?>"
                                            data-price="<?= $l->price ?>"
                                            data-type="<?= h($l->lesson_type) ?>">
                                            <?= h($l->lesson_name) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <span class="pointer-events-none absolute right-4 top-1/2 -translate-y-1/2 text-neutral-400">
                                    <?= $this->element('ui_icon', ['name' => 'chevron_down', 'class' => 'h-5 w-5']) ?>
                                </span>
                            </div>

                            <div id="lessonPreview" class="mt-4 hidden rounded-xl border border-primary-200/50 bg-white/90 p-4 shadow-sm transition-all duration-300 md:p-5">
                                <div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">
                                    <div class="min-w-0 flex-1">
                                        <h3 id="lp_name" class="font-serif text-lg font-semibold text-ink-900 md:text-xl"></h3>
                                        <p id="lp_type" class="mt-1 text-sm font-medium text-primary-700"></p>
                                    </div>
                                    <div class="shrink-0 text-left sm:text-right">
                                        <p class="text-[10px] font-bold uppercase tracking-wider text-neutral-400">From</p>
                                        <p id="lp_price" class="font-serif text-2xl font-semibold text-primary-600 md:text-3xl"></p>
                                    </div>
                                </div>
                                <p id="lp_desc" class="mt-4 border-t border-neutral-100 pt-4 text-sm leading-relaxed text-neutral-600"></p>
                            </div>
                        </div>

                        <div id="preferredDateBlock" class="hidden space-y-4 rounded-2xl border border-neutral-100 bg-neutral-50/40 p-5 md:p-6">
                            <div class="flex items-center gap-2">
                                <span class="flex h-7 w-7 items-center justify-center rounded-lg bg-white text-xs font-bold text-primary-700 shadow-sm ring-1 ring-neutral-200/80">2</span>
                                <span class="text-xs font-bold uppercase tracking-[0.15em] text-neutral-500">Date</span>
                            </div>
                            <div class="flex flex-wrap items-center justify-between gap-3">
                                <label for="booking_date_select" class="text-sm font-semibold text-ink-900">
                                    When would you like to come in?
                                </label>
                                <div class="inline-flex rounded-full border border-neutral-200/80 bg-white p-1 text-xs font-semibold shadow-sm" role="group" aria-label="How to pick a date">
                                    <button type="button" id="booking-date-view-list" class="booking-date-view-btn rounded-full px-4 py-1.5 text-primary-800 bg-primary-50 ring-1 ring-primary-100/80">
                                        List
                                    </button>
                                    <button type="button" id="booking-date-view-cal" class="booking-date-view-btn rounded-full px-4 py-1.5 text-neutral-600 transition hover:text-neutral-900">
                                        Calendar
                                    </button>
                                </div>
                            </div>
                            <p class="text-xs leading-relaxed text-neutral-500">Only days with seats are shown (up to 6 guests per session).</p>

                            <div id="booking-date-list-wrap">
                                <div class="relative">
                                    <select
                                        id="booking_date_select"
                                        name="booking_date"
                                        disabled
                                        class="w-full appearance-none rounded-2xl border border-neutral-200/90 bg-white py-3.5 pl-4 pr-12 text-base text-ink-900 shadow-sm transition focus:border-primary-400 focus:outline-none focus:ring-4 focus:ring-primary-100/80 disabled:cursor-not-allowed disabled:bg-neutral-50 disabled:text-neutral-400">
                                        <option value="">Choose a date…</option>
                                    </select>
                                    <span class="pointer-events-none absolute right-4 top-1/2 -translate-y-1/2 text-neutral-400">
                                        <?= $this->element('ui_icon', ['name' => 'chevron_down', 'class' => 'h-5 w-5']) ?>
                                    </span>
                                </div>
                            </div>

                            <div id="booking-date-calendar-panel" class="hidden rounded-2xl border border-neutral-200/80 bg-white p-3 shadow-sm sm:p-4">
                                    <div class="mb-3 flex items-center justify-between gap-2">
                                        <button type="button" id="booking-cal-prev" class="inline-flex items-center justify-center rounded-lg border border-neutral-200 bg-white p-2 text-neutral-600 transition hover:bg-neutral-50 hover:text-neutral-900 disabled:cursor-not-allowed disabled:opacity-40" aria-label="Previous month">
                                            <?= $this->element('ui_icon', ['name' => 'chevron_left', 'class' => 'h-5 w-5']) ?>
                                        </button>
                                        <span id="booking-cal-month-label" class="min-w-0 flex-1 text-center text-sm font-semibold text-neutral-900"></span>
                                        <button type="button" id="booking-cal-next" class="inline-flex items-center justify-center rounded-lg border border-neutral-200 bg-white p-2 text-neutral-600 transition hover:bg-neutral-50 hover:text-neutral-900 disabled:cursor-not-allowed disabled:opacity-40" aria-label="Next month">
                                            <?= $this->element('ui_icon', ['name' => 'chevron_right', 'class' => 'h-5 w-5']) ?>
                                        </button>
                                    </div>
                                    <div id="booking-cal-grid-host" class="min-h-[14rem]"></div>
                                    <p class="mt-3 text-center text-[11px] text-neutral-500">Available days are highlighted; full or outside the booking window are dimmed.</p>
                                </div>

                                <p class="hidden text-xs text-amber-700" id="booking_date_no_slots" role="status">No open dates in the next window for this workshop. Try another class.</p>
                                <p class="hidden text-xs text-red-600" id="booking_date_error" role="alert">Please select a date.</p>
                        </div>

                        <div id="booking-payment-block" class="hidden space-y-4 rounded-2xl border border-neutral-100 bg-neutral-50/40 p-5 md:p-6">
                            <div class="flex items-center gap-2">
                                <span class="flex h-7 w-7 items-center justify-center rounded-lg bg-white text-xs font-bold text-primary-700 shadow-sm ring-1 ring-neutral-200/80">3</span>
                                <span class="text-xs font-bold uppercase tracking-[0.15em] text-neutral-500">Payment</span>
                            </div>
                            <?= $this->Form->hidden('payment_method', ['value' => 'stripe']) ?>
                            <div class="rounded-2xl border border-primary-200/70 bg-white p-4 shadow-sm ring-1 ring-primary-500/[0.06] md:p-5">
                                <p class="text-sm font-semibold text-ink-900">Pay with card (Stripe)</p>
                                <p class="mt-2 text-xs leading-relaxed text-neutral-600">
                                    Checkout is handled by Stripe. When you continue, you will open Stripe’s secure page to enter your card and complete payment, then you will be sent back here.
                                </p>
                                <ul class="mt-3 space-y-1.5 text-xs text-neutral-600">
                                    <li class="flex gap-2">
                                        <span class="mt-0.5 text-primary-600" aria-hidden="true">✓</span>
                                        <span>Encrypted card processing; we do not store your full card details.</span>
                                    </li>
                                    <li class="flex gap-2">
                                        <span class="mt-0.5 text-primary-600" aria-hidden="true">✓</span>
                                        <span>Booking is confirmed after payment succeeds on Stripe.</span>
                                    </li>
                                </ul>
                            </div>
                        </div>

                        <div class="pt-1">
                            <?php if ($identity): ?>
                                <?= $this->Form->button(
                                    'Continue to Stripe checkout',
                                    [
                                        'class' => 'flex w-full items-center justify-center gap-2 rounded-2xl bg-primary-600 px-6 py-4 text-base font-semibold text-white shadow-lg shadow-primary-900/10 transition hover:bg-primary-700 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-400 focus-visible:ring-offset-2 active:scale-[0.99]',
                                    ]
                                ) ?>
                            <?php else: ?>
                                <?= $this->Html->link(
                                    'Sign in to continue',
                                    $bookingLoginUrl,
                                    [
                                        'class' => 'flex w-full cursor-pointer items-center justify-center gap-2 rounded-2xl border-2 border-primary-600 bg-white px-6 py-4 text-base font-semibold text-primary-700 transition hover:bg-primary-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary-400 focus-visible:ring-offset-2',
                                    ]
                                ) ?>
                                <p class="mt-3 text-center text-xs text-neutral-500">
                                    After sign in you will return here to finish. New?
                                    <?= $this->Html->link('Create an account', $bookingRegisterUrl, ['class' => 'font-medium text-primary-700 underline decoration-primary-300 underline-offset-2 hover:text-primary-800']) ?>
                                </p>
                            <?php endif; ?>
                        </div>

                        <?= $this->Form->end() ?>
                    </div>

                    <div class="flex flex-wrap items-center justify-center gap-x-6 gap-y-2 border-t border-neutral-100 bg-neutral-50/50 px-5 py-3.5 text-center text-[11px] text-neutral-500 md:justify-between md:px-8 md:text-left">
                        <span class="inline-flex items-center gap-1.5">
                            <span class="h-1.5 w-1.5 rounded-full bg-primary-500" aria-hidden="true"></span>
                            Secure checkout (Stripe)
                        </span>
                        <span>Email confirmation after payment</span>
                    </div>
                </div>
            </div>

            <!-- Sidebar: short tips, scannable -->
            <aside class="lg:col-span-5 lg:sticky lg:top-28" aria-label="Booking tips">
                <div class="space-y-4">
                    <div class="rounded-[1.5rem] border border-neutral-200/70 bg-white p-5 shadow-[0_12px_40px_-12px_rgba(15,23,42,0.06)] md:p-6">
                        <h3 class="font-serif text-base font-semibold text-ink-900 md:text-lg">At a glance</h3>
                        <ul class="mt-4 space-y-3.5 text-sm leading-relaxed text-neutral-600">
                            <li class="flex gap-3">
                                <span class="mt-0.5 text-primary-600" aria-hidden="true"><?= $this->element('ui_icon', ['name' => 'book_open', 'class' => 'h-5 w-5']) ?></span>
                                <span>Descriptions and price update as soon as you pick a workshop.</span>
                            </li>
                            <li class="flex gap-3">
                                <span class="mt-0.5 text-primary-600" aria-hidden="true"><?= $this->element('ui_icon', ['name' => 'calendar_days', 'class' => 'h-5 w-5']) ?></span>
                                <span>List and calendar stay in sync. Change workshop anytime to refresh dates.</span>
                            </li>
                            <li class="flex gap-3">
                                <span class="mt-0.5 text-primary-600" aria-hidden="true"><?= $this->element('ui_icon', ['name' => 'question_mark_circle', 'class' => 'h-5 w-5']) ?></span>
                                <span>Questions? Chat with the studio assistant or see <?= $this->Html->link('FAQs', '/faqs', ['class' => 'font-medium text-primary-700 underline decoration-primary-300 underline-offset-2 hover:text-primary-800']) ?>.</span>
                            </li>
                        </ul>
                    </div>
                    <div class="rounded-[1.5rem] border border-dashed border-primary-200/80 bg-gradient-to-br from-primary-50/40 to-white p-5 md:p-6">
                        <p class="text-sm leading-relaxed text-neutral-700">
                            <strong class="text-ink-900">Browsing?</strong>
                            <?= $this->Html->link('Compare workshops', '/workshops', ['class' => 'font-medium text-primary-700 underline decoration-primary-300 underline-offset-2 hover:text-primary-800']) ?>, then come back. Chat links can prefill this form for you.
                        </p>
                    </div>
                </div>
            </aside>
        </div>

        <?php if ($identity !== null): ?>
        <!-- Booking history (signed-in users only) -->
        <section class="mt-20 md:mt-28" aria-labelledby="booking-history-heading">
            <div class="mb-10 flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
                <div>
                    <h2 id="booking-history-heading" class="font-serif text-3xl font-semibold tracking-tight text-ink-900 md:text-4xl">
                        Your bookings
                    </h2>
                </div>
            </div>

            <?php if (empty($bookings)): ?>
                <div class="rounded-3xl border border-neutral-200/80 bg-white p-10 text-center shadow-soft md:p-14">
                    <div class="mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-primary-50 text-primary-600">
                        <?= $this->element('ui_icon', ['name' => 'calendar_days', 'class' => 'h-7 w-7']) ?>
                    </div>
                    <p class="mt-6 font-medium text-ink-900">No bookings yet</p>
                    <p class="mx-auto mt-2 max-w-md text-sm text-neutral-600">
                        When you complete a workshop reservation, it will show up here with status and payment details.
                    </p>
                </div>
            <?php else: ?>
                <div class="grid gap-6 md:grid-cols-2">
                    <?php foreach ($bookings as $b): ?>
                        <?php
                        $payment = $b->payments[0] ?? null;
                        $bdRaw = $b->booking_date;
                        $dateDisplay = $bdRaw instanceof \DateTimeInterface
                            ? $bdRaw->format('l, j M Y')
                            : h((string)$bdRaw);
                        $statusClass = match ($b->status) {
                            'confirmed' => 'bg-primary-50 text-primary-900 ring-primary-100',
                            'pending' => 'bg-amber-50 text-amber-900 ring-amber-100',
                            'cancelled' => 'bg-red-50 text-red-800 ring-red-100',
                            'rejected' => 'bg-neutral-100 text-neutral-700 ring-neutral-200',
                            default => 'bg-neutral-100 text-neutral-700 ring-neutral-200',
                        };
                        $payStatus = $payment ? $payment->payment_status : null;
                        $payClass = $payStatus === 'paid'
                            ? 'bg-primary-50 text-primary-900 ring-primary-100'
                            : ($payStatus === 'unpaid'
                                ? 'bg-orange-50 text-orange-900 ring-orange-100'
                                : 'bg-neutral-100 text-neutral-600 ring-neutral-200');
                        ?>
                        <article class="flex flex-col rounded-3xl border border-neutral-200/80 bg-white p-6 shadow-soft transition hover:border-primary-200/60 hover:shadow-md md:p-7">
                            <div class="flex flex-wrap items-start justify-between gap-3 border-b border-neutral-100 pb-4">
                                <div class="min-w-0">
                                    <h3 class="font-serif text-lg font-semibold text-ink-900 md:text-xl">
                                        <?= h($b->lesson->lesson_name ?? 'Workshop') ?>
                                    </h3>
                                    <p class="mt-1 text-sm text-neutral-500"><?= h($dateDisplay) ?></p>
                                </div>
                                <span class="inline-flex shrink-0 rounded-full px-3 py-1 text-xs font-semibold ring-1 <?= h($statusClass) ?>">
                                    <?= h(ucfirst((string)$b->status)) ?>
                                </span>
                            </div>
                            <dl class="mt-4 grid gap-3 text-sm">
                                <div class="flex items-center justify-between gap-4">
                                    <dt class="text-neutral-500">Payment method</dt>
                                    <dd class="font-medium text-neutral-800"><?= $payment ? h(ucfirst((string)$payment->payment_method)) : 'N/A' ?></dd>
                                </div>
                                <div class="flex items-center justify-between gap-4">
                                    <dt class="text-neutral-500">Payment status</dt>
                                    <dd>
                                        <span class="inline-flex rounded-full px-2.5 py-0.5 text-xs font-semibold ring-1 <?= h($payClass) ?>">
                                            <?= $payment ? h(ucfirst((string)$payment->payment_status)) : 'No data' ?>
                                        </span>
                                    </dd>
                                </div>
                            </dl>
                            <div class="mt-6 flex flex-wrap items-center gap-3 border-t border-neutral-100 pt-5">
                                <?php if ($payment && $payment->payment_status === 'unpaid'): ?>
                                    <?= $this->Html->link(
                                        'Pay now',
                                        ['action' => 'payAgain', $payment->id],
                                        ['class' => 'inline-flex items-center justify-center rounded-lg bg-primary-600 px-4 py-2.5 text-sm font-semibold text-white transition hover:bg-primary-700']
                                    ) ?>
                                <?php endif; ?>
                                <?php if ($b->status === 'pending'): ?>
                                    <?= $this->Form->postLink(
                                        'Cancel request',
                                        ['action' => 'cancel', $b->id],
                                        [
                                            'confirm' => 'Cancel this booking request?',
                                            'class' => 'inline-flex items-center justify-center rounded-lg border border-red-200 bg-white px-4 py-2.5 text-sm font-semibold text-red-700 transition hover:bg-red-50',
                                        ]
                                    ) ?>
                                <?php endif; ?>
                                <?php if ((!$payment || $payment->payment_status === 'paid') && $b->status !== 'pending'): ?>
                                    <span class="text-sm text-neutral-400">No actions</span>
                                <?php endif; ?>
                            </div>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </section>
        <?php endif; ?>
    </div>
    </div>

    <footer class="border-t border-neutral-200/80 bg-ink-900 text-neutral-300" role="contentinfo">
        <div class="mx-auto max-w-7xl px-6 py-14 lg:px-8 lg:py-16">
            <div class="grid gap-12 sm:grid-cols-2 lg:grid-cols-4">
                <div>
                    <p class="font-script text-2xl text-primary-400">CandleCraft</p>
                    <p class="font-serif text-lg font-semibold text-white">Academy</p>
                    <p class="mt-4 max-w-xs text-sm leading-relaxed text-neutral-400">
                        Creative workshops in Melbourne: candle making, pottery, and knitting in a warm, small group studio.
                    </p>
                </div>
                <div>
                    <h3 class="text-[0.65rem] font-semibold uppercase tracking-[0.2em] text-neutral-500">Explore</h3>
                    <ul class="mt-5 space-y-3 text-sm">
                        <li><?= $this->Html->link('Home', '/', ['class' => 'hover:text-white transition-colors']) ?></li>
                        <li><?= $this->Html->link('About', '/pages/about', ['class' => 'hover:text-white transition-colors']) ?></li>
                        <li><?= $this->Html->link('Workshops', '/workshops', ['class' => 'hover:text-white transition-colors']) ?></li>
                        <li><?= $this->Html->link('FAQs', '/faqs', ['class' => 'hover:text-white transition-colors']) ?></li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-[0.65rem] font-semibold uppercase tracking-[0.2em] text-neutral-500">Workshops</h3>
                    <ul class="mt-5 space-y-3 text-sm">
                        <li><?= $this->Html->link('Candle making', '/workshops#workshop-candle', ['class' => 'hover:text-white transition-colors']) ?></li>
                        <li><?= $this->Html->link('Pottery', '/workshops#workshop-pottery', ['class' => 'hover:text-white transition-colors']) ?></li>
                        <li><?= $this->Html->link('Knitting', '/workshops#workshop-knitting', ['class' => 'hover:text-white transition-colors']) ?></li>
                        <li><?= $this->Html->link('Multi class passes', '/workshops', ['class' => 'hover:text-white transition-colors']) ?></li>
                    </ul>
                </div>
                <div>
                    <h3 class="text-[0.65rem] font-semibold uppercase tracking-[0.2em] text-neutral-500">Contact</h3>
                    <ul class="mt-5 space-y-4 text-sm">
                        <li>
                            <a href="mailto:CandleCraftAcademy@gmail.com" class="font-medium text-white hover:text-primary-300 transition-colors">CandleCraftAcademy@gmail.com</a>
                        </li>
                        <li>
                            <a href="tel:+61412345678" class="hover:text-white transition-colors">+61 412 345 678</a>
                        </li>
                        <li>
                            <button type="button" onclick="openContactModal()" class="text-left text-primary-400 hover:text-primary-300 transition-colors">
                                Send a message
                            </button>
                        </li>
                    </ul>
                </div>
            </div>
            <div class="mt-12 flex flex-col items-center justify-between gap-4 border-t border-neutral-800 pt-8 text-xs text-neutral-500 md:flex-row">
                <p>&copy; <?= date('Y') ?> CandleCraft Academy. All rights reserved.</p>
                <div class="flex flex-wrap items-center justify-center gap-6">
                    <button type="button" onclick="openPrivacyModal()" class="font-inherit cursor-pointer border-0 bg-transparent p-0 hover:text-neutral-300">Privacy Policy</button>
                    <button type="button" onclick="openTermsModal()" class="font-inherit cursor-pointer border-0 bg-transparent p-0 hover:text-neutral-300">Terms of Service</button>
                    <a href="mailto:CandleCraftAcademy@gmail.com" class="hover:text-neutral-300">Email</a>
                </div>
                <p class="text-neutral-600">Made by Nexify (Team 112)</p>
            </div>
        </div>
    </footer>
</div>

<script>
(function () {
    var pendingPrefillDate = <?= json_encode($prefillBookingDate ?? null) ?>;

    function ucfirst(str) {
        return str.charAt(0).toUpperCase() + str.slice(1);
    }

    function bookingHashStr(s) {
        var h = 2166136261 >>> 0;
        for (var i = 0; i < s.length; i++) {
            h ^= s.charCodeAt(i);
            h = Math.imul(h, 16777619) >>> 0;
        }
        return h >>> 0;
    }

    /** Dummy availability per workshop (id + type). Max 6 spots. */
    function bookingAvailability(lessonId, lessonType, ymd) {
        var t = (lessonType || '').toLowerCase().replace(/\s+/g, '-');
        var h = bookingHashStr(String(lessonId) + '|' + t + '|' + ymd);
        var salt = bookingHashStr(t + '|workshop-salt') % 37;
        var mix = (h + salt) % 100;

        if (mix < 13) {
            return { spots: 0, label: 'Full' };
        }
        if (mix < 23) {
            return { spots: 1, label: '1 seat' };
        }
        if (mix < 38) {
            return { spots: 2, label: '2 seats' };
        }
        if (mix < 55) {
            return { spots: 4, label: '4 seats' };
        }
        return { spots: 6, label: '6 seats' };
    }

    function pad2(n) {
        return String(n).padStart(2, '0');
    }

    function refreshPaymentBlockVisibility() {
        var block = document.getElementById('booking-payment-block');
        var dateSel = document.getElementById('booking_date_select');
        if (!block || !dateSel) {
            return;
        }
        var show = !dateSel.disabled && !!dateSel.value;
        block.classList.toggle('hidden', !show);
    }

    function refreshBookingStepRail() {
        var lesson = document.getElementById('lessonSelect');
        var dateSel = document.getElementById('booking_date_select');
        var w1 = !!(lesson && lesson.value);
        var w2 = !!(dateSel && !dateSel.disabled && dateSel.value);
        var w3 = w2;

        var fill = document.getElementById('booking-progress-fill');
        if (fill) {
            var pct = w2 ? 100 : w1 ? 33 : 0;
            fill.style.width = pct + '%';
        }

        var hint = document.getElementById('booking-step-hint');
        if (hint) {
            if (w3) {
                hint.textContent = 'Continue to Stripe to pay';
            } else if (w1) {
                hint.textContent = 'Pick an available date';
            } else {
                hint.textContent = 'Choose your workshop';
            }
        }

        var done =
            'booking-step-pill flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-primary-600 text-white shadow-md shadow-primary-600/20 ring-4 ring-primary-100/50 transition-all';
        var doneNum = 'booking-step-num text-[11px] font-bold text-white';
        var todo =
            'booking-step-pill flex h-10 w-10 shrink-0 items-center justify-center rounded-full border-2 border-neutral-200 bg-white text-neutral-400 transition-all';
        var todoNum = 'booking-step-num text-[11px] font-bold text-neutral-500';

        for (var s = 1; s <= 3; s++) {
            var el = document.getElementById('booking-step-' + s);
            if (!el) {
                continue;
            }
            var num = el.querySelector('.booking-step-num');
            var ok = s === 1 ? w1 : s === 2 ? w2 : w3;
            el.className = ok ? done : todo;
            if (num) {
                num.className = ok ? doneNum : todoNum;
            }
        }

        refreshPaymentBlockVisibility();
    }

    function bookingMonthIdx(d) {
        return d.getFullYear() * 12 + d.getMonth();
    }

    function bookingCalendarBounds() {
        var now = new Date();
        now.setHours(0, 0, 0, 0);
        var max = new Date(now.getTime());
        max.setDate(max.getDate() + 120);
        return {
            min: new Date(now.getFullYear(), now.getMonth(), 1),
            maxMonthStart: new Date(max.getFullYear(), max.getMonth(), 1),
        };
    }

    var _bookingCalInit = new Date();
    _bookingCalInit.setHours(0, 0, 0, 0);
    var bookingCalY = _bookingCalInit.getFullYear();
    var bookingCalM = _bookingCalInit.getMonth();
    var bookingDateViewMode = 'list';

    function bookingResetCalCursor() {
        var n = new Date();
        n.setHours(0, 0, 0, 0);
        bookingCalY = n.getFullYear();
        bookingCalM = n.getMonth();
    }

    function bookingSyncCalCursorToSelectIfValid() {
        var sel = document.getElementById('booking_date_select');
        if (!sel || !sel.value || !/^\d{4}-\d{2}-\d{2}$/.test(sel.value)) {
            return;
        }
        var parts = sel.value.split('-');
        var yy = parseInt(parts[0], 10);
        var mm = parseInt(parts[1], 10) - 1;
        var want = new Date(yy, mm, 1);
        var bounds = bookingCalendarBounds();
        if (
            bookingMonthIdx(want) >= bookingMonthIdx(bounds.min) &&
            bookingMonthIdx(want) <= bookingMonthIdx(bounds.maxMonthStart)
        ) {
            bookingCalY = yy;
            bookingCalM = mm;
        }
    }

    function setBookingDateViewMode(mode) {
        bookingDateViewMode = mode;
        var listWrap = document.getElementById('booking-date-list-wrap');
        var calPanel = document.getElementById('booking-date-calendar-panel');
        var btnList = document.getElementById('booking-date-view-list');
        var btnCal = document.getElementById('booking-date-view-cal');
        if (listWrap) {
            listWrap.classList.toggle('hidden', mode !== 'list');
        }
        if (calPanel) {
            calPanel.classList.toggle('hidden', mode !== 'calendar');
        }
        if (btnList && btnCal) {
            var onList = mode === 'list';
            btnList.classList.toggle('text-primary-800', onList);
            btnList.classList.toggle('bg-primary-50', onList);
            btnList.classList.toggle('ring-1', onList);
            btnList.classList.toggle('ring-primary-100/80', onList);
            btnList.classList.toggle('text-neutral-600', !onList);
            btnList.classList.toggle('bg-transparent', !onList);
            btnCal.classList.toggle('text-primary-800', !onList);
            btnCal.classList.toggle('bg-primary-50', !onList);
            btnCal.classList.toggle('ring-1', !onList);
            btnCal.classList.toggle('ring-primary-100/80', !onList);
            btnCal.classList.toggle('text-neutral-600', onList);
            btnCal.classList.toggle('bg-transparent', onList);
        }
        if (mode === 'calendar') {
            bookingSyncCalCursorToSelectIfValid();
            renderBookingCalGrid();
        }
    }

    function renderBookingCalGrid() {
        var host = document.getElementById('booking-cal-grid-host');
        var labelEl = document.getElementById('booking-cal-month-label');
        var prevBtn = document.getElementById('booking-cal-prev');
        var nextBtn = document.getElementById('booking-cal-next');
        var sel = document.getElementById('booking_date_select');
        if (!host || !labelEl || !sel) {
            return;
        }

        var lessonEl = document.getElementById('lessonSelect');
        var opt = lessonEl && lessonEl.options[lessonEl.selectedIndex];
        var lessonId = opt && opt.value ? opt.value : '';
        var lessonType = opt && opt.dataset && opt.dataset.type ? opt.dataset.type : '';

        var y = bookingCalY;
        var m = bookingCalM;
        var first = new Date(y, m, 1);
        var lastDay = new Date(y, m + 1, 0).getDate();
        var startDow = first.getDay();
        labelEl.textContent = first.toLocaleDateString(undefined, { month: 'long', year: 'numeric' });

        var bounds = bookingCalendarBounds();
        if (prevBtn) {
            var prevMonth = new Date(y, m - 1, 1);
            prevBtn.disabled = bookingMonthIdx(prevMonth) < bookingMonthIdx(bounds.min);
        }
        if (nextBtn) {
            var nextMonth = new Date(y, m + 1, 1);
            nextBtn.disabled = bookingMonthIdx(nextMonth) > bookingMonthIdx(bounds.maxMonthStart);
        }

        host.innerHTML = '';
        var grid = document.createElement('div');
        grid.className = 'grid grid-cols-7 gap-1 sm:gap-2';
        var dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
        for (var h = 0; h < dayNames.length; h++) {
            var hn = document.createElement('div');
            hn.className = 'flex h-7 items-center justify-center text-[10px] font-semibold uppercase tracking-wide text-neutral-400 sm:text-xs';
            hn.textContent = dayNames[h];
            grid.appendChild(hn);
        }
        for (var pad = 0; pad < startDow; pad++) {
            grid.appendChild(document.createElement('div'));
        }

        var today0 = new Date();
        today0.setHours(0, 0, 0, 0);
        var horizonEnd = new Date(today0.getTime());
        horizonEnd.setDate(horizonEnd.getDate() + 120);

        var selectedVal = sel.value;

        for (var day = 1; day <= lastDay; day++) {
            var cellDate = new Date(y, m, day);
            cellDate.setHours(0, 0, 0, 0);
            var ymd =
                cellDate.getFullYear() +
                '-' +
                pad2(cellDate.getMonth() + 1) +
                '-' +
                pad2(cellDate.getDate());

            var btn = document.createElement('button');
            btn.type = 'button';
            btn.dataset.ymd = ymd;
            btn.className =
                'flex h-9 w-full max-w-[2.75rem] mx-auto items-center justify-center rounded-lg text-sm font-medium transition sm:h-10 sm:max-w-none';

            var past = cellDate < today0;
            var beyond = cellDate > horizonEnd;

            if (!lessonId || past || beyond) {
                btn.disabled = true;
                btn.classList.add('cursor-not-allowed', 'text-neutral-300', 'opacity-40');
                btn.textContent = String(day);
                grid.appendChild(btn);
                continue;
            }

            var av = bookingAvailability(lessonId, lessonType, ymd);
            if (av.spots <= 0) {
                btn.disabled = true;
                btn.classList.add('cursor-not-allowed', 'text-neutral-400', 'opacity-50', 'line-through');
                btn.textContent = String(day);
                btn.title = 'Full';
            } else {
                btn.classList.add('bg-white', 'text-neutral-800', 'ring-1', 'ring-neutral-200', 'hover:bg-primary-50', 'hover:ring-primary-200');
                btn.title = av.label + ' left';
                btn.textContent = String(day);
                if (selectedVal === ymd) {
                    btn.classList.remove('bg-white', 'ring-neutral-200', 'hover:bg-primary-50', 'hover:ring-primary-200');
                    btn.classList.add('bg-primary-600', 'text-white', 'ring-2', 'ring-primary-500', 'hover:bg-primary-600');
                }
                (function (pickYmd) {
                    btn.addEventListener('click', function () {
                        sel.value = pickYmd;
                        sel.dispatchEvent(new Event('change', { bubbles: true }));
                        renderBookingCalGrid();
                        var er = document.getElementById('booking_date_error');
                        if (er) {
                            er.classList.add('hidden');
                        }
                    });
                })(ymd);
            }
            grid.appendChild(btn);
        }
        host.appendChild(grid);
    }

    function populateBookingDateDropdown(lessonId, lessonType) {
        var block = document.getElementById('preferredDateBlock');
        var sel = document.getElementById('booking_date_select');
        var noSlots = document.getElementById('booking_date_no_slots');
        var err = document.getElementById('booking_date_error');
        if (!block || !sel) {
            refreshBookingStepRail();
            return;
        }
        if (err) {
            err.classList.add('hidden');
        }
        if (!lessonId) {
            block.classList.add('hidden');
            sel.disabled = true;
            sel.required = false;
            sel.innerHTML = '<option value="">Choose a date…</option>';
            if (noSlots) {
                noSlots.classList.add('hidden');
            }
            refreshBookingStepRail();
            return;
        }

        block.classList.remove('hidden');
        sel.disabled = false;
        sel.required = true;
        sel.innerHTML = '';

        var ph = document.createElement('option');
        ph.value = '';
        ph.textContent = 'Choose a date…';
        ph.disabled = true;
        ph.selected = true;
        sel.appendChild(ph);

        var start = new Date();
        start.setHours(0, 0, 0, 0);
        var horizon = 120;

        for (var i = 0; i < horizon; i++) {
            var d = new Date(start.getTime());
            d.setDate(start.getDate() + i);
            var ymd = d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate());
            var a = bookingAvailability(lessonId, lessonType, ymd);
            if (a.spots <= 0) {
                continue;
            }
            var o = document.createElement('option');
            o.value = ymd;
            var label = d.toLocaleDateString(undefined, { weekday: 'short', month: 'short', day: 'numeric', year: 'numeric' });
            o.textContent = label + ', ' + a.label + ' left';
            sel.appendChild(o);
        }

        if (sel.options.length <= 1) {
            if (noSlots) {
                noSlots.classList.remove('hidden');
            }
        } else if (noSlots) {
            noSlots.classList.add('hidden');
        }

        if (pendingPrefillDate) {
            var want = pendingPrefillDate;
            pendingPrefillDate = null;
            for (var j = 0; j < sel.options.length; j++) {
                if (sel.options[j].value === want) {
                    sel.value = want;
                    ph.selected = false;
                    break;
                }
            }
        }

        bookingResetCalCursor();
        if (bookingDateViewMode === 'calendar') {
            renderBookingCalGrid();
        }
        refreshBookingStepRail();
    }

    window.updateLesson = function () {
        var lessonEl = document.getElementById('lessonSelect');
        var opt = lessonEl.options[lessonEl.selectedIndex];
        var preview = document.getElementById('lessonPreview');

        if (!opt.value) {
            if (preview) {
                preview.classList.add('hidden');
            }
            populateBookingDateDropdown('', '');
            return;
        }

        if (preview) {
            preview.classList.remove('hidden');
        }
        document.getElementById('lp_name').innerText = opt.textContent.split('(')[0].trim();
        document.getElementById('lp_type').innerText = opt.dataset.type ? ucfirst(opt.dataset.type) : '';
        document.getElementById('lp_desc').innerText = opt.dataset.desc || '';
        var price = parseInt(opt.dataset.price, 10);
        document.getElementById('lp_price').innerText = isNaN(price) ? '' : ('$' + price.toLocaleString());
        populateBookingDateDropdown(opt.value, opt.dataset.type || '');
    };

    var form = document.getElementById('booking-main-form');
    if (form) {
        form.addEventListener('submit', function (e) {
            var lesson = document.getElementById('lessonSelect');
            if (!lesson || !lesson.value) {
                return;
            }
            var ds = document.getElementById('booking_date_select');
            if (!ds || ds.disabled || !ds.value) {
                e.preventDefault();
                var err = document.getElementById('booking_date_error');
                if (err) {
                    err.classList.remove('hidden');
                }
            }
        });
    }

    var prefillLessonId = <?= json_encode($prefillLessonId ?? null) ?>;
    var lessonSelect = document.getElementById('lessonSelect');
    if (prefillLessonId && lessonSelect) {
        var pOpt = lessonSelect.querySelector('option[value="' + String(prefillLessonId) + '"]');
        if (pOpt) {
            lessonSelect.value = String(prefillLessonId);
            window.updateLesson();
        }
    }

    var dateSelect = document.getElementById('booking_date_select');
    if (dateSelect) {
        dateSelect.addEventListener('change', function () {
            var er = document.getElementById('booking_date_error');
            if (er) {
                er.classList.add('hidden');
            }
            bookingSyncCalCursorToSelectIfValid();
            renderBookingCalGrid();
            refreshBookingStepRail();
        });
    }

    var btnViewList = document.getElementById('booking-date-view-list');
    var btnViewCal = document.getElementById('booking-date-view-cal');
    if (btnViewList) {
        btnViewList.addEventListener('click', function () {
            setBookingDateViewMode('list');
        });
    }
    if (btnViewCal) {
        btnViewCal.addEventListener('click', function () {
            setBookingDateViewMode('calendar');
        });
    }

    var calPrev = document.getElementById('booking-cal-prev');
    if (calPrev) {
        calPrev.addEventListener('click', function () {
            var bounds = bookingCalendarBounds();
            var cur = new Date(bookingCalY, bookingCalM, 1);
            cur.setMonth(cur.getMonth() - 1);
            if (bookingMonthIdx(cur) < bookingMonthIdx(bounds.min)) {
                return;
            }
            bookingCalY = cur.getFullYear();
            bookingCalM = cur.getMonth();
            renderBookingCalGrid();
        });
    }
    var calNext = document.getElementById('booking-cal-next');
    if (calNext) {
        calNext.addEventListener('click', function () {
            var bounds = bookingCalendarBounds();
            var cur = new Date(bookingCalY, bookingCalM, 1);
            cur.setMonth(cur.getMonth() + 1);
            if (bookingMonthIdx(cur) > bookingMonthIdx(bounds.maxMonthStart)) {
                return;
            }
            bookingCalY = cur.getFullYear();
            bookingCalM = cur.getMonth();
            renderBookingCalGrid();
        });
    }

    refreshBookingStepRail();
})();
</script>
