<?= $this->extend('layout/app') ?>

<?= $this->section('title') ?>Booking #<?= (int)($booking['id'] ?? 0) ?><?= $this->endSection() ?>
<?= $this->section('pageTitle') ?>Booking Details<?= $this->endSection() ?>

<?= $this->section('content') ?>
<?php

$bookingMeta = function(array $b): array {
    $startsAt    = $b['starts_at']    ?? null;
    $endsAt      = $b['ends_at']      ?? null;
    $bookingDate = $b['booking_date'] ?? null;
    $startTime   = $b['start_time']  ?? null;

    $rangeSt = null;
    if ($startsAt) {
        $rangeSt = $startsAt;
    } elseif ($bookingDate && $startTime) {
        $rangeSt = $bookingDate . ' ' . $startTime;
    } elseif ($bookingDate) {
        $rangeSt = $bookingDate;
    } elseif ($startTime) {
        $rangeSt = $startTime;
    }
    $rangeEn = $endsAt ?: null;

    $stTs = $rangeSt ? @strtotime($rangeSt) : false;
    $enTs = $rangeEn ? @strtotime($rangeEn) : false;

    $dateReadable = '—';
    $dayOfWeek    = '';
    $dateShort    = '—';
    $startTimeFmt = '—';
    $endTimeFmt   = '—';
    $durMin       = 0;

    if ($stTs) {
        $dateReadable = date('M j, Y', $stTs);
        $dayOfWeek    = date('l',    $stTs);
        $dateShort    = date('M j',  $stTs);
        $startTimeFmt = date('g:i A', $stTs);
    }
    if ($enTs) {
        $endTimeFmt = date('g:i A', $enTs);
    }
    if ($stTs && $enTs) {
        $durMin = (int)round(($enTs - $stTs) / 60);
    }
    if ($durMin <= 0 && !empty($b['duration_minutes'])) {
        $durMin = (int)$b['duration_minutes'];
    }

    return [
        'dateReadable' => $dateReadable,
        'dayOfWeek'    => $dayOfWeek,
        'dateShort'    => $dateShort,
        'startTime'    => $startTimeFmt,
        'endTime'      => $endTimeFmt,
        'durationMin'  => $durMin,
    ];
};

$bid = (int)($booking['id'] ?? 0);
$status = strtolower((string)($booking['status'] ?? 'booked'));

$_bv = [
    'lead_id'             => (int)($booking['lead_id'] ?? 0),
    'booking_date'        => (string)($booking['booking_date'] ?? ($booking['starts_at'] ?? '')),
    'start_time'          => (string)($booking['start_time']   ?? ($booking['starts_at'] ?? '')),
    'starts_at'           => (string)($booking['starts_at']    ?? ''),
    'ends_at'             => (string)($booking['ends_at']      ?? ''),
    'schedule_name'       => (string)($booking['schedule_name'] ?? ($booking['schedule_title'] ?? '')),
    'schedule_title'      => (string)($booking['schedule_title'] ?? ''),
    'booked_by_name'      => (string)($booking['booked_by_name'] ?? ''),
    'lead_name'           => (string)($booking['lead_name']    ?? ''),
    'lead_company_name'   => (string)($booking['lead_company_name'] ?? ''),
    'guest_email'         => (string)($booking['guest_email']  ?? ''),
    'lead_email'          => (string)($booking['lead_email']   ?? ''),
    'guest_phone'         => (string)($booking['guest_phone']  ?? ''),
    'lead_phone'          => (string)($booking['lead_phone']   ?? ''),
    'guest_name'          => (string)($booking['guest_name']   ?? ''),
    'assigned_name'       => (string)($booking['assigned_name']       ?? ($booking['assigned_agent_name'] ?? ($booking['agent_name'] ?? ''))),
    'assigned_agent_name' => (string)($booking['assigned_agent_name'] ?? ($booking['assigned_name']       ?? ($booking['agent_name'] ?? ''))),
    'agent_name'          => (string)($booking['agent_name']          ?? ($booking['assigned_name']       ?? '')),
    'assigned_email'      => (string)($booking['assigned_email']      ?? ($booking['assigned_agent_email'] ?? ($booking['agent_email'] ?? ''))),
    'assigned_agent_email'=> (string)($booking['assigned_agent_email']?? ($booking['assigned_email']       ?? ($booking['agent_email'] ?? ''))),
    'agent_email'         => (string)($booking['agent_email']         ?? ($booking['assigned_email']       ?? '')),
    'notes'               => (string)($booking['notes'] ?? ''),
    'created_at'          => (string)($booking['created_at'] ?? ''),
    'updated_at'          => (string)($booking['updated_at'] ?? ''),
    'timezone'            => (string)($booking['timezone'] ?? ($booking['tz'] ?? '')),
    'tz'                  => (string)($booking['tz'] ?? ($booking['timezone'] ?? '')),
    'duration_minutes'    => (int)($booking['duration_minutes'] ?? 0),
];
$_meta = $bookingMeta($booking);
$durationMin = $_meta['durationMin'];

$headerConfig = match ($status) {
    'booked'      => [
        'gradient' => 'from-emerald-500 via-teal-500 to-cyan-600',
        'icon'     => 'M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z',
        'label'    => 'Scheduled / Booked',
        'sub'      => 'This assessment is confirmed and awaiting the scheduled date.',
    ],
    'completed'   => [
        'gradient' => 'from-blue-500 via-indigo-500 to-violet-600',
        'icon'     => 'M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z',
        'label'    => 'Completed',
        'sub'      => 'This assessment has been completed.',
    ],
    'cancelled'   => [
        'gradient' => 'from-rose-500 via-red-500 to-pink-600',
        'icon'     => 'M6 18L18 6M6 6l12 12',
        'label'    => 'Cancelled',
        'sub'      => 'This assessment has been cancelled.',
    ],
    'rescheduled' => [
        'gradient' => 'from-slate-500 via-slate-600 to-slate-700',
        'icon'     => 'M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15',
        'label'    => 'Rescheduled',
        'sub'      => 'This assessment has been rescheduled from its original slot.',
    ],
    default => [
        'gradient' => 'from-slate-500 via-slate-600 to-slate-700',
        'icon'     => 'M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z',
        'label'    => ucfirst($status),
        'sub'      => 'Booking status: ' . ucfirst($status),
    ],
};

$statusBadgeMap = [
    'booked'      => 'bg-emerald-100 text-emerald-700 border-emerald-200',
    'completed'   => 'bg-blue-100 text-blue-700 border-blue-200',
    'cancelled'   => 'bg-rose-100 text-rose-700 border-rose-200',
    'rescheduled' => 'bg-amber-100 text-amber-700 border-amber-200',
];
$statusClass = $statusBadgeMap[$status] ?? 'bg-slate-100 text-slate-700 border-slate-200';
$canCancel = in_array($status, ['booked', 'rescheduled'], true);
?>

<div class="mb-5 flex items-center gap-3 flex-wrap">
    <a href="<?= esc(site_url('/agent/my-bookings')) ?>" class="inline-flex items-center gap-1.5 px-3 py-2 rounded-xl bg-white border border-slate-200 text-sm text-slate-600 hover:bg-slate-50 hover:border-slate-300 transition-all shadow-sm">
        <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
            <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
        </svg>
        Back to My Bookings
    </a>
    <?php if (!empty($_bv['lead_id'])): ?>
        <a href="<?= esc(site_url('/agent/leads/view/' . (int)$_bv['lead_id'])) ?>" class="inline-flex items-center gap-1.5 px-3 py-2 rounded-xl bg-gradient-to-r from-indigo-50 to-blue-50 border border-indigo-200/60 text-sm font-semibold text-indigo-700 hover:from-indigo-100 hover:to-blue-100 transition-all">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                <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 0z" />
            </svg>
            View Lead
        </a>
    <?php endif; ?>
    <div class="ml-auto">
        <span class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-bold border <?= $statusClass ?>">
            <?= esc(ucfirst($status)) ?>
        </span>
    </div>
</div>

<div class="space-y-6">
    <div class="glass rounded-2xl border border-white/60 shadow-sm overflow-hidden">
        <div class="bg-gradient-to-r <?= $headerConfig['gradient'] ?> px-8 py-7 text-white">
            <div class="flex items-start gap-5 flex-wrap">
                <div class="w-16 h-16 rounded-2xl bg-white/20 backdrop-blur-sm flex items-center justify-center border border-white/25 flex-shrink-0">
                    <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="<?= $headerConfig['icon'] ?>" />
                    </svg>
                </div>
                <div class="flex-1 min-w-0">
                    <p class="text-xs font-semibold text-white/70 uppercase tracking-widest mb-1">Booking #<?= $bid ?></p>
                    <h1 class="text-2xl sm:text-3xl font-bold mb-1"><?= esc($headerConfig['label']) ?></h1>
                    <p class="text-sm text-white/80"><?= esc($headerConfig['sub']) ?></p>
                </div>
            </div>
        </div>

        <div class="p-6 sm:p-8">
            <div class="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 mb-8">
                <div class="rounded-xl bg-gradient-to-br from-indigo-50 to-blue-50 border border-indigo-100 p-4">
                    <p class="text-[10px] font-bold text-indigo-500 uppercase tracking-wider mb-1">Date</p>
                    <p class="text-sm font-extrabold text-slate-800"><?= esc($_meta['dateReadable']) ?></p>
                    <p class="text-[11px] text-slate-400 font-medium mt-0.5"><?= esc($_meta['dayOfWeek']) ?></p>
                </div>
                <div class="rounded-xl bg-gradient-to-br from-emerald-50 to-teal-50 border border-emerald-100 p-4">
                    <p class="text-[10px] font-bold text-emerald-600 uppercase tracking-wider mb-1">Start</p>
                    <p class="text-sm font-extrabold text-slate-800 font-mono"><?= esc($_meta['startTime']) ?></p>
                </div>
                <div class="rounded-xl bg-gradient-to-br from-rose-50 to-pink-50 border border-rose-100 p-4">
                    <p class="text-[10px] font-bold text-rose-600 uppercase tracking-wider mb-1">End</p>
                    <p class="text-sm font-extrabold text-slate-800 font-mono"><?= esc($_meta['endTime']) ?></p>
                </div>
                <div class="rounded-xl bg-gradient-to-br from-amber-50 to-orange-50 border border-amber-100 p-4">
                    <p class="text-[10px] font-bold text-amber-600 uppercase tracking-wider mb-1">Duration</p>
                    <p class="text-sm font-extrabold text-slate-800"><?= $durationMin > 0 ? $durationMin . ' min' : '—' ?></p>
                </div>
                <div class="rounded-xl bg-gradient-to-br from-violet-50 to-purple-50 border border-violet-100 p-4">
                    <p class="text-[10px] font-bold text-violet-600 uppercase tracking-wider mb-1">Schedule</p>
                    <p class="text-sm font-extrabold text-slate-800 truncate" title="<?= esc($_bv['schedule_name']) ?>"><?= !empty($_bv['schedule_name']) ? esc($_bv['schedule_name']) : '—' ?></p>
                </div>
                <div class="rounded-xl bg-gradient-to-br from-slate-50 to-slate-100 border border-slate-200 p-4">
                    <p class="text-[10px] font-bold text-slate-500 uppercase tracking-wider mb-1">Booked By</p>
                    <p class="text-sm font-extrabold text-slate-800 truncate" title="<?= esc($_bv['booked_by_name']) ?>"><?= !empty($_bv['booked_by_name']) ? esc($_bv['booked_by_name']) : '—' ?></p>
                </div>
            </div>

            <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                <div class="rounded-2xl border border-slate-200/60 bg-white/50 overflow-hidden">
                    <div class="px-5 py-4 border-b border-slate-200/60 bg-slate-50/50">
                        <div class="flex items-center gap-3">
                            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-indigo-500 to-blue-600 flex items-center justify-center flex-shrink-0">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-white" 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 0z" />
                                </svg>
                            </div>
                            <div>
                                <h3 class="font-bold text-slate-800">Lead Information</h3>
                                <p class="text-xs text-slate-500">Client / prospect details</p>
                            </div>
                        </div>
                    </div>
                    <div class="p-5 space-y-4">
                        <div>
                            <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Lead Name</p>
                            <?php if (!empty($_bv['lead_id'])): ?>
                                <a href="<?= esc(site_url('/agent/leads/view/' . (int)$_bv['lead_id'])) ?>" class="text-base font-bold text-indigo-700 hover:text-indigo-800">
                                    <?= !empty($_bv['lead_name']) ? esc($_bv['lead_name']) : '—' ?>
                                </a>
                            <?php else: ?>
                                <p class="text-base font-bold text-slate-700"><?= !empty($_bv['lead_name']) ? esc($_bv['lead_name']) : '—' ?></p>
                            <?php endif; ?>
                        </div>
                        <?php if (!empty($_bv['lead_company_name'])): ?>
                            <div>
                                <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Company</p>
                                <p class="text-sm font-medium text-slate-700"><?= esc($_bv['lead_company_name']) ?></p>
                            </div>
                        <?php endif; ?>
                        <div class="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            <?php $contactEmail = $_bv['guest_email'] ?: $_bv['lead_email']; ?>
                            <?php if (!empty($contactEmail)): ?>
                                <div>
                                    <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Email</p>
                                    <a href="mailto:<?= esc($contactEmail) ?>" class="text-sm font-medium text-blue-600 hover:text-blue-700 break-all"><?= esc($contactEmail) ?></a>
                                </div>
                            <?php endif; ?>
                            <?php $contactPhone = $_bv['guest_phone'] ?: $_bv['lead_phone']; ?>
                            <?php if (!empty($contactPhone)): ?>
                                <div>
                                    <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Phone</p>
                                    <a href="tel:<?= esc($contactPhone) ?>" class="text-sm font-medium text-emerald-600 hover:text-emerald-700 font-mono"><?= esc($contactPhone) ?></a>
                                </div>
                            <?php endif; ?>
                        </div>
                        <?php $guestName = $_bv['guest_name']; ?>
                        <?php if (!empty($guestName) && $guestName !== $_bv['lead_name']): ?>
                            <div class="pt-2 border-t border-slate-100">
                                <p class="text-[11px] font-semibold text-slate-400 uppercase mb-0.5">Guest Attendee</p>
                                <p class="text-sm font-medium text-slate-700"><?= esc($guestName) ?></p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>

                <div class="rounded-2xl border border-slate-200/60 bg-white/50 overflow-hidden">
                    <div class="px-5 py-4 border-b border-slate-200/60 bg-slate-50/50">
                        <div class="flex items-center gap-3">
                            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-emerald-400 to-cyan-500 flex items-center justify-center flex-shrink-0">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-white" 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>
                            <div>
                                <h3 class="font-bold text-slate-800">Assigned Agent</h3>
                                <p class="text-xs text-slate-500">Person responsible for this meeting</p>
                            </div>
                        </div>
                    </div>
                    <div class="p-5">
                        <div class="flex items-center gap-4">
                            <div class="w-14 h-14 rounded-2xl bg-gradient-to-br from-emerald-400 to-cyan-500 flex items-center justify-center text-white text-xl font-bold flex-shrink-0 shadow-md shadow-emerald-500/20">
                                <?= strtoupper(substr(esc(!empty($_bv['assigned_name']) ? $_bv['assigned_name'] : 'A'), 0, 1)) ?>
                            </div>
                            <div class="flex-1 min-w-0">
                                <p class="text-lg font-extrabold text-slate-800"><?= !empty($_bv['assigned_name']) ? esc($_bv['assigned_name']) : '—' ?></p>
                                <?php $agentEmail = $_bv['assigned_email'] ?: $_bv['assigned_agent_email'] ?: $_bv['agent_email']; ?>
                                <?php if (!empty($agentEmail)): ?>
                                    <a href="mailto:<?= esc($agentEmail) ?>" class="text-sm text-slate-500 hover:text-blue-600 break-all">
                                        <?= esc($agentEmail) ?>
                                    </a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <?php if (!empty($_bv['notes'])): ?>
                <div class="mt-6 rounded-2xl border border-slate-200/60 bg-gradient-to-br from-amber-50/40 to-orange-50/40 overflow-hidden">
                    <div class="px-5 py-4 border-b border-amber-100/60">
                        <div class="flex items-center gap-3">
                            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-amber-400 to-orange-500 flex items-center justify-center flex-shrink-0">
                                <svg xmlns="http://www.w3.org/2000/svg" class="w-4.5 h-4.5 text-white" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                                    <path stroke-linecap="round" stroke-linejoin="round" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" />
                                </svg>
                            </div>
                            <div>
                                <h3 class="font-bold text-slate-800">Booking Notes</h3>
                                <p class="text-xs text-slate-500">Additional details or agenda</p>
                            </div>
                        </div>
                    </div>
                    <div class="p-5">
                        <div class="text-sm text-slate-700 whitespace-pre-wrap leading-relaxed"><?= esc($_bv['notes']) ?></div>
                    </div>
                </div>
            <?php endif; ?>

            <div class="mt-8 pt-6 border-t border-slate-200/60 flex flex-wrap items-center gap-3">
                <a href="<?= esc(site_url('/agent/my-bookings')) ?>" class="inline-flex items-center gap-2 px-5 py-3 rounded-xl text-sm font-semibold bg-slate-100 hover:bg-slate-200 text-slate-700 border border-slate-200 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="2">
                        <path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" />
                    </svg>
                    Back to My Bookings
                </a>
                <?php if ($canCancel): ?>
                    <button type="button" id="cancel-booking-btn" onclick="cancelBooking(<?= $bid ?>)"
                        class="inline-flex items-center gap-2 px-5 py-3 rounded-xl text-sm font-bold bg-gradient-to-r from-rose-500 to-red-600 text-white shadow-lg shadow-rose-500/25 hover:shadow-xl hover:shadow-rose-500/30 hover:-translate-y-0.5 active:translate-y-0 transition-all disabled:opacity-60 disabled:cursor-not-allowed disabled:hover:translate-y-0">
                        <span id="cancel-spin" class="hidden inline-block w-4 h-4 border-2 border-white/40 border-t-white rounded-full animate-spin"></span>
                        <svg xmlns="http://www.w3.org/2000/svg" id="cancel-icon" class="w-4.5 h-4.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                            <path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                        <span id="cancel-text">Cancel Booking</span>
                    </button>
                <?php endif; ?>
                <div class="ml-auto text-xs text-slate-400 font-medium">
                    Created: <?= !empty($_bv['created_at']) ? date('M j, Y g:i A', strtotime($_bv['created_at'])) : '—' ?>
                    <?php if (!empty($_bv['updated_at']) && $_bv['updated_at'] !== $_bv['created_at']): ?>
                        · Updated: <?= date('M j, Y g:i A', strtotime($_bv['updated_at'])) ?>
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
async function cancelBooking(bookingId) {
    if (!confirm('Are you sure you want to cancel this booking? Cancellation notifications will be sent to the assigned agent and lead.')) return;

    const btn = document.getElementById('cancel-booking-btn');
    const spin = document.getElementById('cancel-spin');
    const icon = document.getElementById('cancel-icon');
    const text = document.getElementById('cancel-text');

    btn.disabled = true;
    spin.classList.remove('hidden');
    icon.classList.add('hidden');
    text.textContent = 'Cancelling…';

    const fd = new FormData();
    fd.append('<?= csrf_token() ?>', '<?= csrf_hash() ?>');

    try {
        const resp = await fetch('<?= site_url('/agent/bookings/cancel/') ?>' + bookingId, {
            method: 'POST',
            credentials: 'same-origin',
            headers: { 'X-Requested-With': 'XMLHttpRequest' },
            body: fd
        });
        const data = await resp.json();
        if (data && data.ok) {
            text.textContent = 'Cancelled';
            setTimeout(() => window.location.reload(), 700);
        } else {
            alert(data.msg || data.error || 'Failed to cancel booking.');
            btn.disabled = false;
            spin.classList.add('hidden');
            icon.classList.remove('hidden');
            text.textContent = 'Retry Cancel';
        }
    } catch (e) {
        alert('Network error — please try again.');
        btn.disabled = false;
        spin.classList.add('hidden');
        icon.classList.remove('hidden');
        text.textContent = 'Cancel Booking';
    }
}
</script>
<?= $this->endSection() ?>
