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

<?= $this->section('title') ?>My Bookings<?= $this->endSection() ?>
<?= $this->section('pageTitle') ?>My Bookings<?= $this->endSection() ?>

<?= $this->section('content') ?>
<?php
$tabs = [
    'upcoming'  => ['label' => 'Upcoming', 'count' => $upcomingCt ?? 0],
    'past'      => ['label' => 'Past', 'count' => $pastCt ?? 0],
    'cancelled' => ['label' => 'Cancelled', 'count' => $cancelledCt ?? 0],
];
$currentFilter = $segment ?? 'upcoming';
$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',
    'no_show'     => 'bg-slate-100 text-slate-700 border-slate-200',
];

$bookingMeta = static function (array $b): array {
    $startsAt = (string)($b['starts_at'] ?? $b['booking_date'] ?? $b['start_time'] ?? '');
    $endsAt   = (string)($b['ends_at']   ?? '');
    $dateReadable = '—';
    $dayOfWeek    = '';
    $dateShort    = '';
    $startTime    = '—';
    $endTime      = '—';
    $durationMin  = 0;

    if ($startsAt !== '' && $startsAt !== '0000-00-00 00:00:00') {
        $ts = strtotime($startsAt);
        if ($ts !== false) {
            $dateReadable = date('M j, Y', $ts);
            $dayOfWeek    = date('l', $ts);
            $dateShort    = date('M j', $ts);
            $startTime    = date('g:i A', $ts);
        }
    }
    if ($endsAt !== '' && $endsAt !== '0000-00-00 00:00:00') {
        $te = strtotime($endsAt);
        if ($te !== false) {
            $endTime = date('g:i A', $te);
            if (isset($ts) && $ts !== false && $te > $ts) {
                $durationMin = (int)round(($te - $ts) / 60);
            }
        }
    }
    if ($durationMin <= 0) {
        $fallback = (int)($b['duration_minutes'] ?? 0);
        if ($fallback > 0) $durationMin = $fallback;
    }
    return [
        'dateReadable' => $dateReadable,
        'dayOfWeek'    => $dayOfWeek,
        'dateShort'    => $dateShort,
        'startTime'    => $startTime,
        'endTime'      => $endTime,
        'durationMin'  => $durationMin,
    ];
};
?>

<div class="space-y-6">
    <div class="flex flex-wrap items-center justify-between gap-3">
        <p class="text-sm text-slate-500">Manage your scheduled assessments. Filter by status using the tabs below.</p>
        <a href="<?= esc(site_url('/agent/leads')) ?>" class="inline-flex items-center gap-2 px-4 py-2.5 rounded-xl text-sm font-semibold bg-gradient-to-r from-indigo-600 to-blue-600 text-white shadow-lg shadow-indigo-500/25 hover:shadow-xl hover:shadow-indigo-500/30 hover:-translate-y-0.5 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 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z" />
            </svg>
            Browse Leads
        </a>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 overflow-hidden">
        <div class="px-2 sm:px-4 pt-4 pb-0 border-b border-slate-200/60">
            <div class="flex gap-1.5 flex-wrap">
                <?php foreach ($tabs as $key => $tab):
                    $isActive = $currentFilter === $key;
                ?>
                    <a href="<?= esc(site_url('/agent/my-bookings/' . $key)) ?>"
                       class="relative inline-flex items-center gap-2 px-5 py-3 rounded-t-xl text-sm font-bold transition-all <?= $isActive
                            ? 'text-indigo-700 bg-white border-t-2 border-x-2 border-indigo-500 -mb-px shadow-[0_-2px_8px_rgba(99,102,241,0.08)]'
                            : 'text-slate-500 hover:text-slate-700 hover:bg-slate-50/50' ?>">
                        <span><?= esc($tab['label']) ?></span>
                        <span class="inline-flex items-center justify-center min-w-[26px] h-6 px-2 rounded-full text-[11px] font-bold <?= $isActive ? 'bg-indigo-100 text-indigo-700' : 'bg-slate-100 text-slate-500' ?>">
                            <?= (int)($tab['count']) ?>
                        </span>
                    </a>
                <?php endforeach; ?>
            </div>
        </div>

        <div class="overflow-x-auto">
            <table class="w-full">
                <thead>
                    <tr class="bg-slate-50/70 border-b border-slate-200/60">
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Date</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Start / End</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Duration</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Lead</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Assigned Agent</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Schedule</th>
                        <th class="px-6 py-3.5 text-left text-xs font-semibold text-slate-500 uppercase tracking-wider">Status</th>
                        <th class="px-6 py-3.5 text-right text-xs font-semibold text-slate-500 uppercase tracking-wider">Actions</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-slate-100">
                    <?php if (empty($list)): ?>
                        <tr><td colspan="8" class="px-6 py-16 text-center">
                            <div class="flex flex-col items-center gap-3">
                                <div class="w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center">
                                    <svg xmlns="http://www.w3.org/2000/svg" class="w-8 h-8 text-slate-400" 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>
                                <p class="text-sm font-medium text-slate-600">
                                    No <?= esc($currentFilter) ?> bookings yet.
                                    <?php if ($currentFilter === 'upcoming'): ?>
                                        Open a <a href="<?= site_url('/agent/leads') ?>" class="text-indigo-600 font-semibold underline">lead</a> and click "Book Assessment" to get started.
                                    <?php endif; ?>
                                </p>
                            </div>
                        </td></tr>
                    <?php else: ?>
                        <?php foreach ($list as $b):
                            $bid = (int)($b['id'] ?? 0);
                            $status = strtolower((string)($b['status'] ?? 'booked'));
                            $statusClass = $statusBadgeMap[$status] ?? 'bg-slate-100 text-slate-700 border-slate-200';
                            $canCancel = in_array($status, ['booked', 'rescheduled'], true);
                            $_meta = $bookingMeta($b);
                            $_mb = [
                                'dateReadable'  => $_meta['dateReadable'],
                                'dayOfWeek'     => $_meta['dayOfWeek'],
                                'startTime'     => $_meta['startTime'],
                                'endTime'       => $_meta['endTime'],
                                'durationMin'   => (int)$_meta['durationMin'],
                                'leadId'        => (int)($b['lead_id'] ?? 0),
                                'leadName'      => trim((string)($b['lead_name'] ?? '')),
                                'agentName'     => trim((string)(($b['assigned_name'] ?? '') ?: ($b['assigned_agent_name'] ?? '') ?: ($b['agent_name'] ?? ''))),
                                'scheduleName'  => trim((string)(($b['schedule_title'] ?? '') ?: ($b['schedule_name'] ?? ''))),
                            ];
                            $leadInitial = $_mb['leadName'] !== '' ? strtoupper(substr($_mb['leadName'], 0, 1)) : 'L';
                            $agentInitial = $_mb['agentName'] !== '' ? strtoupper(substr($_mb['agentName'], 0, 1)) : 'A';
                            $leadLink = $_mb['leadId'] > 0 ? site_url('/agent/leads/view/' . $_mb['leadId']) : '';
                        ?>
                            <tr class="hover:bg-slate-50/50 transition" id="row-<?= $bid ?>">
                                <td class="px-6 py-4">
                                    <div class="flex flex-col">
                                        <p class="text-sm font-bold text-slate-800">
                                            <?= esc($_mb['dateReadable']) ?>
                                        </p>
                                        <p class="text-[11px] text-slate-400 font-medium">
                                            <?= esc($_mb['dayOfWeek']) ?>
                                        </p>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <p class="text-sm font-medium text-slate-700 font-mono">
                                        <?= esc($_mb['startTime']) ?>
                                        <span class="text-slate-400 mx-1">→</span>
                                        <?= esc($_mb['endTime']) ?>
                                    </p>
                                </td>
                                <td class="px-6 py-4">
                                    <?php if ($_mb['durationMin'] > 0): ?>
                                        <span class="inline-flex items-center gap-1 px-2.5 py-1 rounded-lg bg-slate-100 text-slate-700 text-[11px] font-bold">
                                            <svg xmlns="http://www.w3.org/2000/svg" class="w-3 h-3" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                            </svg>
                                            <?= $_mb['durationMin'] ?> min
                                        </span>
                                    <?php else: ?>
                                        <span class="text-sm text-slate-400">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4">
                                    <?php if ($leadLink !== '' && $_mb['leadName'] !== ''): ?>
                                        <a href="<?= esc($leadLink) ?>"
                                           class="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl bg-gradient-to-r from-indigo-50 to-blue-50 text-indigo-700 text-xs font-bold border border-indigo-200/60 hover:from-indigo-100 hover:to-blue-100 transition max-w-[220px] truncate">
                                            <span class="w-5 h-5 rounded-lg bg-gradient-to-br from-indigo-500 to-blue-600 flex items-center justify-center text-white text-[10px] font-bold flex-shrink-0">
                                                <?= esc($leadInitial) ?>
                                            </span>
                                            <span class="truncate"><?= esc($_mb['leadName']) ?></span>
                                        </a>
                                    <?php elseif ($_mb['leadName'] !== ''): ?>
                                        <span class="text-sm font-medium text-slate-700"><?= esc($_mb['leadName']) ?></span>
                                    <?php else: ?>
                                        <span class="text-sm text-slate-400">—</span>
                                    <?php endif; ?>
                                </td>
                                <td class="px-6 py-4">
                                    <div class="flex items-center gap-2">
                                        <?php if ($_mb['agentName'] !== ''): ?>
                                            <div class="w-7 h-7 rounded-lg bg-gradient-to-br from-emerald-400 to-cyan-500 flex items-center justify-center text-white text-[10px] font-bold flex-shrink-0">
                                                <?= esc($agentInitial) ?>
                                            </div>
                                            <span class="text-sm font-medium text-slate-700"><?= esc($_mb['agentName']) ?></span>
                                        <?php else: ?>
                                            <span class="text-sm text-slate-400">—</span>
                                        <?php endif; ?>
                                    </div>
                                </td>
                                <td class="px-6 py-4">
                                    <p class="text-sm font-medium text-slate-700"><?= $_mb['scheduleName'] !== '' ? esc($_mb['scheduleName']) : '—' ?></p>
                                </td>
                                <td class="px-6 py-4">
                                    <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-bold border <?= $statusClass ?>">
                                        <?= esc(ucfirst($status)) ?>
                                    </span>
                                </td>
                                <td class="px-6 py-4 text-right">
                                    <div class="inline-flex items-center gap-1.5">
                                        <a href="<?= esc(site_url('/agent/bookings/view/' . $bid)) ?>"
                                           class="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-[12px] font-semibold bg-slate-100 hover:bg-slate-200 text-slate-700 transition">
                                            <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="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                                                <path stroke-linecap="round" stroke-linejoin="round" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                                            </svg>
                                            View
                                        </a>
                                        <?php if ($canCancel): ?>
                                            <button type="button" id="cancel-btn-<?= $bid ?>" onclick="cancelBooking(<?= $bid ?>)"
                                                class="inline-flex items-center gap-1 px-3 py-1.5 rounded-lg text-[12px] font-semibold bg-rose-50 hover:bg-rose-100 text-rose-700 transition disabled:opacity-60 disabled:cursor-not-allowed">
                                                <span id="cancel-spin-<?= $bid ?>" class="hidden inline-block w-3 h-3 border-2 border-rose-300 border-t-rose-600 rounded-full animate-spin"></span>
                                                <span id="cancel-icon-<?= $bid ?>">
                                                    <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="M6 18L18 6M6 6l12 12" />
                                                    </svg>
                                                </span>
                                                <span id="cancel-text-<?= $bid ?>">Cancel</span>
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

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

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

    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) {
            setTimeout(() => window.location.reload(), 600);
        } else {
            alert(data.msg || data.error || 'Failed to cancel booking.');
            btn.disabled = false;
            spin.classList.add('hidden');
            icon.classList.remove('hidden');
            text.textContent = 'Retry';
        }
    } catch (e) {
        alert('Network error — please try again.');
        btn.disabled = false;
        spin.classList.add('hidden');
        icon.classList.remove('hidden');
        text.textContent = 'Cancel';
    }
}
</script>
<?= $this->endSection() ?>
