<?php
/**
 * Booking — public-facing widget.
 *
 * URL: /book
 * Multi-step booking flow, server-side state via query params:
 *   step 1: pick service
 *   step 2: pick provider (filtered to providers that offer that service)
 *   step 3: pick date + slot (AJAX or page reload — we use plain reload)
 *   step 4: enter contact details + confirm → POST
 *   step 5: success page
 *
 * ?embed=1 strips the outer canvas + footer.
 */

if (!defined('SLATE_ROOT')) {
    require_once dirname(__DIR__, 3) . '/config.php';
}
require_once dirname(__DIR__) . '/BookingAPI.php';
BookingAPI::ensureSchema();

$embed     = !empty($_GET['embed']);
$serviceId = (int)($_GET['service']  ?? 0);
$providerId= (int)($_GET['provider'] ?? 0);
$date      = (string)($_GET['date']  ?? '');
$slot      = (string)($_GET['slot']  ?? '');

// ── POST: confirm submission ─────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!csrf_verify()) {
        bookpub_render_error('Security check failed. Please try again.', $embed);
        return;
    }
    $name  = trim((string)($_POST['customer_name']  ?? ''));
    $email = trim((string)($_POST['customer_email'] ?? ''));
    $phone = trim((string)($_POST['customer_phone'] ?? ''));
    $notes = trim((string)($_POST['notes']          ?? ''));

    $startsAt = ($_POST['date'] ?? '') . ' ' . ($_POST['slot'] ?? '');
    $args = [
        'service_id'    => (int)($_POST['service']  ?? 0),
        'provider_id'   => (int)($_POST['provider'] ?? 0),
        'starts_at'     => $startsAt,
        'customer_name' => $name,
        'customer_email'=> $email,
        'customer_phone'=> $phone,
        'notes'         => $notes,
        'customer_id'   => Auth::customerId(),
    ];
    $result = BookingAPI::createAppointment($args);
    if ($result['ok']) {
        bookpub_render_success($result['ref'], $args, $embed);
        return;
    }
    bookpub_render_step4_with_error($args, $result['error'], $embed);
    return;
}

// ── GET routing by what's in the query ───────────────────────
if ($serviceId === 0) {
    bookpub_render_step1($embed);
    return;
}
$service = BookingAPI::getService($serviceId);
if (!$service || empty($service['is_active'])) {
    bookpub_render_error('That service is no longer available.', $embed);
    return;
}

if ($providerId === 0) {
    bookpub_render_step2($service, $embed);
    return;
}
$provider = Database::row("SELECT * FROM booking_providers WHERE id = ? AND tenant_id = ? AND is_active = 1",
    [$providerId, current_tenant_id()]);
if (!$provider) {
    bookpub_render_error('That provider isn\'t available.', $embed);
    return;
}

if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date) || $slot === '') {
    bookpub_render_step3($service, $provider, $date, $embed);
    return;
}

// We have service + provider + date + slot — show confirm form.
bookpub_render_step4($service, $provider, $date, $slot, [], '', $embed);


// ─────────────────────────────────────────────────────────────
//                          Renderers
// ─────────────────────────────────────────────────────────────

function bookpub_layout_start(string $title, bool $embed): void {
    $siteName = Database::setting('site_name') ?: 'Slate';
    slate_ui_emit_css();
    ?>
    <!DOCTYPE html><html lang="<?= e(I18n::currentLocale()) ?>"><head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
        <title><?= e($title) ?> — <?= e($siteName) ?></title>
        <meta name="csrf" content="<?= e(csrf_token()) ?>">
        <link rel="stylesheet" href="<?= e(plugin_url('booking', 'assets/css/public.css')) ?>">
    </head><body class="book-public<?= $embed ? ' book-public-embed' : '' ?>">
    <main class="book-shell">
        <article class="book-card">
    <?php
}
function bookpub_layout_end(bool $embed): void {
    echo '</article></main>';
    if (!$embed) {
        echo '<footer class="book-footer text-sm text-muted text-center">Powered by '
           . e(Database::setting('site_name') ?: 'Slate') . '</footer>';
    }
    echo '</body></html>';
}

function bookpub_stepper(int $current, bool $embed): void {
    $labels = ['Service','Provider','When','Confirm'];
    echo '<ol class="book-stepper">';
    foreach ($labels as $i => $label) {
        $n = $i + 1;
        $cls = 'book-step';
        if ($n <  $current) $cls .= ' is-done';
        if ($n === $current) $cls .= ' is-current';
        echo '<li class="' . $cls . '"><span class="book-step-num">' . $n . '</span>'
           . '<span class="book-step-label">' . e($label) . '</span></li>';
    }
    echo '</ol>';
}

function bookpub_render_step1(bool $embed): void {
    $services = BookingAPI::getActiveServices();
    bookpub_layout_start('Book an appointment', $embed);
    bookpub_stepper(1, $embed);
    echo '<h1>Pick a service</h1>';
    if (!$services) {
        echo '<div class="alert alert-info">No services are currently available.</div>';
    } else {
        echo '<div class="book-grid">';
        foreach ($services as $s) {
            $price = ((int)$s['price_cents']) > 0
                ? e($s['currency']) . ' ' . number_format($s['price_cents']/100, 2)
                : 'Free';
            echo '<a class="book-card-link" href="?service=' . (int)$s['id']
               . (!empty($_GET['embed']) ? '&embed=1' : '') . '">';
            echo '<div class="book-card-title">' . e($s['name']) . '</div>';
            echo '<div class="book-card-meta">' . (int)$s['duration_min'] . ' min · ' . $price . '</div>';
            if (!empty($s['description'])) {
                echo '<div class="book-card-desc">' . e(mb_strimwidth($s['description'], 0, 140, '…')) . '</div>';
            }
            echo '</a>';
        }
        echo '</div>';
    }
    bookpub_layout_end($embed);
}

function bookpub_render_step2(array $service, bool $embed): void {
    $providers = BookingAPI::getProvidersForService((int)$service['id']);
    bookpub_layout_start($service['name'], $embed);
    bookpub_stepper(2, $embed);
    echo '<a class="book-back" href="?' . ($embed ? 'embed=1' : '') . '">&larr; back</a>';
    echo '<h1>Choose a provider</h1><p class="book-sub">For <strong>' . e($service['name']) . '</strong>.</p>';
    if (!$providers) {
        echo '<div class="alert alert-warning">No providers are available for this service yet.</div>';
    } else {
        echo '<div class="book-grid">';
        foreach ($providers as $p) {
            echo '<a class="book-card-link" href="?service=' . (int)$service['id']
               . '&provider=' . (int)$p['id']
               . ($embed ? '&embed=1' : '') . '">';
            echo '<div class="book-card-title">' . e($p['name']) . '</div>';
            if (!empty($p['bio'])) {
                echo '<div class="book-card-desc">' . e(mb_strimwidth($p['bio'], 0, 140, '…')) . '</div>';
            }
            echo '</a>';
        }
        echo '</div>';
    }
    bookpub_layout_end($embed);
}

function bookpub_render_step3(array $service, array $provider, string $date, bool $embed): void {
    if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
        $date = date('Y-m-d');
    }
    $slots = BookingAPI::computeAvailableSlots((int)$service['id'], (int)$provider['id'], $date);

    bookpub_layout_start($service['name'] . ' — ' . $provider['name'], $embed);
    bookpub_stepper(3, $embed);
    echo '<a class="book-back" href="?service=' . (int)$service['id']
       . ($embed ? '&embed=1' : '') . '">&larr; back</a>';
    echo '<h1>Pick a time</h1>';
    echo '<p class="book-sub"><strong>' . e($service['name']) . '</strong> with '
       . e($provider['name']) . ' · ' . (int)$service['duration_min'] . ' min</p>';

    ?>
    <form method="get" class="book-date-form">
        <input type="hidden" name="service"  value="<?= (int)$service['id'] ?>">
        <input type="hidden" name="provider" value="<?= (int)$provider['id'] ?>">
        <?php if ($embed): ?><input type="hidden" name="embed" value="1"><?php endif; ?>
        <label class="field-label" for="date">Date</label>
        <input type="date" id="date" name="date" value="<?= e($date) ?>"
               min="<?= e(date('Y-m-d')) ?>"
               onchange="this.form.submit()">
    </form>
    <?php

    if (empty($slots)) {
        echo '<div class="alert alert-info">No slots available on this day. Pick another date.</div>';
    } else {
        echo '<div class="book-slots">';
        foreach ($slots as $time) {
            echo '<a class="book-slot" href="?service=' . (int)$service['id']
               . '&provider=' . (int)$provider['id']
               . '&date=' . urlencode($date)
               . '&slot=' . urlencode($time)
               . ($embed ? '&embed=1' : '') . '">' . e($time) . '</a>';
        }
        echo '</div>';
    }
    bookpub_layout_end($embed);
}

function bookpub_render_step4(array $service, array $provider, string $date, string $slot, array $errors = [], string $generalError = '', bool $embed = false): void {
    $cust = Auth::customer();

    bookpub_layout_start('Confirm — ' . $service['name'], $embed);
    bookpub_stepper(4, $embed);
    echo '<a class="book-back" href="?service=' . (int)$service['id']
       . '&provider=' . (int)$provider['id']
       . '&date=' . urlencode($date)
       . ($embed ? '&embed=1' : '') . '">&larr; back</a>';
    echo '<h1>Confirm your booking</h1>';
    echo '<div class="book-summary">';
    echo   '<div><span class="kv-label">Service</span><span class="kv-value">' . e($service['name']) . '</span></div>';
    echo   '<div><span class="kv-label">With</span><span class="kv-value">' . e($provider['name']) . '</span></div>';
    echo   '<div><span class="kv-label">When</span><span class="kv-value">'
         . e(date('l, j F Y', strtotime($date))) . ' · ' . e($slot) . '</span></div>';
    if (((int)$service['price_cents']) > 0) {
        echo '<div><span class="kv-label">Price</span><span class="kv-value">'
           . e($service['currency']) . ' ' . number_format($service['price_cents']/100, 2)
           . ' <span class="text-muted">(paid in person)</span></span></div>';
    }
    echo '</div>';

    if ($generalError !== '') {
        echo '<div class="alert alert-error">' . e($generalError) . '</div>';
    }
    ?>
    <form method="post">
        <?= csrf_field() ?>
        <input type="hidden" name="service"  value="<?= (int)$service['id'] ?>">
        <input type="hidden" name="provider" value="<?= (int)$provider['id'] ?>">
        <input type="hidden" name="date"     value="<?= e($date) ?>">
        <input type="hidden" name="slot"     value="<?= e($slot) ?>">
        <?php if ($embed): ?><input type="hidden" name="embed" value="1"><?php endif; ?>

        <div class="field-row field-row-2">
            <div class="field">
                <label class="field-label" for="customer_name">Your name <span class="field-required">*</span></label>
                <input type="text" id="customer_name" name="customer_name" required maxlength="160"
                       value="<?= e($cust['name'] ?? '') ?>">
            </div>
            <div class="field">
                <label class="field-label" for="customer_email">Email <span class="field-required">*</span></label>
                <input type="email" id="customer_email" name="customer_email" required maxlength="200"
                       value="<?= e($cust['email'] ?? '') ?>">
            </div>
        </div>
        <div class="field">
            <label class="field-label" for="customer_phone">Phone <span class="text-muted text-xs">(optional)</span></label>
            <input type="tel" id="customer_phone" name="customer_phone" maxlength="40">
        </div>
        <div class="field">
            <label class="field-label" for="notes">Notes <span class="text-muted text-xs">(optional)</span></label>
            <textarea id="notes" name="notes" maxlength="2000"></textarea>
        </div>

        <button type="submit" class="btn btn-primary btn-lg btn-block">Confirm booking</button>
    </form>
    <?php
    bookpub_layout_end($embed);
}

function bookpub_render_step4_with_error(array $args, string $error, bool $embed): void {
    $service  = BookingAPI::getService((int)$args['service_id']);
    $provider = Database::row("SELECT * FROM booking_providers WHERE id = ?", [(int)$args['provider_id']]);
    if (!$service || !$provider) {
        bookpub_render_error($error, $embed);
        return;
    }
    [$date, $slot] = explode(' ', $args['starts_at']) + ['', ''];
    $slot = substr($slot, 0, 5);
    bookpub_render_step4($service, $provider, $date, $slot, [], $error, $embed);
}

function bookpub_render_success(string $ref, array $args, bool $embed): void {
    bookpub_layout_start('Booking confirmed', $embed);
    ?>
    <div class="book-success">
        <div class="book-success-icon" aria-hidden="true">
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                 stroke-linecap="round" stroke-linejoin="round">
                <polyline points="20 6 9 17 4 12"/>
            </svg>
        </div>
        <h1>You're booked</h1>
        <p>We've sent a confirmation to <strong><?= e($args['customer_email']) ?></strong>.</p>
        <p class="text-sm text-muted">Reference: <code><?= e($ref) ?></code></p>
        <p class="mt-3"><a href="?<?= $embed ? 'embed=1' : '' ?>" class="btn btn-ghost">Book something else</a></p>
    </div>
    <?php
    bookpub_layout_end($embed);
}

function bookpub_render_error(string $msg, bool $embed): void {
    bookpub_layout_start('Booking', $embed);
    echo '<h1>Something went wrong</h1>';
    echo '<div class="alert alert-error">' . e($msg) . '</div>';
    echo '<a href="?' . ($embed ? 'embed=1' : '') . '" class="btn">Start over</a>';
    bookpub_layout_end($embed);
}
