<?php
$dayNames = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
$durationOptions = [15, 30, 45, 60, 90];
$breakOptions = [0, 5, 10, 15, 30, 60];
$timezones = ['America/Los_Angeles', 'America/New_York', 'America/Chicago', 'America/Denver', 'America/Phoenix', 'UTC', 'Europe/London', 'Europe/Paris', 'Asia/Tokyo', 'Australia/Sydney'];

$usersById = [];
foreach (($agents ?? []) as $ag) {
    $usersById[(int)($ag['id'] ?? 0)] = $ag;
}

$roleBadge = function ($role) {
    $r = strtolower((string)$role);
    if ($r === 'admin') {
        return '<span class="ml-1.5 inline-flex items-center px-1.5 py-0.5 rounded-md bg-rose-100 text-rose-700 text-[9px] font-bold uppercase tracking-wide">Admin</span>';
    }
    return '<span class="ml-1.5 inline-flex items-center px-1.5 py-0.5 rounded-md bg-sky-100 text-sky-700 text-[9px] font-bold uppercase tracking-wide">Agent</span>';
};
?>

<div class="space-y-6">
    <div class="flex flex-wrap items-center justify-between gap-3">
        <div>
            <h2 class="text-lg font-bold text-slate-800">Booking Schedules</h2>
            <p class="text-sm text-slate-500">Manage availability schedules, time slots, and agent assignments.</p>
        </div>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 p-6" id="schedule-form-card">
        <div class="flex items-start gap-3 mb-5">
            <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-sky-500 to-indigo-500 text-white flex items-center justify-center shadow-md shadow-sky-500/20 flex-shrink-0">
                <svg xmlns="http://www.w3.org/2000/svg" class="w-[18px] h-[18px]" id="schedule-form-icon" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="1.8">
                    <path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                </svg>
            </div>
            <div class="flex-1">
                <h3 class="text-base font-semibold text-slate-800" id="schedule-form-title">Add Schedule</h3>
                <p class="text-[11px] text-slate-500 mt-0.5" id="schedule-form-sub">Create a new booking schedule with availability windows and assigned agents.</p>
            </div>
            <a href="<?= site_url('/admin/booking-schedules') ?>" id="schedule-form-cancel" class="hidden px-3 py-1.5 rounded-lg text-[11px] font-semibold text-slate-600 bg-slate-100 hover:bg-slate-200 transition">Cancel edit</a>
        </div>
        <form method="post" action="<?= site_url('/admin/booking-schedules') ?>" id="schedule-form" class="space-y-5">
            <?= csrf_field() ?>
            <input type="hidden" name="action" id="schedule-form-action" value="save">
            <input type="hidden" name="schedule_id" id="schedule-form-id" value="0">
            <div class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4">
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Schedule Title</label>
                    <input type="text" id="sf_title" name="title" required class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition" placeholder="e.g. Standard Weekday">
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Timezone</label>
                    <select name="timezone" id="sf_timezone" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition">
                        <?php foreach ($timezones as $tz): ?>
                            <option value="<?= esc($tz) ?>" <?= $tz === 'America/Los_Angeles' ? 'selected' : '' ?>><?= esc($tz) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Meeting Duration (min)</label>
                    <select name="meeting_duration_minutes" id="sf_meeting" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition">
                        <?php foreach ($durationOptions as $d): ?>
                            <option value="<?= $d ?>" <?= $d === 30 ? 'selected' : '' ?>><?= $d ?> min</option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div>
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Break Between (min)</label>
                    <select name="break_duration_minutes" id="sf_break" class="w-full rounded-xl border border-slate-300 bg-white px-4 py-2.5 text-sm focus:ring-2 focus:ring-sky-500/30 focus:border-sky-500 outline-none transition">
                        <?php foreach ($breakOptions as $b): ?>
                            <option value="<?= $b ?>" <?= $b === 10 ? 'selected' : '' ?>><?= $b === 0 ? 'No break' : $b . ' min' ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <div class="md:col-span-2 xl:col-span-1">
                    <label class="block text-xs font-semibold text-slate-600 mb-1.5">Active</label>
                    <div class="flex items-center h-[42px]">
                        <label class="inline-flex items-center gap-2.5 cursor-pointer">
                            <input type="checkbox" id="sf_active" name="is_active" value="1" checked class="w-4.5 h-4.5 text-sky-600 rounded">
                            <span class="text-sm font-medium text-slate-700">Schedule is active</span>
                        </label>
                    </div>
                </div>
            </div>

            <div>
                <label class="block text-xs font-semibold text-slate-600 mb-2">Available Days</label>
                <div class="flex flex-wrap gap-2" id="sf_days">
                    <?php for ($i = 0; $i < 7; $i++): ?>
                        <label class="inline-flex items-center gap-2 px-3.5 py-2 rounded-xl border border-slate-200 bg-white hover:bg-slate-50 cursor-pointer transition sf-day-wrap">
                            <input type="checkbox" name="days[]" value="<?= $i ?>" class="w-4 h-4 text-sky-600 rounded sf-day" data-day="<?= $i ?>">
                            <span class="text-sm font-semibold text-slate-700"><?= $dayNames[$i] ?></span>
                        </label>
                    <?php endfor; ?>
                </div>
            </div>

            <div>
                <label class="block text-xs font-semibold text-slate-600 mb-1.5">
                    Assigned Agents &amp; Admins
                    <span class="text-[10px] text-slate-400 font-normal ml-1">(multi-select, admins shown in pink)</span>
                </label>
                <div class="rounded-xl border border-slate-300 bg-white max-h-48 overflow-y-auto scrollbar-thin">
                    <?php if (empty($agents)): ?>
                        <div class="p-4 text-center text-[11px] text-slate-500">No users defined yet.</div>
                    <?php else: ?>
                        <?php foreach ($agents as $u):
                            $uid = (int)$u['id'];
                            $ur  = (string)($u['role'] ?? 'agent');
                        ?>
                            <label class="flex items-start gap-2.5 px-3 py-2 border-b border-slate-100 last:border-b-0 hover:bg-slate-50 transition cursor-pointer sf-agent-wrap">
                                <input type="checkbox" name="assigned_agent_ids[]" value="<?= $uid ?>" class="mt-0.5 w-4 h-4 text-sky-600 rounded sf-agent" data-user="<?= $uid ?>">
                                <div class="flex-1 min-w-0">
                                    <div class="flex items-center flex-wrap">
                                        <span class="text-[12px] font-medium text-slate-800 truncate"><?= esc($u['full_name'] ?? $u['username'] ?? 'User') ?></span>
                                        <?= $roleBadge($ur) ?>
                                    </div>
                                    <span class="text-[10px] text-slate-500"><?= esc($u['email'] ?? '') ?></span>
                                </div>
                            </label>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <div class="flex justify-end">
                <button type="submit" id="schedule-form-submit" class="px-6 py-2.5 rounded-xl text-sm font-semibold text-white bg-gradient-to-r from-sky-600 to-indigo-600 shadow-md hover:shadow-lg transition">
                    Save Schedule
                </button>
            </div>
        </form>
    </div>

    <div class="glass rounded-2xl shadow-sm border border-slate-200/60 p-6">
        <div class="flex items-start gap-3 mb-5">
            <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-md shadow-violet-500/20 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="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>
            <div class="flex-1">
                <h3 class="text-base font-semibold text-slate-800">Schedules</h3>
                <p class="text-[11px] text-slate-500 mt-0.5">All booking schedules with shift windows and agent assignments.</p>
            </div>
        </div>

        <?php if (empty($schedules)): ?>
            <div class="text-center py-12">
                <div class="w-16 h-16 rounded-2xl bg-slate-100 flex items-center justify-center mx-auto mb-3">
                    <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="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>
                <p class="text-sm font-medium text-slate-600">No schedules created yet.</p>
                <p class="text-[11px] text-slate-500 mt-1">Use the form above to add your first schedule.</p>
            </div>
        <?php else: ?>
            <div class="space-y-4">
                <?php foreach ($schedules as $s):
                    $sid = (int)$s['id'];
                    $daysArr = !empty($s['days_json']) ? (array)json_decode($s['days_json'], true) : [];
                    if (!is_array($daysArr)) $daysArr = [];
                    $daysArr = array_values(array_filter(array_map('intval', $daysArr)));
                    $agentIds = !empty($s['assigned_agent_ids_json']) ? (array)json_decode($s['assigned_agent_ids_json'], true) : [];
                    if (!is_array($agentIds)) $agentIds = [];
                    $agentIds = array_values(array_filter(array_map('intval', $agentIds)));
                    $agentPills = [];
                    foreach ($agentIds as $aid) {
                        $u = $usersById[$aid] ?? null;
                        $name = $u ? ($u['full_name'] ?? ($u['username'] ?? "User #{$aid}")) : "User #{$aid}";
                        $role = $u ? (string)($u['role'] ?? 'agent') : 'agent';
                        $agentPills[] = ['name' => $name, 'role' => $role];
                    }
                    $shifts = $s['shifts'] ?? [];
                    $bookingsCount = (int)($s['bookings_count'] ?? ($s['booking_count'] ?? 0));
                    $payload = [
                        'id'       => $sid,
                        'title'    => (string)($s['title'] ?? ''),
                        'timezone' => (string)($s['timezone'] ?? ''),
                        'meeting'  => (int)($s['meeting_duration_minutes'] ?? 30),
                        'break'    => (int)($s['break_duration_minutes'] ?? 0),
                        'active'   => !empty($s['is_active']),
                        'days'     => $daysArr,
                        'agents'   => $agentIds,
                    ];
                ?>
                    <div class="border border-slate-200/80 rounded-2xl bg-gradient-to-br from-white/80 to-slate-50/60 overflow-hidden">
                        <div class="flex flex-wrap items-center gap-3 px-5 py-4 border-b border-slate-200/80 bg-slate-50/50">
                            <div class="flex-1 min-w-0">
                                <div class="flex flex-wrap items-center gap-2 mb-1.5">
                                    <h4 class="text-sm font-bold text-slate-800 truncate"><?= esc($s['title']) ?></h4>
                                    <?php if (!empty($s['is_active'])): ?>
                                        <span class="inline-flex items-center px-2 py-0.5 rounded-full bg-emerald-100 text-emerald-700 text-[10px] font-bold">ACTIVE</span>
                                    <?php else: ?>
                                        <span class="inline-flex items-center px-2 py-0.5 rounded-full bg-slate-200 text-slate-600 text-[10px] font-bold">INACTIVE</span>
                                    <?php endif; ?>
                                    <span class="inline-flex items-center px-2 py-0.5 rounded-full bg-indigo-50 text-indigo-700 text-[10px] font-semibold">
                                        <?= $bookingsCount ?> booking<?= $bookingsCount === 1 ? '' : 's' ?>
                                    </span>
                                </div>
                                <div class="flex flex-wrap gap-x-4 gap-y-1 text-[11px] text-slate-500">
                                    <span><?= esc($s['timezone']) ?></span>
                                    <span>Meeting: <?= (int)$s['meeting_duration_minutes'] ?>min</span>
                                    <span>Break: <?= (int)$s['break_duration_minutes'] ?>min</span>
                                </div>
                            </div>
                            <div class="flex items-center gap-2">
                                <button type="button" class="sf-edit-btn inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-[11px] font-semibold text-slate-700 bg-slate-100 hover:bg-slate-200 border border-slate-200 transition"
                                    data-schedule="<?= esc(json_encode($payload), 'attr') ?>">
                                    <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.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" /></svg>
                                    Edit
                                </button>
                                <a href="<?= site_url('/admin/booking-schedules/delete/' . $sid) ?>" onclick="return confirm('Delete this schedule and all its shifts?');" class="p-2 rounded-lg text-red-500 hover:bg-red-50 transition" title="Delete schedule">
                                    <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
                                </a>
                            </div>
                        </div>

                        <div class="p-5 space-y-4">
                            <div class="flex flex-wrap gap-2">
                                <span class="text-[11px] font-semibold text-slate-500 uppercase tracking-wider mr-1 pt-1">Days:</span>
                                <?php if (empty($daysArr)): ?>
                                    <span class="text-[11px] text-slate-400 italic">No days selected</span>
                                <?php else: ?>
                                    <?php foreach ($daysArr as $di): ?>
                                        <span class="inline-flex items-center px-2.5 py-1 rounded-lg bg-sky-100 text-sky-800 text-[11px] font-bold"><?= $dayNames[$di] ?? '?' ?></span>
                                    <?php endforeach; ?>
                                <?php endif; ?>
                            </div>

                            <div>
                                <span class="text-[11px] font-semibold text-slate-500 uppercase tracking-wider block mb-2">Assigned Agents &amp; Admins:</span>
                                <?php if (empty($agentPills)): ?>
                                    <span class="text-[11px] text-slate-400 italic">No agents assigned</span>
                                <?php else: ?>
                                    <div class="flex flex-wrap gap-1.5">
                                        <?php foreach ($agentPills as $ap): ?>
                                            <?php
                                            $isAdmin = strtolower($ap['role'] ?? '') === 'admin';
                                            $pillClasses = $isAdmin
                                                ? 'bg-gradient-to-r from-rose-100 to-pink-100 text-rose-800'
                                                : 'bg-gradient-to-r from-violet-100 to-fuchsia-100 text-violet-800';
                                            $dotClasses = $isAdmin ? 'bg-rose-500' : 'bg-violet-500';
                                            ?>
                                            <span class="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full <?= $pillClasses ?> text-[11px] font-semibold">
                                                <span class="w-1.5 h-1.5 rounded-full <?= $dotClasses ?>"></span>
                                                <?= esc($ap['name']) ?>
                                                <?php if ($isAdmin): ?>
                                                    <span class="ml-0.5 inline-flex px-1 py-0.5 rounded bg-white/60 text-rose-700 text-[9px] font-bold uppercase tracking-wide">admin</span>
                                                <?php endif; ?>
                                            </span>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </div>

                            <div>
                                <div class="flex items-center justify-between mb-2">
                                    <span class="text-[11px] font-semibold text-slate-500 uppercase tracking-wider">Shift Windows</span>
                                </div>
                                <form method="post" action="<?= site_url('/admin/booking-schedules') ?>" class="flex flex-wrap items-stretch gap-2 mb-3">
                                    <?= csrf_field() ?>
                                    <input type="hidden" name="action" value="save-shift">
                                    <input type="hidden" name="schedule_id" value="<?= $sid ?>">
                                    <input type="time" name="shift_start" step="300" required class="rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition">
                                    <span class="flex items-center text-slate-400 text-sm px-1">→</span>
                                    <input type="time" name="shift_end" step="300" required class="rounded-xl border border-slate-300 bg-white px-3 py-2 text-sm focus:ring-2 focus:ring-violet-500/30 focus:border-violet-500 outline-none transition">
                                    <button type="submit" class="inline-flex items-center gap-1.5 px-4 py-2 rounded-xl bg-gradient-to-r from-violet-600 to-fuchsia-600 text-white text-xs font-bold shadow-sm hover:shadow-md 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="2"><path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6m0 0v6m0-6h6m-6 0H6" /></svg>
                                        Add Shift
                                    </button>
                                </form>

                                <?php if (empty($shifts)): ?>
                                    <div class="p-3 rounded-xl border border-dashed border-slate-200 text-center">
                                        <span class="text-[11px] text-slate-400 italic">No shifts defined. Add at least one shift window above.</span>
                                    </div>
                                <?php else: ?>
                                    <div class="space-y-1.5">
                                        <?php foreach ($shifts as $sh):
                                            $shid = (int)$sh['id'];
                                        ?>
                                            <div class="flex items-center justify-between px-3.5 py-2 rounded-xl bg-white border border-slate-200 hover:border-slate-300 transition">
                                                <div class="flex items-center gap-3">
                                                    <div class="w-2 h-2 rounded-full bg-emerald-500"></div>
                                                    <span class="text-sm font-mono font-semibold text-slate-700">
                                                        <?= esc($sh['shift_start'] ?? '') ?>
                                                        <span class="text-slate-400 mx-1">→</span>
                                                        <?= esc($sh['shift_end'] ?? '') ?>
                                                    </span>
                                                </div>
                                                <a href="<?= site_url('/admin/booking-schedules/shift/delete/' . $shid) ?>" onclick="return confirm('Delete this shift?');" class="p-1.5 rounded-lg text-rose-500 hover:bg-rose-50 transition" title="Delete shift">
                                                    <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="M6 18L18 6M6 6l12 12" /></svg>
                                                </a>
                                            </div>
                                        <?php endforeach; ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>
        <?php endif; ?>

        <div class="mt-8 grid grid-cols-1 md:grid-cols-3 gap-4">
            <div class="rounded-2xl border border-emerald-200/70 bg-gradient-to-br from-emerald-50/70 to-white p-5">
                <div class="flex items-center gap-3 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-md shadow-emerald-500/20">
                        <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="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" /></svg>
                    </div>
                    <div>
                        <p class="font-bold text-emerald-800 mb-1.5 text-sm">1. Availability</p>
                        <p class="text-slate-600 leading-relaxed text-[12px]">Each schedule becomes a unique bookable link you can share with leads.</p>
                    </div>
                </div>
                <p class="text-slate-600 leading-relaxed text-[12px]">Meeting &amp; break durations apply to every slot window of that schedule.</p>
            </div>

            <div class="rounded-2xl border border-sky-200/70 bg-gradient-to-br from-sky-50/70 to-white p-5">
                <div class="flex items-center gap-3 mb-3">
                    <div class="w-9 h-9 rounded-xl bg-gradient-to-br from-sky-500 to-indigo-500 text-white flex items-center justify-center shadow-md shadow-sky-500/20">
                        <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="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>
                    <div>
                        <p class="font-bold text-sky-800 mb-1.5 text-sm">2. Agent Assignments</p>
                        <p class="text-slate-600 leading-relaxed text-[12px]">Pick which agents (or admins) are eligible to take meetings for each schedule.</p>
                    </div>
                </div>
                <p class="text-slate-600 leading-relaxed text-[12px]">When no agents are assigned, any agent can accept / be booked on it.</p>
            </div>

            <div class="rounded-2xl border border-violet-200/70 bg-gradient-to-br from-violet-50/70 to-white p-5">
                <div class="flex items-center gap-3 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-md shadow-violet-500/20">
                        <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="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /></svg>
                    </div>
                    <div>
                        <p class="font-bold text-violet-800 mb-1.5 text-sm">3. Exceptions &amp; Bookings</p>
                        <p class="text-slate-600 leading-relaxed text-[12px]">Schedule exceptions (full-day closures) and already-booked slots are automatically excluded from available times.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
(function(){
    var form = document.getElementById('schedule-form');
    if (!form) return;
    var title    = document.getElementById('sf_title');
    var timezone = document.getElementById('sf_timezone');
    var meeting  = document.getElementById('sf_meeting');
    var brk      = document.getElementById('sf_break');
    var active   = document.getElementById('sf_active');
    var action   = document.getElementById('schedule-form-action');
    var sid      = document.getElementById('schedule-form-id');
    var days     = form.querySelectorAll('.sf-day');
    var agents   = form.querySelectorAll('.sf-agent');
    var card     = document.getElementById('schedule-form-card');
    var cancel   = document.getElementById('schedule-form-cancel');
    var formHdr  = document.getElementById('schedule-form-title');
    var formSub  = document.getElementById('schedule-form-sub');
    var submitBtn= document.getElementById('schedule-form-submit');
    var formIcon = document.getElementById('schedule-form-icon');

    function setForCreate(){
        action.value = 'save';
        sid.value = '0';
        if (formHdr) formHdr.textContent = 'Add Schedule';
        if (formSub) formSub.textContent = 'Create a new booking schedule with availability windows and assigned agents.';
        if (submitBtn) submitBtn.textContent = 'Save Schedule';
        if (formIcon) formIcon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />';
        if (cancel) cancel.classList.add('hidden');
    }
    function clearForm(){
        form.reset();
        if (timezone) timezone.value = 'America/Los_Angeles';
        if (meeting) meeting.value = '30';
        if (brk) brk.value = '10';
        if (active) active.checked = true;
        days.forEach(function(d){ d.checked = false; });
        agents.forEach(function(a){ a.checked = false; });
        if (title) title.value = '';
    }
    if (cancel) cancel.addEventListener('click', function(e){
        e.preventDefault();
        clearForm();
        setForCreate();
        card.scrollIntoView({ behavior: 'smooth', block: 'start' });
    });
    document.querySelectorAll('.sf-edit-btn').forEach(function(btn){
        btn.addEventListener('click', function(){
            try {
                var data = JSON.parse(btn.getAttribute('data-schedule') || '{}');
            } catch(e) { return; }
            clearForm();
            if (title) title.value = data.title || '';
            if (timezone) timezone.value = (data.timezone || 'America/Los_Angeles');
            if (meeting) meeting.value = String(data.meeting || 30);
            if (brk) brk.value = String(data.break || 0);
            if (active) active.checked = !!data.active;
            var daySet = {};
            (data.days || []).forEach(function(d){ daySet[parseInt(d,10)] = true; });
            days.forEach(function(d){
                var n = parseInt(d.getAttribute('data-day') || '0', 10);
                d.checked = !!daySet[n];
            });
            var agSet = {};
            (data.agents || []).forEach(function(a){ agSet[parseInt(a,10)] = true; });
            agents.forEach(function(a){
                var n = parseInt(a.getAttribute('data-user') || '0', 10);
                a.checked = !!agSet[n];
            });
            action.value = 'update';
            sid.value = String(data.id || 0);
            if (formHdr) formHdr.textContent = 'Edit Schedule · ' + (data.title || ('Schedule #' + (data.id || 0)));
            if (formSub) formSub.textContent = 'Update title, timezone, windows, agent assignment, or active status.';
            if (submitBtn) submitBtn.textContent = 'Save Changes';
            if (formIcon) formIcon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" d="M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z" />';
            if (cancel) cancel.classList.remove('hidden');
            card.scrollIntoView({ behavior: 'smooth', block: 'start' });
        });
    });
})();
</script>
