<?php
/**
 * member_reservation.php — PHP 8.4 compatible
 *
 * Security fixes (all preserved from original hardened version):
 *  - $column validated against ALLOWED_TIME_SLOTS allowlist (column injection fix)
 *  - $eqid cast to (int) before use in SQL
 *  - $eqavailable validated against allowlist ('half'|'full')
 *  - $memberid always sourced from SESSION
 *  - All echoed values wrapped in h() helper (XSS fix)
 *  - mysqli_error() only logged server-side, never shown to user
 *  - exit() after header() calls
 *  - Bug fix: last time slot PM check corrected
 */

session_start(['gc_maxlifetime' => 14400, 'cookie_httponly' => true]);
include('member_session.php');
include('../coach/functions.php');
include('../coach/objects/class.member.php');

// ── XSS-safe output helper ────────────────────────────────────────────────────
function h(mixed $v): string {
    return htmlspecialchars((string)($v ?? ''), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

// ── Allowed time-slot column names (allowlist for SQL column injection fix) ───
const ALLOWED_TIME_SLOTS = [
    '6:00 - 7:00 AM',
    '7:00 - 8:00 AM',
    '8:00 - 9:00 AM',
    '9:00 - 10:00 AM',
    '10:00 - 11:00 AM',
    '5:00 - 6:00 PM',
    '6:00 - 7:00 PM',
    '7:00 - 8:00 PM',
    '8:00 - 9:00 PM',
];

// ── Session-sourced memberid ───────────────────────────────────────────────────
$memberid    = (int)($_SESSION['memberid'] ?? 0);
$page_action = $_POST['action'] ?? 'edit';

// ── Time comparisons ──────────────────────────────────────────────────────────
$currentTime  = (int)date('H');
$currentTimes = date('H:i:s');
$ct    = strtotime($currentTimes);
$am_6  = strtotime('6:00:00');
$am_7  = strtotime('7:00:00');
$am_8  = strtotime('8:00:00');
$am_9  = strtotime('9:00:00');
$am_10 = strtotime('10:00:00');
$pm_5  = strtotime('17:00:00');
$pm_6  = strtotime('18:00:00');
$pm_7  = strtotime('19:00:00');

// ── Auto-clear past time slots ────────────────────────────────────────────────
$slot_clear_map = [
    $am_6  => '6:00 - 7:00 AM',
    $am_7  => '7:00 - 8:00 AM',
    $am_8  => '8:00 - 9:00 AM',
    $am_9  => '9:00 - 10:00 AM',
    $am_10 => '10:00 - 11:00 AM',
    $pm_5  => '5:00 - 6:00 PM',
    $pm_6  => '6:00 - 7:00 PM',
    $pm_7  => '7:00 - 8:00 PM',
];

foreach ($slot_clear_map as $threshold => $slot) {
    if ($ct > $threshold) {
        $runquery = mysqli_query(
            $connection,
            "UPDATE `equipment` SET `$slot`='' WHERE id IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)"
        );
        if (!$runquery) {
            error_log('Slot clear failed: ' . mysqli_error($connection));
        }
    }
}

// ── Auto-clear all slots at end of day or on demand ──────────────────────────
if ($currentTime > 21 || isset($_GET['clear_reservations'])) {
    $allClear = "UPDATE `equipment`
                    SET `6:00 - 7:00 AM`='', `7:00 - 8:00 AM`='', `8:00 - 9:00 AM`='',
                        `9:00 - 10:00 AM`='', `10:00 - 11:00 AM`='',
                        `5:00 - 6:00 PM`='', `6:00 - 7:00 PM`='',
                        `7:00 - 8:00 PM`='', `8:00 - 9:00 PM`='', `reservation_at`=''
                  WHERE id IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)";
    if (!mysqli_query($connection, $allClear)) {
        error_log('Full clear failed: ' . mysqli_error($connection));
    }
}

// ── Auto-clear reservations from previous days ────────────────────────────────
$today = date('Y-m-d');
mysqli_query(
    $connection,
    "UPDATE `equipment`
        SET `6:00 - 7:00 AM`='', `7:00 - 8:00 AM`='', `8:00 - 9:00 AM`='',
            `9:00 - 10:00 AM`='', `10:00 - 11:00 AM`='',
            `5:00 - 6:00 PM`='', `6:00 - 7:00 PM`='',
            `7:00 - 8:00 PM`='', `8:00 - 9:00 PM`='', `reservation_at`=''
      WHERE DATE(reservation_at) < '$today'"
);

// ── Load member name from DB (not from POST) ──────────────────────────────────
$member_object = new Member();
$member        = $member_object->Get($memberid);
$member_fname  = $member->member_fname ?? '';

// ══════════════════════════════════════════════════════════════════════════════
// RESERVE
// ══════════════════════════════════════════════════════════════════════════════
$flash_message = '';
$flash_type    = ''; // 'success' | 'error'

if (isset($_POST['reserve'])) {
    $column = $_POST['time'] ?? '';
    $eqid   = (int)($_POST['equipmentid'] ?? -1);

    if (!in_array($column, ALLOWED_TIME_SLOTS, true) || $eqid < 0) {
        $flash_message = 'Invalid reservation request.';
        $flash_type    = 'error';
    } else {
        $now = date('Y-m-d H:i:s');
        $mysqlquery = "UPDATE `equipment`
                          SET `$column`='" . mysqli_real_escape_string($connection, $member_fname) . "',
                              `reservation_at`='$now'
                        WHERE id=$eqid";
        if (mysqli_query($connection, $mysqlquery)) {
            $flash_message = 'Reservation successful!';
            $flash_type    = 'success';
        } else {
            error_log('Reserve error: ' . mysqli_error($connection));
            $flash_message = 'Please select an available time slot for your reservation.';
            $flash_type    = 'error';
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// UNRESERVE
// ══════════════════════════════════════════════════════════════════════════════
if (isset($_POST['unreserve'])) {
    $column = $_POST['time'] ?? '';
    $eqid   = (int)($_POST['equipmentid'] ?? -1);

    if (!in_array($column, ALLOWED_TIME_SLOTS, true) || $eqid < 0) {
        $flash_message = 'Invalid unreserve request.';
        $flash_type    = 'error';
    } else {
        $mysqlquery = "UPDATE `equipment` SET `$column`='', `reservation_at`='' WHERE id=$eqid";
        if (mysqli_query($connection, $mysqlquery)) {
            $flash_message = 'Reservation cancelled.';
            $flash_type    = 'success';
        } else {
            error_log('Unreserve error: ' . mysqli_error($connection));
            $flash_message = 'Could not cancel reservation. Please try again.';
            $flash_type    = 'error';
        }
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// CLEAR RESERVATION (admin-only: memberid 3 or 550)
// ══════════════════════════════════════════════════════════════════════════════
if (isset($_POST['clear_reservation'])) {
    if ($memberid !== 3 && $memberid !== 550) {
        http_response_code(403);
        exit('Access denied.');
    }
    $eqid = (int)($_POST['equipmentid'] ?? -1);
    if ($eqid >= 0) {
        $mysqlquery = "UPDATE `equipment`
                          SET `6:00 - 7:00 AM`='', `7:00 - 8:00 AM`='', `8:00 - 9:00 AM`='',
                              `9:00 - 10:00 AM`='', `10:00 - 11:00 AM`='',
                              `5:00 - 6:00 PM`='', `6:00 - 7:00 PM`='',
                              `7:00 - 8:00 PM`='', `8:00 - 9:00 PM`='', `reservation_at`=''
                        WHERE id=$eqid";
        if (!mysqli_query($connection, $mysqlquery)) {
            error_log('Clear reservation error: ' . mysqli_error($connection));
        }
        $flash_message = 'Equipment reservations cleared.';
        $flash_type    = 'success';
    }
}

// ══════════════════════════════════════════════════════════════════════════════
// EQ AVAILABILITY toggle (admin-only)
// ══════════════════════════════════════════════════════════════════════════════
if (isset($_POST['eq-availability']) && ($memberid === 3 || $memberid === 550)) {
    $eqavailable = $_POST['eq-availability'];
    if (in_array($eqavailable, ['half', 'full'], true)) {
        $mysqlquery = "UPDATE `equipment` SET `availability`='$eqavailable'
                        WHERE id IN (0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15)";
        if (!mysqli_query($connection, $mysqlquery)) {
            error_log('Availability update error: ' . mysqli_error($connection));
        }
    }
}

// ── Fetch current availability setting ───────────────────────────────────────
$avrow          = mysqli_fetch_assoc(mysqli_query($connection, "SELECT `availability` FROM equipment WHERE `id` = 0"));
$eqavailability = $avrow['availability'] ?? 'full';

// ── "My Reservations" — collect all current member reservations ───────────────
$hasreserved = false;
$dbquery     = "SELECT * FROM equipment ORDER BY id ASC";
$query       = mysqli_query($connection, $dbquery);
$my_reservations = []; // [ ['eqname'=>..., 'time'=>..., 'eqid'=>...], ... ]

while ($row = mysqli_fetch_assoc($query)) {
    $slots    = ALLOWED_TIME_SLOTS;
    $id       = (int)$row['id'];
    foreach ($row as $k => $v) {
        if (in_array($k, ['id', 'name', 'availability', 'reservation_at'], true)) continue;
        if ($v === $member_fname && $v !== '') {
            $hasreserved       = true;
            $my_reservations[] = [
                'eqname' => $row['name'],
                'time'   => $k,
                'eqid'   => $id,
            ];
        }
    }
}

// ── Day-of-week slot visibility flags (used in JS data attrs) ─────────────────
$is_tuesday_thursday_saturday = in_array(date('l'), ['Tuesday', 'Thursday', 'Saturday']);
$is_saturday                  = (date('l') === 'Saturday');
$is_sunday                    = (date('l') === 'Sunday');

// ── Build per-equipment data for each group ───────────────────────────────────
// Each group: name, idStart, idEnd (full availability), halfEnd, img key
$equipment_groups = [
    [
        'key'      => 'treadmill',
        'name'     => 'Treadmill',
        'idStart'  => 0,
        'idEnd'    => 5,     // IDs 0-5 = 6 units
        'halfEnd'  => 1,     // IDs 0-1 = 2 units when half
    ],
    [
        'key'      => 'elliptical',
        'name'     => 'Elliptical Trainer',
        'idStart'  => 6,
        'idEnd'    => 11,    // IDs 6-11 = 6 units (was 7-12 in 1-based)
        'halfEnd'  => 9,     // IDs 6-9 = 4 units when half
    ],
    [
        'key'      => 'bike',
        'name'     => 'Stationary Bike',
        'idStart'  => 12,
        'idEnd'    => 13,    // IDs 12-13 = 2 units
        'halfEnd'  => 12,    // ID 12 only when half
    ],
    [
        'key'      => 'airrunner',
        'name'     => 'Air Runner',
        'idStart'  => 14,
        'idEnd'    => 15,    // IDs 14-15
        'halfEnd'  => 14,    // ID 14 only when half
        'halfOnly' => true,  // hidden entirely when eqavailability === 'half'
    ],
];

// ── Pre-fetch all equipment rows ──────────────────────────────────────────────
$all_equipment = [];
$eq_result = mysqli_query($connection, "SELECT * FROM equipment ORDER BY id ASC");
while ($eq_row = mysqli_fetch_assoc($eq_result)) {
    $all_equipment[(int)$eq_row['id']] = $eq_row;
}

$msg = 'Equipment Reservation';
include('member-header.php');
?>

<!-- ── Bootstrap 5 + Icons ────────────────────────────────────────────────── -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">

<!-- ── Page Styles ────────────────────────────────────────────────────────── -->
<style>
    /* ── Layout ─────────────────────────────────────────────────────────── */
    .app-layout   { display:flex; min-height:100vh; }
    .main-content { flex:1; display:flex; flex-direction:column; min-width:0; background:#f8f9fa; }

    /* ── Page header ─────────────────────────────────────────────────────── */
    .page-header          { background:#fff; border-bottom:1px solid #e5e7eb; padding:1.25rem 1.5rem; }
    .page-header-meta     { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:1rem; }
    .page-header-title    { font-size:1.4rem; font-weight:700; margin:0; line-height:1.2; }
    .page-header-subtitle { font-size:.875rem; color:#6b7280; margin:0; }

    /* ── Body ────────────────────────────────────────────────────────────── */
    .body-content { padding:1.5rem; flex:1; }
    .cr-body      { display:flex; flex-direction:column; gap:1.5rem; }

    /* ── Flash alert ─────────────────────────────────────────────────────── */
    .cr-flash {
        border-radius:.5rem; padding:.75rem 1rem;
        font-size:.875rem; font-weight:600; margin-bottom:.5rem;
    }
    .cr-flash-success { background:#d1fae5; color:#065f46; border:1px solid #6ee7b7; }
    .cr-flash-error   { background:#fee2e2; color:#991b1b; border:1px solid #fca5a5; }

    /* ── Section head ────────────────────────────────────────────────────── */
    .cr-section-head     { margin-bottom:.25rem; }
    .cr-section-title    { font-size:1.1rem; font-weight:700; margin:0 0 .125rem; }
    .cr-section-subtitle { font-size:.875rem; color:#6b7280; margin:0; }

    /* ── Equipment card ──────────────────────────────────────────────────── */
    .cr-equip-list { display:flex; flex-direction:column; gap:1rem; }
    .cr-equip-card {
        background:#fff; border:1px solid #e5e7eb; border-radius:.75rem;
        padding:1.25rem; display:flex; flex-direction:column; gap:1rem;
    }
    .cr-equip-info-wrap { display:flex; align-items:center; justify-content:space-between; flex-wrap:wrap; gap:.75rem; }
    .cr-equip-info      { display:flex; align-items:center; gap:1rem; }
    .cr-equip-icon      {
        display:flex; align-items:center; justify-content:center;
        width:4rem; height:4rem; background:#f3f4f6; border-radius:.625rem; flex-shrink:0;
    }
    .cr-equip-name-wrap { display:flex; flex-direction:column; gap:.2rem; }
    .cr-equip-name      { font-size:1rem; font-weight:700; margin:0; color:#111827; }
    .cr-equip-tag       {
        font-size:.75rem; font-weight:600; padding:.15rem .5rem;
        background:#e5e7eb; color:#374151; border-radius:999px; width:fit-content;
    }
    .cr-equip-controls  { display:flex; flex-direction:column; gap:.75rem; }

    /* ── Scrollable pill-button rows ─────────────────────────────────────── */
    .cr-scroll-wrap     { display:flex; align-items:center; gap:.375rem; }
    .cr-scroll-container{ flex:1; overflow:hidden; position:relative; }
    .cr-scroll-track    { display:flex; gap:.5rem; transition:transform .2s ease; white-space:nowrap; }
    .cr-scroll-arrow {
        display:flex; align-items:center; justify-content:center;
        width:1.75rem; height:1.75rem; flex-shrink:0;
        background:#fff; border:1.5px solid #e5e7eb; border-radius:.375rem;
        cursor:pointer; padding:0; transition:background .12s, border-color .12s;
    }
    .cr-scroll-arrow:hover:not(:disabled) { background:#f3f4f6; border-color:#9ca3af; }
    .cr-scroll-arrow:disabled { opacity:.35; cursor:not-allowed; }

    /* Unit buttons */
    .cr-unit-btn {
        flex-shrink:0; white-space:nowrap;
        padding:.35rem .85rem; border-radius:999px;
        border:1.5px solid #e5e7eb; background:#fff;
        font-size:.8rem; font-weight:500; cursor:pointer;
        transition:background .12s, border-color .12s, color .12s;
        color:#374151;
    }
    .cr-unit-btn:hover { background:#f3f4f6; border-color:#9ca3af; }
    .cr-unit-btn.active { background:#111; color:#fff; border-color:#111; }
    /* Past time slot */
    .cr-unit-btn.past   { background:#f3f4f6; color:#9ca3af; cursor:not-allowed; text-decoration:line-through; }
    /* Reserved by someone else */
    .cr-unit-btn.reserved-other { background:#fee2e2; color:#b91c1c; border-color:#fca5a5; cursor:not-allowed; }
    /* Reserved by this member */
    .cr-unit-btn.reserved-mine  { background:#d1fae5; color:#065f46; border-color:#6ee7b7; }

    /* Time buttons */
    .cr-time-btn {
        flex-shrink:0; white-space:nowrap;
        padding:.35rem .85rem; border-radius:999px;
        border:1.5px solid #e5e7eb; background:#fff;
        font-size:.8rem; font-weight:500; cursor:pointer;
        transition:background .12s, border-color .12s, color .12s;
        color:#374151;
    }
    .cr-time-btn:hover:not(:disabled) { background:#f3f4f6; border-color:#9ca3af; }
    .cr-time-btn.active   { background:#111; color:#fff; border-color:#111; }
    .cr-time-btn.past     { background:#f3f4f6; color:#9ca3af; cursor:not-allowed; text-decoration:line-through; }
    .cr-time-btn.reserved { background:#fee2e2; color:#b91c1c; border-color:#fca5a5; }
    .cr-time-btn:disabled { opacity:.5; cursor:not-allowed; }

    /* ── Action row ──────────────────────────────────────────────────────── */
    .cr-action-row { display:flex; align-items:center; gap:.625rem; flex-wrap:wrap; }

    .cr-clear-btn {
        display:inline-flex; align-items:center; gap:.375rem;
        padding:.5rem 1rem; border-radius:.5rem;
        border:1.5px solid #d1d5db; background:#fff;
        font-size:.85rem; font-weight:500; cursor:pointer; color:#374151;
        transition:background .12s, border-color .12s;
    }
    .cr-clear-btn:hover { background:#f9fafb; border-color:#9ca3af; }

    .cr-reserve-btn {
        display:inline-flex; align-items:center; gap:.375rem;
        padding:.5rem 1.25rem; border-radius:.5rem;
        border:none; background:#111; color:#fff;
        font-size:.85rem; font-weight:600; cursor:pointer;
        transition:background .15s;
    }
    .cr-reserve-btn:hover:not(:disabled) { background:#333; }
    .cr-reserve-btn:disabled { background:#9ca3af; cursor:not-allowed; }

    /* ── Admin controls ──────────────────────────────────────────────────── */
    .cr-admin-bar {
        display:flex; align-items:center; gap:.75rem; flex-wrap:wrap;
        background:#fef9c3; border:1px solid #fde68a; border-radius:.5rem;
        padding:.625rem 1rem; font-size:.85rem;
    }
    .cr-admin-label { font-weight:600; color:#92400e; }
    .cr-admin-select {
        padding:.35rem .6rem; border:1.5px solid #fcd34d; border-radius:.375rem;
        background:#fff; font-size:.85rem; cursor:pointer;
    }
    .cr-admin-clear {
        padding:.35rem .75rem; border-radius:.375rem;
        background:transparent; border:1px solid #fcd34d;
        color:#92400e; font-size:.8rem; font-weight:600; cursor:pointer;
    }
    .cr-admin-clear:hover { background:#fef3c7; }

    /* ── Social-distancing notice ────────────────────────────────────────── */
    .cr-distancing-notice {
        display:inline-flex; align-items:center; gap:.375rem;
        background:#f97316; color:#fff; font-size:.8rem; font-weight:600;
        padding:.3rem .75rem; border-radius:999px;
    }

    /* ── My Reservations panel ───────────────────────────────────────────── */
    .cr-my-res-panel {
        background:#f9fafb; border:1px solid #e5e7eb; border-radius:.75rem;
        padding:1.25rem;
    }
    .cr-my-res-head  { display:flex; align-items:center; justify-content:space-between; margin-bottom:1rem; flex-wrap:wrap; gap:.5rem; }
    .cr-my-res-title { font-size:1rem; font-weight:700; margin:0; }
    .cr-my-res-list  { display:flex; flex-direction:column; gap:.625rem; }
    .cr-my-res-item  {
        display:flex; align-items:center; justify-content:space-between;
        background:#fff; border:1px solid #e5e7eb; border-radius:.5rem;
        padding:.625rem 1rem; gap:.75rem; flex-wrap:wrap;
    }
    .cr-my-res-info  { display:flex; flex-direction:column; gap:.1rem; }
    .cr-my-res-name  { font-size:.9rem; font-weight:600; color:#111827; margin:0; }
    .cr-my-res-time  { font-size:.8rem; color:#6b7280; margin:0; }
    .cr-my-res-empty { font-size:.875rem; color:#6b7280; }
    .cr-unreserve-btn {
        display:inline-flex; align-items:center; gap:.3rem;
        padding:.375rem .75rem; border-radius:.375rem;
        background:#fee2e2; border:1px solid #fca5a5;
        color:#b91c1c; font-size:.8rem; font-weight:600;
        cursor:pointer; transition:background .12s;
    }
    .cr-unreserve-btn:hover { background:#fecaca; }

    /* ── Sunday / day-field overrides (kept from original) ──────────────── */
    .cr-sunday-notice { font-size:.875rem; color:#6b7280; padding:.5rem 0; }

    /* ── Footer note ─────────────────────────────────────────────────────── */
    .cr-footer         { margin-top:.5rem; }
    .cr-footer-note    { font-size:.8rem; color:#6b7280; margin:0 0 .5rem; }
    .cr-footer-divider { border-top:1px solid #e5e7eb; }

    @media (max-width:768px) {
        .body-content { padding:1rem; }
        .page-header  { padding:1rem; }
        .cr-equip-card { padding:1rem; }
    }
</style>



<?php /* Remote-client redirect — identical to original */ ?>
<?php if (!empty($remoteClient) && $remoteClient == 1 && in_array('cardio_reservation', $remote_client ?? [])): ?>
    <script>window.location.href = 'member_homepage.php';</script>
<?php endif; ?>

<div class="app-layout">
    <?php include('menu.php'); ?>
<main class="main-content">

    <!-- ── Page Header ──────────────────────────────────────────────────────── -->
    <header class="page-header">
        <div class="page-header-meta">
            <div>
                <h1 class="page-header-title">Cardio Reservations</h1>
                <p class="page-header-subtitle">Reserve up to 24 hours in advance.</p>
            </div>
            <?php if ($eqavailability === 'half'): ?>
                <div class="cr-distancing-notice">
                    <i class="bi bi-people"></i>
                    Equipment availability reflects proper social distancing guidelines
                </div>
            <?php endif; ?>
        </div>
    </header>

    <!-- ── Body ─────────────────────────────────────────────────────────────── -->
    <div class="body-content">
        <div class="cr-body">

            <?php /* Flash message — replaces original inline <p class="notice/reserved"> */ ?>
            <?php if ($flash_message): ?>
                <div class="cr-flash <?= $flash_type === 'success' ? 'cr-flash-success' : 'cr-flash-error' ?>">
                    <?= h($flash_message) ?>
                </div>
            <?php endif; ?>

            <!-- ── Admin controls ──────────────────────────────────────────── -->
            <?php if ($memberid === 3 || $memberid === 550): ?>
            <div class="cr-admin-bar">
                <span class="cr-admin-label">Admin:</span>
                <form method="post" id="eq-availability-<?= $memberid ?>" style="display:inline;">
                    <label for="eq-avail-select" style="font-size:.85rem;color:#92400e;margin-right:.3rem;">Availability:</label>
                    <select name="eq-availability" id="eq-avail-select" class="cr-admin-select">
                        <option value="half" <?= $eqavailability === 'half' ? 'selected' : '' ?>>Half (Social Distancing)</option>
                        <option value="full" <?= $eqavailability === 'full' ? 'selected' : '' ?>>Full</option>
                    </select>
                </form>
            </div>
            <?php endif; ?>

            <!-- ── My Reservations ─────────────────────────────────────────── -->
            <div class="cr-my-res-panel">
                <div class="cr-my-res-head">
                    <h2 class="cr-my-res-title">My Reservations</h2>
                    <p style="font-size:.8rem;color:#6b7280;margin:0;">View And Manage Your Current Reservations.</p>
                </div>
                <div class="cr-my-res-list">
                    <?php if (empty($my_reservations)): ?>
                        <p class="cr-my-res-empty">You have no active reservations today.</p>
                    <?php else: ?>
                        <?php foreach ($my_reservations as $res): ?>
                        <div class="cr-my-res-item">
                            <div class="cr-my-res-info">
                                <p class="cr-my-res-name"><?= h($res['eqname']) ?></p>
                                <p class="cr-my-res-time"><?= h($res['time']) ?></p>
                            </div>
                            <!-- Unreserve form — POST keys preserved: time, equipmentid, unreserve -->
                            <form method="post" style="margin:0;">
                                <input type="hidden" name="time"        value="<?= h($res['time']) ?>">
                                <input type="hidden" name="equipmentid" value="<?= (int)$res['eqid'] ?>">
                                <button type="submit" name="unreserve" class="cr-unreserve-btn">
                                    <i class="bi bi-x-circle"></i> Unreserve
                                </button>
                            </form>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </div>

            <!-- ── Equipment cards ──────────────────────────────────────────── -->
            <div class="cr-section-head">
                <h2 class="cr-section-title">Equipment</h2>
                <p class="cr-section-subtitle">Select a machine, choose your time slot, then reserve.</p>
            </div>

            <?php
            // ── SVG icons keyed by equipment key ─────────────────────────────
            $eq_icons = [
                'treadmill' => '<svg width="61" height="46" viewBox="0 0 61 46" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M57.4518 28.0762H2.89826C1.73945 28.0762 0.800049 29.0156 0.800049 30.1744V34.3708C0.800049 35.5296 1.73945 36.469 2.89826 36.469H57.4518C58.6106 36.469 59.5501 35.5296 59.5501 34.3708V30.1744C59.5501 29.0156 58.6106 28.0762 57.4518 28.0762Z" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M9.19312 28.0763L17.586 9.19238H42.7645L51.1574 28.0763" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M9.19341 44.8622C12.0904 44.8622 14.4389 42.5137 14.4389 39.6166C14.4389 36.7196 12.0904 34.3711 9.19341 34.3711C6.29638 34.3711 3.94788 36.7196 3.94788 39.6166C3.94788 42.5137 6.29638 44.8622 9.19341 44.8622Z" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M51.1574 44.8622C54.0544 44.8622 56.4029 42.5137 56.4029 39.6166C56.4029 36.7196 54.0544 34.3711 51.1574 34.3711C48.2604 34.3711 45.9119 36.7196 45.9119 39.6166C45.9119 42.5137 48.2604 44.8622 51.1574 44.8622Z" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M17.5862 9.19266V0.799805M42.7648 9.19266V0.799805" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M13.3889 0.799805H46.9603" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>',

                'elliptical' => '<svg width="60" height="60" viewBox="0 0 60 60" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0.800171 54.6572H58.8002" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M0.800171 54.6572L2.8716 58.8001" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M58.8002 54.6572L56.7288 58.8001" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M29.8002 55.6931C41.2404 55.6931 50.5145 53.3746 50.5145 50.5145C50.5145 47.6545 41.2404 45.3359 29.8002 45.3359C18.36 45.3359 9.08594 47.6545 9.08594 50.5145C9.08594 53.3746 18.36 55.6931 29.8002 55.6931Z" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M17.3716 48.4431L19.443 9.08594" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M42.2288 48.4431L40.1573 9.08594" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M15.3002 9.08594H44.3002" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M19.4431 9.08594L9.08594 32.9074" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M40.1573 9.08594L50.5145 32.9074" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M9.08594 32.9072L13.2288 50.5144" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M50.5144 32.9072L46.3716 50.5144" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M32.9073 0.799805H26.6931C26.1211 0.799805 25.6573 1.26351 25.6573 1.83552V4.94266C25.6573 5.51467 26.1211 5.97837 26.6931 5.97837H32.9073C33.4794 5.97837 33.9431 5.51467 33.9431 4.94266V1.83552C33.9431 1.26351 33.4794 0.799805 32.9073 0.799805Z" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M29.8002 5.97852V9.08566" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>',

                'bike' => '<svg width="63" height="48" viewBox="0 0 63 48" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M11.6404 47.1172C17.6273 47.1172 22.4807 42.2638 22.4807 36.2768C22.4807 30.2899 17.6273 25.4365 11.6404 25.4365C5.65343 25.4365 0.800049 30.2899 0.800049 36.2768C0.800049 42.2638 5.65343 47.1172 11.6404 47.1172Z" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M51.0597 47.1172C57.0466 47.1172 61.9 42.2638 61.9 36.2768C61.9 30.2899 57.0466 25.4365 51.0597 25.4365C45.0727 25.4365 40.2194 30.2899 40.2194 36.2768C40.2194 42.2638 45.0727 47.1172 51.0597 47.1172Z" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M11.6404 36.2771L31.3501 8.68359L51.0597 36.2771" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M25.4371 8.68359H37.2629" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M31.3501 8.68368V0.799805" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M25.4371 0.799805H37.2629" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>',

                'airrunner' => '<svg width="61" height="57" viewBox="0 0 61 57" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M0.800171 43.8831C7.32795 38.6609 17.1196 36.0498 30.1752 36.0498C43.2307 36.0498 53.0224 38.6609 59.5502 43.8831" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M0.800171 43.8828C2.10573 47.7995 4.06406 50.0842 6.67517 50.737H53.6752C56.2863 50.0842 58.2446 47.7995 59.5502 43.8828" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M4.71688 50.7373L2.75854 55.6331" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M55.6335 50.7373L57.5919 55.6331" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M20.3835 36.0495L18.4252 8.63281" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M39.9668 36.0495L41.9251 8.63281" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M14.5085 8.63314C24.953 6.02203 35.3974 6.02203 45.8419 8.63314" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M14.5085 8.63281L12.5502 14.5078" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M45.8418 8.63281L47.8001 14.5078" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M33.1127 0.799805H27.2377C26.6969 0.799805 26.2585 1.23819 26.2585 1.77897V4.71647C26.2585 5.25725 26.6969 5.69564 27.2377 5.69564H33.1127C33.6535 5.69564 34.0919 5.25725 34.0919 4.71647V1.77897C34.0919 1.23819 33.6535 0.799805 33.1127 0.799805Z" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M30.1752 5.69531V8.63281" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M12.5502 39.9668H47.8002" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/><path d="M8.63354 42.9043H51.7169" stroke="#374151" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round"/></svg>',
            ];

            // Shared SVG helpers
            $svg_prev = '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M10 12L6 8L10 4" stroke="black" stroke-opacity="0.5" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/></svg>';
            $svg_next = '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6 12L10 8L6 4" stroke="black" stroke-opacity="0.5" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/></svg>';
            $svg_clear = '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M2 8C2 6.4087 2.63214 4.88258 3.75736 3.75736C4.88258 2.63214 6.4087 2 8 2C9.67737 2.00631 11.2874 2.66082 12.4933 3.82667L14 5.33333" stroke="#212529" stroke-opacity="0.7" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 2L14 5.33333H10.6667" stroke="#212529" stroke-opacity="0.7" stroke-linecap="round" stroke-linejoin="round"/><path d="M14 8C14 9.5913 13.3679 11.1174 12.2426 12.2426C11.1174 13.3679 9.5913 14 8 14C6.32263 13.9937 4.71265 13.3392 3.50667 12.1733L2 10.6667" stroke="#212529" stroke-opacity="0.7" stroke-linecap="round" stroke-linejoin="round"/><path d="M5.33333 10.667H2L2 14.0003" stroke="#212529" stroke-opacity="0.7" stroke-linecap="round" stroke-linejoin="round"/></svg>';
            $svg_reserve = '<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M6.66666 1.66699L6.66666 5.00033" stroke="white" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/><path d="M13.3333 1.66699L13.3333 5.00033" stroke="white" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/><path d="M15.8333 3.33301L4.16667 3.33301C3.24619 3.33301 2.5 4.0792 2.5 4.99967L2.5 16.6663C2.5 17.5868 3.24619 18.333 4.16667 18.333H15.8333C16.7538 18.333 17.5 17.5868 17.5 16.6663L17.5 4.99967C17.5 4.0792 16.7538 3.33301 15.8333 3.33301Z" stroke="white" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/><path d="M2.5 8.33301L17.5 8.33301" stroke="white" stroke-width="1.33333" stroke-linecap="round" stroke-linejoin="round"/></svg>';
            ?>

            <div class="cr-equip-list">
            <?php foreach ($equipment_groups as $group):
                // Air Runner hidden entirely when half-availability — original logic
                if (!empty($group['halfOnly']) && $eqavailability === 'half') continue;

                $idEnd = ($eqavailability === 'half') ? $group['halfEnd'] : $group['idEnd'];
                ?>
                <div class="cr-equip-card" data-equip="<?= h($group['key']) ?>">
                    <div class="cr-equip-info-wrap">
                        <div class="cr-equip-info">
                            <div class="cr-equip-icon">
                                <?= $eq_icons[$group['key']] ?? '' ?>
                            </div>
                            <div class="cr-equip-name-wrap">
                                <p class="cr-equip-name"><?= h($group['name']) ?></p>
                                <span class="cr-equip-tag">Cardio</span>
                            </div>
                        </div>
                        <?php /* Admin clear-all button per machine group */ ?>
                        <?php if ($memberid === 3 || $memberid === 550): ?>
                            <form method="post" style="margin:0;">
                                <input type="hidden" name="equipmentid" value="<?= $group['idStart'] ?>">
                                <button type="submit" name="clear_reservation" class="cr-admin-clear">
                                    Clear All
                                </button>
                            </form>
                        <?php endif; ?>
                    </div>

                    <div class="cr-equip-controls">
                        <?php if ($is_sunday): ?>
                            <p class="cr-sunday-notice">No availability on Sundays.</p>
                        <?php else: ?>

                        <!-- Unit selector -->
                        <div class="cr-scroll-wrap" data-scroll="units">
                            <button class="cr-scroll-arrow cr-scroll-prev" aria-label="Scroll left"><?= $svg_prev ?></button>
                            <div class="cr-scroll-container">
                                <div class="cr-scroll-track">
                                    <?php for ($i = $group['idStart'], $unitNum = 1; $i <= $idEnd; $i++, $unitNum++):
                                        $eq_row = $all_equipment[$i] ?? null;
                                        $isFull = false;
                                        if ($eq_row) {
                                            // Unit considered "fully reserved" if all non-meta columns are taken
                                            $slotCount   = 0; $reservedCount = 0;
                                            foreach ($eq_row as $k => $v) {
                                                if (in_array($k, ['id','name','availability','reservation_at'], true)) continue;
                                                $slotCount++;
                                                if (!empty($v)) $reservedCount++;
                                            }
                                            $isFull = ($slotCount > 0 && $reservedCount === $slotCount);
                                        }
                                        $isFirstUnit = ($i === $group['idStart']);
                                        $unitLabel   = $group['name'] . ' - ' . $unitNum;
                                    ?>
                                        <button class="cr-unit-btn <?= $isFirstUnit ? 'active' : '' ?> <?= $isFull ? 'reserved-other' : '' ?>"
                                                data-eqid="<?= $i ?>"
                                                data-unit="<?= $unitNum ?>">
                                            <?= h($unitLabel) ?>
                                        </button>
                                    <?php endfor; ?>
                                </div>
                            </div>
                            <button class="cr-scroll-arrow cr-scroll-next" aria-label="Scroll right"><?= $svg_next ?></button>
                        </div>

                        <!-- Time slot selector (populated by JS when unit changes) -->
                        <div class="cr-scroll-wrap" data-scroll="times">
                            <button class="cr-scroll-arrow cr-scroll-prev" aria-label="Scroll left"><?= $svg_prev ?></button>
                            <div class="cr-scroll-container">
                                <div class="cr-scroll-track">
                                    <?php
                                    // Render time slots for the first (active) unit
                                    $first_eq_row = $all_equipment[$group['idStart']] ?? [];
                                    $x = 1;
                                    foreach (ALLOWED_TIME_SLOTS as $slot):
                                        // Day-of-week visibility — identical to original field-N CSS rules
                                        // field-3 = '8:00-9:00 AM', field-7 = '6:00-7:00 PM'
                                        $slotHidden = false;
                                        if ($is_tuesday_thursday_saturday && $slot === '8:00 - 9:00 AM') $slotHidden = true;
                                        if (!$is_saturday && $slot === '6:00 - 7:00 PM') $slotHidden = true;
                                        if ($is_saturday && in_array($slot, ['8:00 - 9:00 AM','9:00 - 10:00 AM','10:00 - 11:00 AM','7:00 - 8:00 PM','8:00 - 9:00 PM'])) $slotHidden = true;
                                        if ($slotHidden) continue;

                                        $slotVal    = $first_eq_row[$slot] ?? '';
                                        $isPast     = (
                                            ($slot === '6:00 - 7:00 AM'   && $ct > $am_6)  ||
                                            ($slot === '7:00 - 8:00 AM'   && $ct > $am_7)  ||
                                            ($slot === '8:00 - 9:00 AM'   && $ct > $am_8)  ||
                                            ($slot === '9:00 - 10:00 AM'  && $ct > $am_9)  ||
                                            ($slot === '10:00 - 11:00 AM' && $ct > $am_10) ||
                                            ($slot === '5:00 - 6:00 PM'   && $ct > $pm_5)  ||
                                            ($slot === '6:00 - 7:00 PM'   && $ct > $pm_6)  ||
                                            ($slot === '7:00 - 8:00 PM'   && $ct > $pm_7)
                                        );
                                        $isMine     = (!empty($slotVal) && $slotVal === $member_fname);
                                        $isReserved = (!empty($slotVal) && !$isMine);
                                        $firstSlot  = ($slot === ALLOWED_TIME_SLOTS[0]);
                                        $btnClass   = 'cr-time-btn';
                                        if ($isPast)     $btnClass .= ' past';
                                        elseif ($isMine) $btnClass .= ' reserved-mine active';
                                        elseif ($isReserved) $btnClass .= ' reserved';
                                        elseif ($firstSlot && !$isPast && !$isReserved) $btnClass .= ' active';
                                    ?>
                                        <button class="<?= $btnClass ?>"
                                                data-slot="<?= h($slot) ?>"
                                                <?= ($isPast || $isReserved) ? 'disabled' : '' ?>>
                                            <?= h($slot) ?>
                                        </button>
                                    <?php $x++; endforeach; ?>
                                </div>
                            </div>
                            <button class="cr-scroll-arrow cr-scroll-next" aria-label="Scroll right"><?= $svg_next ?></button>
                        </div>

                        <!-- Actions -->
                        <!-- Reserve form — POST keys preserved: time (hidden), equipmentid (hidden), reserve (submit) -->
                        <form method="post" class="cr-reserve-form" style="margin:0;">
                            <input type="hidden" name="time"        class="selected-time-input" value="<?= h(ALLOWED_TIME_SLOTS[0]) ?>">
                            <input type="hidden" name="equipmentid" class="selected-eqid-input"  value="<?= $group['idStart'] ?>">
                            <div class="cr-action-row">
                                <button type="button" class="cr-clear-btn">
                                    <?= $svg_clear ?> Clear
                                </button>
                                <?php if (!$hasreserved): ?>
                                <button type="submit" name="reserve" class="cr-reserve-btn">
                                    <?= $svg_reserve ?> Reserve
                                </button>
                                <?php else: ?>
                                <button type="button" class="cr-reserve-btn" disabled title="You already have a reservation today">
                                    <?= $svg_reserve ?> Reserve
                                </button>
                                <?php endif; ?>
                            </div>
                        </form>

                        <?php endif; // end !$is_sunday ?>
                    </div><!-- /.cr-equip-controls -->
                </div><!-- /.cr-equip-card -->
            <?php endforeach; ?>
            </div><!-- /.cr-equip-list -->

            <!-- Footer note -->
            <div class="cr-footer">
                <p class="cr-footer-note">Reservations Can Be Made Up To 24 Hours In Advance.</p>
                <div class="cr-footer-divider"></div>
            </div>

        </div><!-- /.cr-body -->
    </div><!-- /.body-content -->

</main>
</div><!-- /.app-layout -->

<script src="../coach/js/jquery.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>

<script>
// ================================================================
// 1. HORIZONTAL SCROLL LOGIC (from cardio-reservations.html)
// ================================================================
document.addEventListener('DOMContentLoaded', function () {

    document.querySelectorAll('.cr-scroll-wrap').forEach(function (wrap) {
        var container = wrap.querySelector('.cr-scroll-container');
        var track     = wrap.querySelector('.cr-scroll-track');
        var prevBtn   = wrap.querySelector('.cr-scroll-prev');
        var nextBtn   = wrap.querySelector('.cr-scroll-next');
        var scrollPos = 0;
        var scrollStep = 150;

        function checkOverflow() {
            var isOverflow = track.scrollWidth > container.clientWidth;
            if (isOverflow) {
                wrap.classList.add('has-overflow');
                updateArrows();
            } else {
                wrap.classList.remove('has-overflow');
                scrollPos = 0;
                track.style.transform = 'translateX(0px)';
            }
        }

        function updateArrows() {
            var maxScroll = track.scrollWidth - container.clientWidth;
            prevBtn.disabled = scrollPos <= 0;
            nextBtn.disabled = scrollPos >= maxScroll;
        }

        prevBtn.addEventListener('click', function () {
            scrollPos = Math.max(0, scrollPos - scrollStep);
            track.style.transform = 'translateX(-' + scrollPos + 'px)';
            updateArrows();
        });

        nextBtn.addEventListener('click', function () {
            var maxScroll = track.scrollWidth - container.clientWidth;
            scrollPos = Math.min(maxScroll, scrollPos + scrollStep);
            track.style.transform = 'translateX(-' + scrollPos + 'px)';
            updateArrows();
        });

        checkOverflow();

        var resizeTimer;
        window.addEventListener('resize', function () {
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(function () {
                var maxScroll = track.scrollWidth - container.clientWidth;
                if (scrollPos > maxScroll) {
                    scrollPos = Math.max(0, maxScroll);
                    track.style.transform = 'translateX(-' + scrollPos + 'px)';
                }
                checkOverflow();
            }, 150);
        });
    });

    // ================================================================
    // 2. UNIT BUTTON SELECTION
    //    When a unit button is clicked:
    //      a) Activate it visually
    //      b) Update the hidden equipmentid input in the form
    //      c) Re-render time slots from the data embedded in data-slots attr
    // ================================================================
    document.querySelectorAll('.cr-unit-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            if (this.disabled || this.classList.contains('reserved-other')) return;
            var card = this.closest('.cr-equip-card');

            // Activate unit
            card.querySelectorAll('.cr-unit-btn').forEach(function (b) { b.classList.remove('active'); });
            this.classList.add('active');

            // Update hidden equipmentid
            var eqid = this.getAttribute('data-eqid');
            card.querySelector('.selected-eqid-input').value = eqid;

            // Re-fetch time slot states via data attribute (set by PHP below via data-slots)
            var slotsJson = this.getAttribute('data-slots');
            if (!slotsJson) return;
            var slots = JSON.parse(slotsJson);
            var timeTrack = card.querySelector('[data-scroll="times"] .cr-scroll-track');
            timeTrack.querySelectorAll('.cr-time-btn').forEach(function (tb) {
                var slotName = tb.getAttribute('data-slot');
                var val = slots[slotName] || '';
                tb.classList.remove('reserved','reserved-mine','past','active');
                tb.disabled = false;
                // past class handled server-side via initial render; JS only applies reserved states
                if (val === '<?= addslashes($member_fname) ?>') {
                    tb.classList.add('reserved-mine', 'active');
                } else if (val !== '') {
                    tb.classList.add('reserved');
                    tb.disabled = true;
                }
            });

            // Reset form time to first available slot
            var firstAvail = timeTrack.querySelector('.cr-time-btn:not(.past):not([disabled])');
            if (firstAvail) {
                timeTrack.querySelectorAll('.cr-time-btn').forEach(function (b) { b.classList.remove('active'); });
                firstAvail.classList.add('active');
                card.querySelector('.selected-time-input').value = firstAvail.getAttribute('data-slot');
            }
        });
    });

    // ================================================================
    // 3. TIME BUTTON SELECTION
    //    Updates the hidden time input in the reserve form.
    // ================================================================
    document.querySelectorAll('.cr-time-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            if (this.disabled) return;
            var wrap = this.closest('[data-scroll="times"]');
            wrap.querySelectorAll('.cr-time-btn').forEach(function (b) { b.classList.remove('active'); });
            this.classList.add('active');

            // Update hidden time input
            var card = this.closest('.cr-equip-card');
            card.querySelector('.selected-time-input').value = this.getAttribute('data-slot');
        });
    });

    // ================================================================
    // 4. CLEAR BUTTON — resets unit + time selection to defaults
    // ================================================================
    document.querySelectorAll('.cr-clear-btn').forEach(function (btn) {
        btn.addEventListener('click', function () {
            var card = this.closest('.cr-equip-card');

            // Reset unit to first
            var unitBtns = card.querySelectorAll('.cr-unit-btn');
            unitBtns.forEach(function (b, i) { b.classList.toggle('active', i === 0); });
            if (unitBtns[0]) {
                card.querySelector('.selected-eqid-input').value = unitBtns[0].getAttribute('data-eqid');
            }

            // Reset time to first available
            var timeBtns = card.querySelectorAll('.cr-time-btn');
            var resetDone = false;
            timeBtns.forEach(function (b) {
                b.classList.remove('active');
                if (!resetDone && !b.disabled && !b.classList.contains('past')) {
                    b.classList.add('active');
                    card.querySelector('.selected-time-input').value = b.getAttribute('data-slot');
                    resetDone = true;
                }
            });

            // Reset scroll positions
            card.querySelectorAll('.cr-scroll-track').forEach(function (t) {
                t.style.transform = 'translateX(0px)';
            });
            card.querySelectorAll('.cr-scroll-wrap').forEach(function (w) {
                var ct2  = w.querySelector('.cr-scroll-container');
                var t2   = w.querySelector('.cr-scroll-track');
                var pb   = w.querySelector('.cr-scroll-prev');
                var nb   = w.querySelector('.cr-scroll-next');
                if (t2.scrollWidth > ct2.clientWidth) {
                    pb.disabled = true;
                    nb.disabled = false;
                }
            });
        });
    });

    // ================================================================
    // 5. Admin: auto-submit availability select on change
    // ================================================================
    var adminForm = document.getElementById('eq-availability-<?= $memberid ?>');
    if (adminForm) {
        adminForm.querySelector('select').addEventListener('change', function () {
            adminForm.submit();
        });
    }
});
</script>

<?php
// ── Embed per-unit slot data as JSON into data-slots attributes ───────────────
// This lets JS update time-slot states when the user switches units
// without an AJAX call, keeping the original no-AJAX architecture.
?>
<script>
(function () {
    document.querySelectorAll('.cr-unit-btn').forEach(function (btn) {
        var eqid = btn.getAttribute('data-eqid');
        if (!eqid) return;

        // Slot data is embedded server-side below
        var slotDataMap = <?php
            $slot_data = [];
            foreach ($all_equipment as $id => $row) {
                $slots = [];
                foreach (ALLOWED_TIME_SLOTS as $s) {
                    $slots[$s] = $row[$s] ?? '';
                }
                $slot_data[$id] = $slots;
            }
            echo json_encode($slot_data, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT);
        ?>;

        if (slotDataMap[eqid]) {
            btn.setAttribute('data-slots', JSON.stringify(slotDataMap[eqid]));
        }
    });
})();
</script>

<?php include('member-footer.php'); ?>