<?php
declare(strict_types=1);

require_once dirname(__DIR__) . '/lib/tenant.php';
require_once dirname(__DIR__) . '/lib/admin_layout.php';

require_admin();
$tenantId = current_tenant_id();
$flash = '';
$error = '';

// Ensure bookings table exists (friendly nudge)
try {
    db()->query('SELECT 1 FROM bookings LIMIT 1');
} catch (Throwable $e) {
    admin_header('Schedule Calendar', 'calendar');
    echo '<div class="flash error">Bookings table missing. Run <a href="' . htmlspecialchars(APP_BASE) . '/migrate.php">migrate.php</a> once, then reload.</div>';
    admin_footer();
    exit;
}

$month = $_GET['month'] ?? date('Y-m');
if (!preg_match('/^\d{4}-\d{2}$/', $month)) {
    $month = date('Y-m');
}
$monthStart = DateTime::createFromFormat('Y-m-d', $month . '-01') ?: new DateTime('first day of this month');
$monthEnd = (clone $monthStart)->modify('last day of this month');
$prev = (clone $monthStart)->modify('-1 month')->format('Y-m');
$next = (clone $monthStart)->modify('+1 month')->format('Y-m');

$selectedDay = $_GET['day'] ?? date('Y-m-d');
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $selectedDay)) {
    $selectedDay = date('Y-m-d');
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = (string) ($_POST['action'] ?? '');
    try {
        if ($action === 'add_schedule_exception') {
            $staffId = (int) ($_POST['staff_id'] ?? 0);
            $offDate = trim((string) ($_POST['off_date'] ?? $selectedDay));
            $reason = trim((string) ($_POST['reason'] ?? '')) ?: null;
            $kind = (string) ($_POST['exception_kind'] ?? 'day_off');
            if ($staffId < 1 || !preg_match('/^\d{4}-\d{2}-\d{2}$/', $offDate)) {
                throw new RuntimeException('Pick a barber and a valid date.');
            }
            $chk = db()->prepare('SELECT id FROM staff_barbers WHERE id = ? AND tenant_id = ?');
            $chk->execute([$staffId, $tenantId]);
            if (!$chk->fetch()) {
                throw new RuntimeException('Staff not found.');
            }
            $isDayOff = 1;
            $openTime = null;
            $closeTime = null;
            if ($kind === 'custom_hours') {
                $openTime = trim((string) ($_POST['open_time'] ?? ''));
                $closeTime = trim((string) ($_POST['close_time'] ?? ''));
                if (!preg_match('/^\d{2}:\d{2}$/', $openTime) || !preg_match('/^\d{2}:\d{2}$/', $closeTime)) {
                    throw new RuntimeException('Custom hours need open and close times (HH:MM).');
                }
                if ($openTime >= $closeTime) {
                    throw new RuntimeException('Close time must be after open time.');
                }
                $isDayOff = 0;
            }
            db()->prepare(
                'INSERT INTO staff_time_off (tenant_id, staff_id, off_date, is_day_off, open_time, close_time, reason)
                 VALUES (?,?,?,?,?,?,?)
                 ON DUPLICATE KEY UPDATE is_day_off = VALUES(is_day_off), open_time = VALUES(open_time),
                   close_time = VALUES(close_time), reason = VALUES(reason)'
            )->execute([$tenantId, $staffId, $offDate, $isDayOff, $openTime, $closeTime, $reason]);
            $flash = $isDayOff
                ? 'Day off saved — no public slots for that barber on ' . $offDate . '.'
                : 'Custom hours saved for ' . $offDate . ' (' . $openTime . '–' . $closeTime . ').';
            $selectedDay = $offDate;
            $month = substr($offDate, 0, 7);
            $monthStart = DateTime::createFromFormat('Y-m-d', $month . '-01') ?: $monthStart;
            $monthEnd = (clone $monthStart)->modify('last day of this month');
        } elseif ($action === 'remove_time_off') {
            $id = (int) ($_POST['id'] ?? 0);
            db()->prepare('DELETE FROM staff_time_off WHERE id = ? AND tenant_id = ?')->execute([$id, $tenantId]);
            $flash = 'Schedule exception removed.';
        }
    } catch (Throwable $e) {
        $error = $e->getMessage();
        if (str_contains($error, 'staff_time_off')) {
            $error = 'Schedule table missing. Run migrate.php once, then try again.';
        }
    }
}

$services = db()->prepare('SELECT id, name, duration_minutes FROM services WHERE tenant_id = ? ORDER BY display_order');
$services->execute([$tenantId]);
$serviceRows = $services->fetchAll();

$staff = db()->prepare('SELECT id, name FROM staff_barbers WHERE tenant_id = ? ORDER BY name');
$staff->execute([$tenantId]);
$staffRows = $staff->fetchAll();

$stmt = db()->prepare(
    'SELECT b.*, s.name AS service_name, sb.name AS staff_name
     FROM bookings b
     LEFT JOIN services s ON s.id = b.service_id
     LEFT JOIN staff_barbers sb ON sb.id = b.staff_id
     WHERE b.tenant_id = ? AND b.starts_at >= ? AND b.starts_at < DATE_ADD(?, INTERVAL 1 DAY)
     ORDER BY b.starts_at'
);
$stmt->execute([$tenantId, $monthStart->format('Y-m-d 00:00:00'), $monthEnd->format('Y-m-d')]);
$bookings = $stmt->fetchAll();

$byDay = [];
foreach ($bookings as $b) {
    $day = substr((string) $b['starts_at'], 0, 10);
    $byDay[$day][] = $b;
}

$timeOffRows = [];
$offByDay = [];
try {
    $toff = db()->prepare(
        'SELECT t.*, sb.name AS staff_name
         FROM staff_time_off t
         JOIN staff_barbers sb ON sb.id = t.staff_id
         WHERE t.tenant_id = ? AND t.off_date >= ? AND t.off_date <= ?
         ORDER BY t.off_date, sb.name'
    );
    $toff->execute([$tenantId, $monthStart->format('Y-m-d'), $monthEnd->format('Y-m-d')]);
    $timeOffRows = $toff->fetchAll();
    foreach ($timeOffRows as $row) {
        $offByDay[(string) $row['off_date']][] = $row;
    }
} catch (Throwable $e) {
    // table may not exist until migrate
}

$dayBookings = $byDay[$selectedDay] ?? [];
$dayOffs = $offByDay[$selectedDay] ?? [];

// Calendar grid: start from Sunday of first week
$gridStart = (clone $monthStart);
$dow = (int) $gridStart->format('w'); // 0=Sun
$gridStart->modify("-{$dow} days");
$gridEnd = (clone $monthEnd);
$endDow = (int) $gridEnd->format('w');
$gridEnd->modify('+' . (6 - $endDow) . ' days');

admin_header('Schedule Calendar', 'calendar');
if ($flash): ?><div class="flash"><?= htmlspecialchars($flash) ?></div><?php endif; ?>
<?php if ($error): ?><div class="flash error"><?= htmlspecialchars($error) ?></div><?php endif; ?>
<div class="panel">
  <div style="display:flex;justify-content:space-between;align-items:center;gap:1rem;flex-wrap:wrap">
    <h2 style="margin:0"><?= htmlspecialchars($monthStart->format('F Y')) ?></h2>
    <div style="display:flex;gap:.5rem">
      <a class="btn secondary" href="?month=<?= $prev ?>">← Prev</a>
      <a class="btn secondary" href="?month=<?= date('Y-m') ?>&day=<?= date('Y-m-d') ?>">Today</a>
      <a class="btn secondary" href="?month=<?= $next ?>">Next →</a>
    </div>
  </div>
  <p class="muted">Click a day to view and manage bookings. Public Book form writes into this calendar.</p>

  <div class="cal-grid">
    <?php foreach (['Sun','Mon','Tue','Wed','Thu','Fri','Sat'] as $d): ?>
      <div class="cal-dow"><?= $d ?></div>
    <?php endforeach; ?>
    <?php
    $cursor = clone $gridStart;
    while ($cursor <= $gridEnd):
      $ymd = $cursor->format('Y-m-d');
      $inMonth = $cursor->format('Y-m') === $monthStart->format('Y-m');
      $count = count($byDay[$ymd] ?? []);
      $offCount = count($offByDay[$ymd] ?? []);
      $isSelected = $ymd === $selectedDay;
      $isToday = $ymd === date('Y-m-d');
      $classes = 'cal-day';
      if (!$inMonth) $classes .= ' muted-day';
      if ($isSelected) $classes .= ' selected';
      if ($isToday) $classes .= ' today';
      if ($offCount) $classes .= ' has-off';
      ?>
      <a class="<?= $classes ?>" href="?month=<?= urlencode($month) ?>&day=<?= $ymd ?>">
        <span class="cal-num"><?= $cursor->format('j') ?></span>
        <?php if ($offCount): ?>
          <?php
            $anyOff = false;
            $anyCustom = false;
            foreach ($offByDay[$ymd] as $ox) {
                if ((int) ($ox['is_day_off'] ?? 1) === 1) {
                    $anyOff = true;
                } else {
                    $anyCustom = true;
                }
            }
          ?>
          <span class="cal-count" style="color:var(--danger)">
            <?= $anyOff ? 'Off' : '' ?><?= $anyOff && $anyCustom ? ' · ' : '' ?><?= $anyCustom ? 'Hours' : '' ?>
          </span>
        <?php endif; ?>
        <?php if ($count): ?>
          <span class="cal-count"><?= $count ?> booking<?= $count === 1 ? '' : 's' ?></span>
          <div class="cal-dots">
            <?php foreach (array_slice($byDay[$ymd], 0, 3) as $b): ?>
              <span class="cal-dot status-<?= htmlspecialchars((string) $b['status']) ?>"></span>
            <?php endforeach; ?>
          </div>
        <?php endif; ?>
      </a>
      <?php
      $cursor->modify('+1 day');
    endwhile;
    ?>
  </div>
</div>

<div class="grid-2">
  <div class="panel">
    <h2>Bookings · <?= htmlspecialchars(date('D, M j, Y', strtotime($selectedDay))) ?></h2>
    <?php if (!$dayBookings): ?>
      <p class="muted">No bookings this day.</p>
    <?php else: ?>
      <table class="table">
        <thead>
          <tr>
            <th>Time</th><th>Client</th><th>Service</th><th>Barber</th><th>Pay</th><th>Status</th><th></th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($dayBookings as $b): ?>
            <tr data-id="<?= (int) $b['id'] ?>">
              <td><?= htmlspecialchars(date('g:i A', strtotime((string) $b['starts_at']))) ?>
                <div class="muted" style="font-size:.8rem"><?= htmlspecialchars(date('g:i A', strtotime((string) $b['ends_at']))) ?></div>
              </td>
              <td>
                <strong><?= htmlspecialchars($b['customer_name']) ?></strong>
                <div class="muted" style="font-size:.8rem"><?= htmlspecialchars((string) $b['customer_phone']) ?></div>
              </td>
              <td><?= htmlspecialchars((string) ($b['service_name'] ?? '—')) ?></td>
              <td><?= htmlspecialchars((string) ($b['staff_name'] ?? 'Any')) ?></td>
              <td>
                <div style="font-size:.8rem"><?= htmlspecialchars((string) ($b['payment_status'] ?? 'unpaid')) ?></div>
                <?php if ((float) ($b['deposit_paid'] ?? 0) > 0): ?>
                  <div class="muted" style="font-size:.75rem">$<?= number_format((float) $b['deposit_paid'], 2) ?></div>
                <?php endif; ?>
              </td>
              <td>
                <select class="status-select" data-id="<?= (int) $b['id'] ?>" style="margin:0;min-width:110px">
                  <?php foreach (['pending','confirmed','completed','cancelled','awaiting_payment','no_show'] as $st): ?>
                    <option value="<?= $st ?>" <?= $b['status'] === $st ? 'selected' : '' ?>><?= $st ?></option>
                  <?php endforeach; ?>
                </select>
              </td>
              <td style="white-space:nowrap">
                <?php if (!in_array((string) $b['status'], ['cancelled', 'completed'], true)): ?>
                  <button type="button" class="btn small secondary toggle-reschedule"
                    data-id="<?= (int) $b['id'] ?>"
                    data-service="<?= (int) $b['service_id'] ?>"
                    data-staff="<?= (int) ($b['staff_id'] ?? 0) ?>"
                    data-date="<?= htmlspecialchars(substr((string) $b['starts_at'], 0, 10)) ?>">Reschedule</button>
                <?php endif; ?>
                <button type="button" class="btn small secondary no-show-btn" data-id="<?= (int) $b['id'] ?>">No-show</button>
                <button type="button" class="btn small secondary waive-btn" data-id="<?= (int) $b['id'] ?>">Waive fee</button>
                <button type="button" class="btn small secondary charge-fee-btn" data-id="<?= (int) $b['id'] ?>">Fee link</button>
                <button type="button" class="btn small danger del-booking" data-id="<?= (int) $b['id'] ?>">Delete</button>
              </td>
            </tr>
            <?php if (!in_array((string) $b['status'], ['cancelled', 'completed'], true)): ?>
            <tr class="reschedule-row" id="reschedule-row-<?= (int) $b['id'] ?>" hidden>
              <td colspan="7">
                <form class="admin-reschedule-form" data-id="<?= (int) $b['id'] ?>" style="display:grid;gap:.75rem;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));align-items:end">
                  <div>
                    <label>New date</label>
                    <input type="date" class="rs-date" required value="<?= htmlspecialchars(substr((string) $b['starts_at'], 0, 10)) ?>"
                      data-service="<?= (int) $b['service_id'] ?>" data-booking="<?= (int) $b['id'] ?>">
                  </div>
                  <div>
                    <label>Barber</label>
                    <select class="rs-staff">
                      <option value="">Any available</option>
                      <?php foreach ($staffRows as $st): ?>
                        <option value="<?= (int) $st['id'] ?>" <?= (int) ($b['staff_id'] ?? 0) === (int) $st['id'] ? 'selected' : '' ?>><?= htmlspecialchars($st['name']) ?></option>
                      <?php endforeach; ?>
                    </select>
                  </div>
                  <div style="grid-column:1/-1">
                    <label>Available times</label>
                    <div class="slot-grid rs-slots" id="admin-slots-<?= (int) $b['id'] ?>"></div>
                    <input type="hidden" class="rs-time" required>
                  </div>
                  <div>
                    <button class="btn" type="submit">Save new time</button>
                  </div>
                </form>
              </td>
            </tr>
            <?php endif; ?>
          <?php endforeach; ?>
        </tbody>
      </table>
    <?php endif; ?>
  </div>

  <div class="panel">
    <h2>Add booking</h2>
    <form id="admin-book-form">
      <label>Customer name</label>
      <input type="text" name="customer_name" required>
      <label>Phone</label>
      <input type="text" name="customer_phone">
      <label>Email (reminders)</label>
      <input type="email" name="customer_email" placeholder="optional">
      <label>Service</label>
      <select name="service_id" required>
        <option value="">Select…</option>
        <?php foreach ($serviceRows as $sv): ?>
          <option value="<?= (int) $sv['id'] ?>"><?= htmlspecialchars($sv['name']) ?> (<?= (int) $sv['duration_minutes'] ?> min)</option>
        <?php endforeach; ?>
      </select>
      <label>Barber</label>
      <select name="staff_id">
        <option value="">Any / unassigned</option>
        <?php foreach ($staffRows as $st): ?>
          <option value="<?= (int) $st['id'] ?>"><?= htmlspecialchars($st['name']) ?></option>
        <?php endforeach; ?>
      </select>
      <label>Starts at</label>
      <input type="datetime-local" name="starts_at" required value="<?= htmlspecialchars($selectedDay . 'T10:00') ?>">
      <label>Status</label>
      <select name="status">
        <option value="confirmed">confirmed</option>
        <option value="pending">pending</option>
      </select>
      <button class="btn" type="submit">Save to calendar</button>
    </form>
  </div>
</div>

<div class="panel">
  <h2>Barber schedule · <?= htmlspecialchars(date('D, M j, Y', strtotime($selectedDay))) ?></h2>
  <p class="muted">Override the weekly Staff hours for this date only: full day off, or custom open/close. Weekly pattern stays under <a href="<?= htmlspecialchars(APP_BASE) ?>/admin/staff.php">Staff</a>.</p>
  <form method="post" class="grid-2" id="schedule-exception-form">
    <input type="hidden" name="action" value="add_schedule_exception">
    <div>
      <label>Barber</label>
      <select name="staff_id" required>
        <option value="">Select…</option>
        <?php foreach ($staffRows as $st): ?>
          <option value="<?= (int) $st['id'] ?>"><?= htmlspecialchars($st['name']) ?></option>
        <?php endforeach; ?>
      </select>
      <label>Date</label>
      <input type="date" name="off_date" required value="<?= htmlspecialchars($selectedDay) ?>">
      <label>Type</label>
      <select name="exception_kind" id="exceptionKind">
        <option value="day_off">Full day off</option>
        <option value="custom_hours">Custom hours this day</option>
      </select>
    </div>
    <div>
      <div id="customHoursFields" hidden>
        <label>Open</label>
        <input type="time" name="open_time" value="10:00">
        <label>Close</label>
        <input type="time" name="close_time" value="14:00">
      </div>
      <label>Reason (optional)</label>
      <input type="text" name="reason" placeholder="Vacation, early leave, training…">
      <button class="btn" type="submit" style="margin-top:1rem">Save schedule override</button>
    </div>
  </form>
  <?php if ($dayOffs): ?>
    <table class="table" style="margin-top:1rem">
      <thead><tr><th>Barber</th><th>Override</th><th>Reason</th><th></th></tr></thead>
      <tbody>
        <?php foreach ($dayOffs as $off): ?>
          <tr>
            <td><?= htmlspecialchars((string) $off['staff_name']) ?></td>
            <td>
              <?php if ((int) ($off['is_day_off'] ?? 1) === 1): ?>
                <strong style="color:var(--danger)">Day off</strong>
              <?php else: ?>
                <?= htmlspecialchars(substr((string) ($off['open_time'] ?? ''), 0, 5)) ?>
                –
                <?= htmlspecialchars(substr((string) ($off['close_time'] ?? ''), 0, 5)) ?>
              <?php endif; ?>
            </td>
            <td class="muted"><?= htmlspecialchars((string) ($off['reason'] ?? '—')) ?></td>
            <td>
              <form method="post" style="margin:0" onsubmit="return confirm('Remove this schedule override?')">
                <input type="hidden" name="action" value="remove_time_off">
                <input type="hidden" name="id" value="<?= (int) $off['id'] ?>">
                <button class="btn small danger" type="submit">Remove</button>
              </form>
            </td>
          </tr>
        <?php endforeach; ?>
      </tbody>
    </table>
  <?php else: ?>
    <p class="muted" style="margin-top:1rem">No schedule overrides on this date.</p>
  <?php endif; ?>
</div>

<script>
(function(){
  const APP_BASE = <?= json_encode(defined('APP_BASE') ? APP_BASE : '/barbershop') ?>;

  const kindSel = document.getElementById('exceptionKind');
  const customFields = document.getElementById('customHoursFields');
  if (kindSel && customFields) {
    const syncKind = () => { customFields.hidden = kindSel.value !== 'custom_hours'; };
    kindSel.addEventListener('change', syncKind);
    syncKind();
  }

  function formatTime(hhmm) {
    const [h, m] = hhmm.split(':').map(Number);
    const ampm = h >= 12 ? 'PM' : 'AM';
    const hr = ((h + 11) % 12) + 1;
    return hr + ':' + String(m).padStart(2, '0') + ' ' + ampm;
  }

  async function loadAdminSlots(form) {
    const dateInput = form.querySelector('.rs-date');
    const staffSelect = form.querySelector('.rs-staff');
    const grid = form.querySelector('.rs-slots');
    const timeInput = form.querySelector('.rs-time');
    timeInput.value = '';
    grid.innerHTML = 'Loading…';
    const params = new URLSearchParams({
      action: 'slots',
      service_id: dateInput.dataset.service,
      date: dateInput.value,
      exclude_booking: dateInput.dataset.booking
    });
    if (staffSelect.value) params.set('staff_id', staffSelect.value);
    const res = await fetch(APP_BASE + '/api/availability.php?' + params.toString());
    const data = await res.json();
    grid.innerHTML = '';
    if (!data.ok || !data.slots || !data.slots.length) {
      grid.textContent = 'No open times that day.';
      return;
    }
    data.slots.forEach(slot => {
      const b = document.createElement('button');
      b.type = 'button';
      b.className = 'slot-btn';
      b.textContent = formatTime(slot.time) + (slot.staff_name && !staffSelect.value ? ' · ' + slot.staff_name : '');
      b.addEventListener('click', () => {
        grid.querySelectorAll('.slot-btn').forEach(x => x.classList.remove('selected'));
        b.classList.add('selected');
        timeInput.value = slot.time;
        timeInput.dataset.resolvedStaff = slot.staff_id ? String(slot.staff_id) : '';
      });
      grid.appendChild(b);
    });
  }

  document.querySelectorAll('.toggle-reschedule').forEach(btn => {
    btn.addEventListener('click', () => {
      const row = document.getElementById('reschedule-row-' + btn.dataset.id);
      if (!row) return;
      row.hidden = !row.hidden;
      if (!row.hidden) {
        const form = row.querySelector('.admin-reschedule-form');
        loadAdminSlots(form);
      }
    });
  });

  document.querySelectorAll('.admin-reschedule-form').forEach(form => {
    form.querySelector('.rs-date').addEventListener('change', () => loadAdminSlots(form));
    form.querySelector('.rs-staff').addEventListener('change', () => loadAdminSlots(form));
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      const timeInput = form.querySelector('.rs-time');
      const time = timeInput.value;
      if (!time) {
        BarberAdmin.toast('Pick a time slot', true);
        return;
      }
      const fd = new FormData();
      fd.append('action', 'reschedule');
      fd.append('id', form.dataset.id);
      fd.append('date', form.querySelector('.rs-date').value);
      fd.append('time', time);
      const staff = form.querySelector('.rs-staff').value || timeInput.dataset.resolvedStaff || '';
      if (staff) fd.append('staff_id', staff);
      try {
        await BarberAdmin.postForm(APP_BASE + '/api/bookings.php', fd);
        BarberAdmin.toast('Appointment rescheduled');
        location.reload();
      } catch (err) {
        BarberAdmin.toast(err.message, true);
      }
    });
  });

  document.querySelectorAll('.status-select').forEach(sel => {
    sel.addEventListener('change', async () => {
      const fd = new FormData();
      fd.append('action', 'update_status');
      fd.append('id', sel.dataset.id);
      fd.append('status', sel.value);
      try {
        await BarberAdmin.postForm(APP_BASE + '/api/bookings.php', fd);
        BarberAdmin.toast('Status updated');
      } catch (e) { BarberAdmin.toast(e.message, true); }
    });
  });
  document.querySelectorAll('.no-show-btn').forEach(btn => {
    btn.addEventListener('click', async () => {
      if (!confirm('Mark as no-show and note the cancel fee?')) return;
      const fd = new FormData();
      fd.append('action', 'mark_no_show');
      fd.append('id', btn.dataset.id);
      try {
        const data = await BarberAdmin.postForm(APP_BASE + '/api/bookings.php', fd);
        BarberAdmin.toast('No-show recorded' + (data.fee ? (' · fee $' + Number(data.fee).toFixed(2)) : ''));
        location.reload();
      } catch (e) { BarberAdmin.toast(e.message, true); }
    });
  });
  document.querySelectorAll('.waive-btn').forEach(btn => {
    btn.addEventListener('click', async () => {
      const fd = new FormData();
      fd.append('action', 'waive_fee');
      fd.append('id', btn.dataset.id);
      try {
        await BarberAdmin.postForm(APP_BASE + '/api/bookings.php', fd);
        BarberAdmin.toast('Fee waived');
        location.reload();
      } catch (e) { BarberAdmin.toast(e.message, true); }
    });
  });
  document.querySelectorAll('.charge-fee-btn').forEach(btn => {
    btn.addEventListener('click', async () => {
      const provider = prompt('Provider for fee checkout link: stripe or paypal', 'stripe');
      if (!provider) return;
      const fd = new FormData();
      fd.append('action', 'charge_fee');
      fd.append('id', btn.dataset.id);
      fd.append('provider', provider.trim());
      fd.append('tenant', window.TENANT_SLUG || '');
      try {
        const data = await BarberAdmin.postForm(APP_BASE + '/api/bookings.php', fd);
        if (data.checkout_url) {
          await navigator.clipboard.writeText(data.checkout_url);
          BarberAdmin.toast('Fee checkout link copied ($' + Number(data.fee).toFixed(2) + ')');
          window.open(data.checkout_url, '_blank');
        } else {
          BarberAdmin.toast('Fee checkout created');
        }
      } catch (e) { BarberAdmin.toast(e.message, true); }
    });
  });
  document.querySelectorAll('.del-booking').forEach(btn => {
    btn.addEventListener('click', async () => {
      if (!confirm('Delete this booking?')) return;
      const fd = new FormData();
      fd.append('action', 'delete');
      fd.append('id', btn.dataset.id);
      try {
        await BarberAdmin.postForm(APP_BASE + '/api/bookings.php', fd);
        location.reload();
      } catch (e) { BarberAdmin.toast(e.message, true); }
    });
  });
  document.getElementById('admin-book-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const form = e.target;
    const fd = new FormData(form);
    fd.append('action', 'create');
    try {
      await BarberAdmin.postForm(APP_BASE + '/api/bookings.php', fd);
      location.reload();
    } catch (err) { BarberAdmin.toast(err.message, true); }
  });
})();
</script>
<?php admin_footer(); ?>
