<?php $this->extend('layout/app'); ?>
<?php $this->section('content'); ?>

<?php
$_abv = [
    'status'         => (string)($booking['status'] ?? 'booked'),
    'id'             => (int)($booking['id'] ?? 0),
    'starts_at'      => (string)($booking['starts_at'] ?? ''),
    'ends_at'        => (string)($booking['ends_at']   ?? ''),
    'lead_name'      => (string)($booking['lead_name'] ?? ($booking['lead_display'] ?? '')),
    'lead_display'   => (string)($booking['lead_display'] ?? ($booking['lead_name'] ?? '')),
    'lead_email'     => (string)($booking['lead_email'] ?? ''),
    'lead_phone'     => (string)($booking['lead_phone'] ?? ''),
    'agent_name'     => (string)($booking['agent_name'] ?? ($booking['agent_display'] ?? ($booking['assigned_name'] ?? ($booking['assigned_agent_name'] ?? '')))),
    'agent_display'  => (string)($booking['agent_display'] ?? ($booking['agent_name'] ?? '')),
    'agent_email'    => (string)($booking['agent_email'] ?? ($booking['assigned_email'] ?? ($booking['assigned_agent_email'] ?? ''))),
    'timezone'       => (string)($booking['timezone'] ?? ($booking['tz'] ?? '')),
    'tz'             => (string)($booking['tz'] ?? ($booking['timezone'] ?? '')),
    'schedule_title' => (string)($booking['schedule_title'] ?? ($booking['schedule_name'] ?? '')),
    'schedule_name'  => (string)($booking['schedule_name'] ?? ($booking['schedule_title'] ?? '')),
    'schedule_id'    => (int)($booking['schedule_id'] ?? 0),
    'created_at'     => (string)($booking['created_at'] ?? ''),
    'notes'          => (string)($booking['notes'] ?? ''),
];
$st = $_abv['status'];
$statusBadgeClass = match($st) {
    'booked'    => 'bg-emerald-100 text-emerald-800',
    'cancelled' => 'bg-rose-100 text-rose-800',
    'pending'   => 'bg-amber-100 text-amber-800',
    'completed' => 'bg-sky-100 text-sky-800',
    default     => 'bg-slate-100 text-slate-700',
};
$statusGradient = match($st) {
    'cancelled' => 'from-rose-500 via-pink-500 to-orange-500',
    'completed' => 'from-sky-500 via-indigo-500 to-violet-500',
    'pending'   => 'from-amber-500 via-orange-500 to-rose-500',
    default     => 'from-emerald-500 via-teal-500 to-sky-500',
};
$startTs = !empty($_abv['starts_at']) ? strtotime($_abv['starts_at']) : null;
$endTs   = !empty($_abv['ends_at'])   ? strtotime($_abv['ends_at'])   : null;
$durMin  = ($startTs && $endTs) ? (int)round(($endTs - $startTs) / 60) : 0;
?>

<div class="space-y-6">
    <div class="flex items-center gap-2">
        <a href="<?= site_url('/admin/bookings') ?>" class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg bg-slate-100 hover:bg-slate-200 text-slate-700 text-[12px] font-semibold transition">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" /></svg>
            Back to Bookings
        </a>
    </div>

    <div class="rounded-3xl bg-gradient-to-br <?= $statusGradient ?> p-[1.5px] shadow-xl shadow-slate-900/5">
        <div class="rounded-[22px] bg-gradient-to-br from-white/95 to-white/85 backdrop-blur p-6 md:p-8">
            <div class="flex flex-wrap items-start justify-between gap-4">
                <div class="flex-1 min-w-0">
                    <div class="flex flex-wrap items-center gap-2.5 mb-3">
                        <span class="inline-flex items-center px-3 py-1 rounded-full <?= $statusBadgeClass ?> text-[11px] font-black uppercase tracking-[0.08em]">
                            <?= esc($st) ?>
                        </span>
                        <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-white/80 border border-slate-200/80 text-[11px] font-semibold text-slate-600">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14" /></svg>
                            #<?= (int)$_abv['id'] ?>
                        </span>
                    </div>
                    <h1 class="text-2xl md:text-3xl font-extrabold text-slate-900 tracking-tight mb-2">
                        Appointment Details
                    </h1>
                    <?php if ($startTs): ?>
                        <p class="text-[15px] text-slate-600 font-medium">
                            <span class="font-bold text-slate-800"><?= date('l, F jS, Y', $startTs) ?></span>
                            <span class="mx-2 text-slate-400">·</span>
                            <span class="font-mono font-semibold"><?= date('g:i A', $startTs) ?> – <?= $endTs ? date('g:i A', $endTs) : '—' ?></span>
                        </p>
                    <?php endif; ?>
                </div>
                <div class="flex items-center gap-2">
                    <?php if ($st !== 'cancelled'): ?>
                        <button type="button" id="btnCancelBooking" class="inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-gradient-to-r from-rose-600 to-pink-600 text-white text-sm font-bold shadow-lg shadow-rose-500/25 hover:shadow-xl hover:-translate-y-0.5 active:translate-y-0 transition-all">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" /></svg>
                            Cancel Booking
                        </button>
                    <?php else: ?>
                        <span class="inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-slate-100 text-slate-500 text-sm font-bold">
                            <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" /></svg>
                            Already Cancelled
                        </span>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>

    <div class="grid grid-cols-1 sm:grid-cols-2 xl:grid-cols-3 gap-3">
        <div class="glass rounded-2xl border border-slate-200/60 p-5 shadow-sm">
            <div class="flex items-center gap-2.5 mb-3">
                <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-sky-500 to-cyan-500 text-white flex items-center justify-center shadow-sm">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" /></svg>
                </div>
                <span class="text-[11px] font-bold text-slate-500 uppercase tracking-wider">Lead</span>
            </div>
            <p class="text-sm font-extrabold text-slate-800 mb-0.5"><?= !empty($_abv['lead_name']) ? esc($_abv['lead_name']) : 'Unknown' ?></p>
            <?php if (!empty($_abv['lead_email'])): ?>
                <p class="text-[12px] text-slate-500"><?= esc($_abv['lead_email']) ?></p>
            <?php endif; ?>
            <?php if (!empty($_abv['lead_phone'])): ?>
                <p class="text-[12px] text-slate-500"><?= esc($_abv['lead_phone']) ?></p>
            <?php endif; ?>
        </div>

        <div class="glass rounded-2xl border border-slate-200/60 p-5 shadow-sm">
            <div class="flex items-center gap-2.5 mb-3">
                <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 text-white flex items-center justify-center shadow-sm">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" /></svg>
                </div>
                <span class="text-[11px] font-bold text-slate-500 uppercase tracking-wider">Agent</span>
            </div>
            <p class="text-sm font-extrabold text-slate-800 mb-0.5"><?= !empty($_abv['agent_name']) ? esc($_abv['agent_name']) : 'Unassigned' ?></p>
            <?php if (!empty($_abv['agent_email'])): ?>
                <p class="text-[12px] text-slate-500"><?= esc($_abv['agent_email']) ?></p>
            <?php endif; ?>
        </div>

        <div class="glass rounded-2xl border border-slate-200/60 p-5 shadow-sm">
            <div class="flex items-center gap-2.5 mb-3">
                <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-emerald-500 to-teal-500 text-white flex items-center justify-center shadow-sm">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" /></svg>
                </div>
                <span class="text-[11px] font-bold text-slate-500 uppercase tracking-wider">Date / Time</span>
            </div>
            <?php if ($startTs): ?>
                <p class="text-sm font-extrabold text-slate-800 mb-0.5"><?= date('D, M j, Y', $startTs) ?></p>
                <p class="text-[12px] font-mono text-slate-600 font-semibold"><?= date('g:i A', $startTs) ?> – <?= $endTs ? date('g:i A', $endTs) : '—' ?></p>
                <?php if (!empty($_abv['timezone'])): ?>
                    <p class="text-[10px] text-slate-400 mt-1"><?= esc($_abv['timezone']) ?></p>
                <?php endif; ?>
            <?php else: ?>
                <p class="text-sm text-slate-500 italic">Not set</p>
            <?php endif; ?>
        </div>

        <div class="glass rounded-2xl border border-slate-200/60 p-5 shadow-sm">
            <div class="flex items-center gap-2.5 mb-3">
                <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-amber-500 to-orange-500 text-white flex items-center justify-center shadow-sm">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                </div>
                <span class="text-[11px] font-bold text-slate-500 uppercase tracking-wider">Duration</span>
            </div>
            <p class="text-2xl font-black text-slate-800 leading-none"><?= $durMin ?><span class="text-sm font-bold text-slate-500 ml-1">min</span></p>
            <p class="text-[12px] text-slate-500 mt-1"><?= $durMin >= 60 ? floor($durMin / 60) . 'h ' . ($durMin % 60) . 'm' : $durMin . ' minutes' ?></p>
        </div>

        <div class="glass rounded-2xl border border-slate-200/60 p-5 shadow-sm">
            <div class="flex items-center gap-2.5 mb-3">
                <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-indigo-500 to-blue-500 text-white flex items-center justify-center shadow-sm">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M19 11H5m14 0a2 2 0 012 2v6a2 2 0 01-2 2H5a2 2 0 01-2-2v-6a2 2 0 012-2m14 0V9a2 2 0 00-2-2M5 11V9a2 2 0 012-2m0 0V5a2 2 0 012-2h6a2 2 0 012 2v2M7 7h10" /></svg>
                </div>
                <span class="text-[11px] font-bold text-slate-500 uppercase tracking-wider">Schedule</span>
            </div>
            <p class="text-sm font-extrabold text-slate-800 mb-0.5 truncate" title="<?= esc($_abv['schedule_title']) ?>"><?= !empty($_abv['schedule_title']) ? esc($_abv['schedule_title']) : '—' ?></p>
            <p class="text-[12px] text-slate-500">Schedule ID: <?= (int)$_abv['schedule_id'] ?></p>
        </div>

        <div class="glass rounded-2xl border border-slate-200/60 p-5 shadow-sm">
            <div class="flex items-center gap-2.5 mb-3">
                <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-pink-500 to-rose-500 text-white flex items-center justify-center shadow-sm">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                </div>
                <span class="text-[11px] font-bold text-slate-500 uppercase tracking-wider">Status</span>
            </div>
            <div class="flex items-center gap-2">
                <span class="inline-flex items-center px-3 py-1 rounded-full <?= $statusBadgeClass ?> text-[12px] font-black uppercase"><?= esc($st) ?></span>
            </div>
            <?php if (!empty($_abv['created_at'])): ?>
                <p class="text-[11px] text-slate-400 mt-2">Created: <?= date('M j, Y g:ia', strtotime($_abv['created_at'])) ?></p>
            <?php endif; ?>
        </div>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 p-6">
        <div class="flex items-start gap-3 mb-4">
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-slate-700 to-slate-900 text-white flex items-center justify-center shadow-md flex-shrink-0">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8"><path stroke-linecap="round" stroke-linejoin="round" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" /></svg>
            </div>
            <div class="flex-1">
                <h3 class="text-base font-semibold text-slate-800">Notes</h3>
                <p class="text-[11px] text-slate-500 mt-0.5">Additional booking notes, meeting location, or special instructions.</p>
            </div>
        </div>
        <div class="rounded-2xl border border-slate-200 bg-gradient-to-br from-white to-slate-50/60 p-5 min-h-[120px]">
            <?php if (!empty($_abv['notes'])): ?>
                <p class="text-sm text-slate-700 whitespace-pre-wrap leading-relaxed"><?= esc($_abv['notes']) ?></p>
            <?php else: ?>
                <p class="text-sm text-slate-400 italic">No notes for this booking.</p>
            <?php endif; ?>
        </div>
    </div>

    <div id="cancelResult" class="hidden"></div>
</div>

<script>
(function () {
    const btn = document.getElementById('btnCancelBooking');
    const result = document.getElementById('cancelResult');
    const bookingId = <?= (int)($booking['id'] ?? 0) ?>;

    function showToast(ok, message) {
        result.classList.remove('hidden');
        result.className = 'glass rounded-2xl p-5 border ' +
            (ok ? 'bg-emerald-50/60 border-emerald-200/60' : 'bg-rose-50/60 border-rose-200/60');
        result.innerHTML =
            '<div class="flex items-center gap-3">' +
                (ok
                    ? '<div class="w-10 h-10 rounded-xl bg-emerald-500 text-white flex items-center justify-center flex-shrink-0"><svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M5 13l4 4L19 7" /></svg></div>'
                    : '<div class="w-10 h-10 rounded-xl bg-rose-500 text-white flex items-center justify-center flex-shrink-0"><svg xmlns="http://www.w3.org/2000/svg" class="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg></div>') +
                '<div class="flex-1 min-w-0">' +
                    '<p class="text-sm font-bold ' + (ok ? 'text-emerald-800' : 'text-rose-800') + '">' + (ok ? 'Booking Cancelled' : 'Cancellation Failed') + '</p>' +
                    '<p class="text-[12px] ' + (ok ? 'text-emerald-700' : 'text-rose-700') + ' mt-0.5">' + message + '</p>' +
                '</div>' +
            '</div>';
    }

    btn?.addEventListener('click', async () => {
        if (!confirm('Are you sure you want to cancel this booking? Notifications will be sent to all configured recipients.')) {
            return;
        }
        const body = new FormData();
        const csrfName = '<?= csrf_token() ?>';
        const csrfHash = '<?= csrf_hash() ?>';
        body.append(csrfName, csrfHash);
        btn.disabled = true;
        btn.classList.add('opacity-60', 'cursor-not-allowed');
        const origHTML = btn.innerHTML;
        btn.innerHTML = '<svg class="animate-spin w-4.5 h-4.5 mr-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg>Cancelling...';
        try {
            const resp = await fetch('<?= site_url('/admin/bookings/cancel/') ?>' + bookingId, {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                body: body,
                credentials: 'same-origin',
            });
            let data;
            try { data = await resp.json(); } catch (e) { data = { ok: false, message: 'Bad response from server.' }; }
            showToast(!!data.ok, data.message || (data.ok ? 'Cancellation successful.' : 'Unknown error.'));
            if (data.ok) {
                btn.remove();
                setTimeout(() => location.reload(), 1500);
            } else {
                btn.disabled = false;
                btn.classList.remove('opacity-60', 'cursor-not-allowed');
                btn.innerHTML = origHTML;
            }
        } catch (e) {
            showToast(false, 'Network error: ' + e.message);
            btn.disabled = false;
            btn.classList.remove('opacity-60', 'cursor-not-allowed');
            btn.innerHTML = origHTML;
        }
    });
})();
</script>

<?php $this->endSection(); ?>
