<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>حمام السباحة: <?= e($pool->name_ar) ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/pool/<?= (int) $pool->id ?>/schedules" class="btn btn-outline"><i data-lucide="repeat" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> الجداول الأسبوعية</a>
<a href="/pool/config/<?= (int) $pool->id ?>/edit" class="btn btn-outline"><i data-lucide="settings" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> الإعدادات</a>
<a href="/pool" class="btn btn-outline"><i data-lucide="arrow-right" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> العودة</a>
<?php $__template->endSection(); ?>

<?php $__template->section('content'); ?>

<?php
$lanes = $gridState['lanes'] ?? [];
$timeSlots = $gridState['time_slots'] ?? [];
$cells = $gridState['cells'] ?? [];
$schedules = $schedules ?? [];
$statusColors = [
    'available'   => '#10B981',
    'booked'      => '#3B82F6',
    'in_progress' => '#F59E0B',
    'maintenance' => '#EF4444',
    'scheduled'   => '#8B5CF6',
];
$bookingTypeLabels = [
    'lap_swimming'    => 'سباحة حرة',
    'lessons'         => 'دروس',
    'free_swim'       => 'ترفيهية',
    'academy_session' => 'أكاديمية',
    'competition'     => 'مسابقة',
    'maintenance'     => 'صيانة',
];
?>

<style>
.pool-grid-wrap { user-select:none; }
.pool-grid { border-collapse:collapse; width:100%; }
.pool-grid th, .pool-grid td { padding:0; margin:0; }
.pool-grid th { font-size:11px; color:#6B7280; font-weight:600; }
.pool-cell {
    width:100%; height:52px; border:1px solid #E5E7EB; border-radius:4px;
    cursor:pointer; transition:all 0.12s; position:relative;
    display:flex; align-items:center; justify-content:center;
    font-size:10px; font-weight:600; margin:1px;
}
.pool-cell:hover { transform:scale(1.04); z-index:2; box-shadow:0 2px 8px rgba(0,0,0,0.15); }
.pool-cell.selected { outline:3px solid #1e3a5f; outline-offset:-1px; z-index:3; }
.pool-cell.available { background:#10B98115; border-color:#10B98140; color:#059669; }
.pool-cell.booked { background:#3B82F615; border-color:#3B82F640; color:#2563EB; cursor:default; }
.pool-cell.in_progress { background:#F59E0B15; border-color:#F59E0B40; color:#D97706; cursor:default; }
.pool-cell.maintenance { background:#EF444415; border-color:#EF444440; color:#DC2626; cursor:default; }
.pool-cell.scheduled { background:#8B5CF615; border-color:#8B5CF640; color:#7C3AED; cursor:default; }
.pool-cell .cell-label { font-size:9px; position:absolute; bottom:2px; left:2px; right:2px; text-align:center; overflow:hidden; white-space:nowrap; text-overflow:ellipsis; }
.pool-cell .cell-count { font-size:14px; font-weight:700; }
.lane-header { cursor:pointer; padding:8px 6px !important; border-radius:6px; transition:background 0.15s; text-align:center; }
.lane-header:hover { background:#F0FDFA; }
.time-header { cursor:pointer; padding:6px 2px !important; border-radius:6px; transition:background 0.15s; min-width:60px; text-align:center; }
.time-header:hover { background:#F0FDFA; }
.booking-panel { position:fixed; bottom:0; left:0; right:0; background:#fff; box-shadow:0 -4px 20px rgba(0,0,0,0.15); padding:20px 30px; z-index:100; transform:translateY(100%); transition:transform 0.3s ease; border-top:3px solid #1e3a5f; }
.booking-panel.visible { transform:translateY(0); }
.selection-info { display:flex; gap:20px; align-items:center; flex-wrap:wrap; }
.selection-badge { display:inline-flex; align-items:center; gap:6px; padding:6px 14px; background:#1e3a5f15; border:1px solid #1e3a5f40; border-radius:20px; font-size:13px; color:#1e3a5f; font-weight:600; }
</style>

<!-- Date Navigation + Stats Bar -->
<div style="display:flex;gap:12px;margin-bottom:15px;align-items:stretch;">
    <div class="card" style="padding:12px 16px;display:flex;align-items:center;gap:8px;flex:0 0 auto;">
        <?php
        $prevDate = date('Y-m-d', strtotime($date . ' -1 day'));
        $nextDate = date('Y-m-d', strtotime($date . ' +1 day'));
        $dayNames = ['الأحد','الإثنين','الثلاثاء','الأربعاء','الخميس','الجمعة','السبت'];
        $dayName = $dayNames[(int) date('w', strtotime($date))];
        ?>
        <a href="/pool/<?= (int) $pool->id ?>/grid?date=<?= $prevDate ?>" class="btn btn-sm btn-outline" style="padding:4px 8px;">&rarr;</a>
        <form method="GET" action="/pool/<?= (int) $pool->id ?>/grid" style="display:flex;gap:6px;align-items:center;">
            <input type="date" name="date" value="<?= e($date) ?>" class="form-input" style="direction:ltr;font-size:12px;padding:4px 8px;width:130px;" onchange="this.form.submit()">
        </form>
        <a href="/pool/<?= (int) $pool->id ?>/grid?date=<?= $nextDate ?>" class="btn btn-sm btn-outline" style="padding:4px 8px;">&larr;</a>
        <a href="/pool/<?= (int) $pool->id ?>/grid" class="btn btn-sm btn-outline" style="padding:4px 8px;font-size:11px;">اليوم</a>
        <span style="font-size:13px;font-weight:600;color:#1A1A2E;margin-right:8px;"><?= e($dayName) ?></span>
    </div>

    <div class="card" style="padding:12px 16px;flex:1;display:flex;gap:20px;align-items:center;">
        <div style="text-align:center;"><span style="font-size:18px;font-weight:700;color:#1e3a5f;"><?= $utilization['occupancy_pct'] ?? 0 ?>%</span><div style="font-size:10px;color:#6B7280;">إشغال</div></div>
        <div style="text-align:center;"><span style="font-size:18px;font-weight:700;color:#2563EB;"><?= $utilization['total_bookings'] ?? 0 ?></span><div style="font-size:10px;color:#6B7280;">حجز</div></div>
        <div style="text-align:center;"><span style="font-size:18px;font-weight:700;color:#D97706;"><?= $utilization['total_swimmers'] ?? 0 ?></span><div style="font-size:10px;color:#6B7280;">سبّاح</div></div>
        <div style="text-align:center;"><span style="font-size:18px;font-weight:700;color:#059669;"><?= number_format($utilization['total_revenue'] ?? 0, 0) ?></span><div style="font-size:10px;color:#6B7280;">ج.م</div></div>
        <div style="margin-right:auto;display:flex;gap:8px;flex-wrap:wrap;">
            <?php foreach ($statusColors as $st => $color): ?>
            <span style="display:flex;align-items:center;gap:3px;font-size:10px;"><span style="width:10px;height:10px;border-radius:2px;background:<?= $color ?>;display:inline-block;"></span><?= ['available'=>'متاح','booked'=>'محجوز','in_progress'=>'جاري','maintenance'=>'صيانة','scheduled'=>'جدول'][$st] ?></span>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Instructions -->
<div style="margin-bottom:12px;padding:10px 16px;background:#F0FDFA;border:1px solid #CCFBF1;border-radius:8px;font-size:12px;color:#1e3a5f;display:flex;gap:20px;align-items:center;">
    <span><strong>اضغط</strong> على خلية لتحديدها</span>
    <span><strong>اسحب</strong> لتحديد عدة خلايا</span>
    <span><strong>رأس الحارة</strong> = تحديد صف كامل</span>
    <span><strong>رأس الوقت</strong> = تحديد عمود كامل</span>
    <span><strong>Esc</strong> = إلغاء التحديد</span>
</div>

<!-- The Grid -->
<div class="card pool-grid-wrap" style="padding:0;overflow:auto;">
    <div style="padding:8px;overflow-x:auto;">
        <table class="pool-grid" id="poolGrid">
            <thead>
                <tr>
                    <th style="min-width:70px;position:sticky;right:0;background:#fff;z-index:5;"></th>
                    <?php foreach ($timeSlots as $si => $slot): ?>
                    <th class="time-header" data-col="<?= $si ?>" onclick="selectColumn(<?= $si ?>)">
                        <div style="direction:ltr;font-size:10px;"><?= e($slot['start']) ?></div>
                        <div style="direction:ltr;font-size:9px;color:#9CA3AF;"><?= e($slot['end']) ?></div>
                    </th>
                    <?php endforeach; ?>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($lanes as $li => $lane):
                    $laneNum = (int) $lane['lane_number'];
                ?>
                <tr data-lane="<?= $laneNum ?>">
                    <td class="lane-header" style="position:sticky;right:0;background:#fff;z-index:4;" data-row="<?= $li ?>" onclick="selectRow(<?= $li ?>)">
                        <div style="font-size:12px;font-weight:700;color:#1e3a5f;"><?= e($lane['label_ar'] ?? ('حارة ' . $laneNum)) ?></div>
                        <div style="font-size:9px;color:#9CA3AF;"><?= e($lane['width_meters']) ?>م</div>
                    </td>
                    <?php foreach ($timeSlots as $si => $slot):
                        $slotStart = $slot['start'];
                        $cell = $cells[$laneNum][$slotStart] ?? ['status' => 'available', 'booking' => null];
                        $booking = $cell['booking'];
                        $cellStatus = $cell['status'];

                        // Check if a recurring schedule covers this cell
                        $scheduleMatch = null;
                        if ($cellStatus === 'available') {
                            foreach ($schedules as $sch) {
                                $schLanes = json_decode($sch['lanes_json'] ?? '[]', true);
                                if (is_array($schLanes) && in_array($laneNum, $schLanes)) {
                                    if ($sch['start_time'] <= $slotStart && $sch['end_time'] > $slotStart) {
                                        $scheduleMatch = $sch;
                                        $cellStatus = 'scheduled';
                                        break;
                                    }
                                }
                            }
                        }
                    ?>
                    <td style="padding:2px;">
                        <div class="pool-cell <?= e($cellStatus) ?>"
                             data-row="<?= $li ?>" data-col="<?= $si ?>"
                             data-lane="<?= $laneNum ?>" data-slot="<?= e($slotStart) ?>" data-slot-end="<?= e($slot['end']) ?>"
                             data-status="<?= e($cellStatus) ?>"
                             <?php if ($booking): ?>
                             data-booking-id="<?= (int) $booking['id'] ?>"
                             title="<?= e(($bookingTypeLabels[$booking['type']] ?? '') . ' — ' . ($booking['booker'] ?? '') . ' (' . $booking['swimmers'] . ')') ?>"
                             <?php elseif ($scheduleMatch): ?>
                             title="<?= e(($scheduleMatch['schedule_name'] ?? '') . ' — ' . ($scheduleMatch['coach_name'] ?? '')) ?>"
                             <?php endif; ?>
                        >
                            <?php if ($booking): ?>
                                <span class="cell-count"><?= (int) $booking['swimmers'] ?></span>
                                <span class="cell-label"><?= e($booking['booker'] ?? '') ?></span>
                            <?php elseif ($scheduleMatch): ?>
                                <span class="cell-count"><i data-lucide="repeat" style="width:12px;height:12px;"></i></span>
                                <span class="cell-label"><?= e($scheduleMatch['schedule_name'] ?? '') ?></span>
                            <?php endif; ?>
                        </div>
                    </td>
                    <?php endforeach; ?>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Pool Dimensions Visual -->
<div class="card" style="margin-top:15px;padding:15px 20px;">
    <div style="display:flex;align-items:center;gap:15px;">
        <div style="border:2px solid #1e3a5f;border-radius:8px;padding:6px;background:#F0FDFA;display:flex;gap:2px;flex:1;max-width:500px;">
            <?php foreach ($lanes as $lane): ?>
            <div style="flex:1;height:30px;background:#CCFBF1;border:1px dashed #1e3a5f30;border-radius:3px;display:flex;align-items:center;justify-content:center;font-size:9px;color:#1e3a5f;font-weight:600;">
                <?= (int) $lane['lane_number'] ?>
            </div>
            <?php endforeach; ?>
        </div>
        <span style="font-size:12px;color:#6B7280;"><?= e($pool->length_meters) ?>م × <?= e($pool->width_meters) ?>م<?php if ($pool->depth_shallow || $pool->depth_deep): ?> — عمق: <?= e($pool->depth_shallow ?? '?') ?>–<?= e($pool->depth_deep ?? '?') ?>م<?php endif; ?></span>
    </div>
</div>

<!-- Inline Booking Panel (slides up from bottom) -->
<div class="booking-panel" id="bookingPanel">
    <form method="POST" action="/pool/<?= (int) $pool->id ?>/book-cells" id="cellBookingForm">
        <?= csrf_field() ?>
        <input type="hidden" name="booking_date" value="<?= e($date) ?>">
        <input type="hidden" name="cells_json" id="cellsJsonInput" value="[]">

        <div style="display:flex;gap:20px;align-items:center;flex-wrap:wrap;">
            <div class="selection-info">
                <span class="selection-badge"><i data-lucide="grid-3x3" style="width:14px;height:14px;"></i> <span id="selCount">0</span> خلية محددة</span>
                <span class="selection-badge"><i data-lucide="move-horizontal" style="width:14px;height:14px;"></i> <span id="selLanes">0</span> حارة</span>
                <span class="selection-badge"><i data-lucide="clock" style="width:14px;height:14px;"></i> <span id="selTime">—</span></span>
            </div>

            <div style="display:flex;gap:10px;align-items:center;flex:1;">
                <select name="booking_type" class="form-input" style="width:130px;font-size:12px;padding:6px 10px;" required>
                    <?php foreach ($bookingTypeLabels as $k => $v): ?>
                    <option value="<?= e($k) ?>"><?= e($v) ?></option>
                    <?php endforeach; ?>
                </select>
                <input type="text" name="booker_name" placeholder="اسم الحاجز" class="form-input" style="width:160px;font-size:12px;padding:6px 10px;" required>
                <input type="number" name="expected_swimmers" value="1" min="1" class="form-input" style="width:70px;font-size:12px;padding:6px 10px;direction:ltr;" placeholder="عدد">
                <input type="text" name="notes" placeholder="ملاحظات" class="form-input" style="width:140px;font-size:12px;padding:6px 10px;">
            </div>

            <div style="display:flex;gap:8px;">
                <button type="submit" class="btn btn-primary" style="font-size:13px;padding:8px 20px;">
                    <i data-lucide="check" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> حجز
                </button>
                <button type="button" class="btn btn-outline" style="font-size:13px;padding:8px 10px;" onclick="clearSelection()">
                    <i data-lucide="x" style="width:14px;height:14px;vertical-align:middle;"></i>
                </button>
            </div>
        </div>
    </form>
</div>

<script>
document.addEventListener('DOMContentLoaded', function() {
    if (typeof lucide !== 'undefined') lucide.createIcons();

    var grid = document.getElementById('poolGrid');
    var panel = document.getElementById('bookingPanel');
    var cellsInput = document.getElementById('cellsJsonInput');
    var selected = new Set();
    var isDragging = false;
    var dragStart = null;

    function getCellKey(row, col) { return row + ':' + col; }

    function toggleCell(cell) {
        var row = parseInt(cell.dataset.row);
        var col = parseInt(cell.dataset.col);
        var status = cell.dataset.status;
        if (status !== 'available') return;

        var key = getCellKey(row, col);
        if (selected.has(key)) {
            selected.delete(key);
            cell.classList.remove('selected');
        } else {
            selected.add(key);
            cell.classList.add('selected');
        }
        updatePanel();
    }

    function selectRange(r1, c1, r2, c2) {
        var minR = Math.min(r1, r2), maxR = Math.max(r1, r2);
        var minC = Math.min(c1, c2), maxC = Math.max(c1, c2);
        for (var r = minR; r <= maxR; r++) {
            for (var c = minC; c <= maxC; c++) {
                var cell = grid.querySelector('.pool-cell[data-row="' + r + '"][data-col="' + c + '"]');
                if (cell && cell.dataset.status === 'available') {
                    var key = getCellKey(r, c);
                    selected.add(key);
                    cell.classList.add('selected');
                }
            }
        }
        updatePanel();
    }

    // Mouse events for drag selection
    grid.addEventListener('mousedown', function(e) {
        var cell = e.target.closest('.pool-cell');
        if (!cell || cell.dataset.status !== 'available') return;
        e.preventDefault();
        isDragging = true;
        dragStart = { row: parseInt(cell.dataset.row), col: parseInt(cell.dataset.col) };
        if (!e.shiftKey && !e.ctrlKey && !e.metaKey) {
            clearSelection(true);
        }
        toggleCell(cell);
    });

    grid.addEventListener('mouseover', function(e) {
        if (!isDragging || !dragStart) return;
        var cell = e.target.closest('.pool-cell');
        if (!cell || cell.dataset.status !== 'available') return;
        var row = parseInt(cell.dataset.row);
        var col = parseInt(cell.dataset.col);
        // Clear previous drag range, re-select from start
        clearSelection(true);
        selectRange(dragStart.row, dragStart.col, row, col);
    });

    document.addEventListener('mouseup', function() {
        isDragging = false;
        dragStart = null;
    });

    // Keyboard
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') clearSelection();
    });

    // Row/Column selection
    window.selectRow = function(rowIdx) {
        var cells = grid.querySelectorAll('.pool-cell[data-row="' + rowIdx + '"]');
        var allSelected = true;
        cells.forEach(function(c) {
            if (c.dataset.status === 'available' && !c.classList.contains('selected')) allSelected = false;
        });
        cells.forEach(function(c) {
            if (c.dataset.status !== 'available') return;
            var key = getCellKey(parseInt(c.dataset.row), parseInt(c.dataset.col));
            if (allSelected) {
                selected.delete(key);
                c.classList.remove('selected');
            } else {
                selected.add(key);
                c.classList.add('selected');
            }
        });
        updatePanel();
    };

    window.selectColumn = function(colIdx) {
        var cells = grid.querySelectorAll('.pool-cell[data-col="' + colIdx + '"]');
        var allSelected = true;
        cells.forEach(function(c) {
            if (c.dataset.status === 'available' && !c.classList.contains('selected')) allSelected = false;
        });
        cells.forEach(function(c) {
            if (c.dataset.status !== 'available') return;
            var key = getCellKey(parseInt(c.dataset.row), parseInt(c.dataset.col));
            if (allSelected) {
                selected.delete(key);
                c.classList.remove('selected');
            } else {
                selected.add(key);
                c.classList.add('selected');
            }
        });
        updatePanel();
    };

    window.clearSelection = function(silent) {
        selected.clear();
        grid.querySelectorAll('.pool-cell.selected').forEach(function(c) { c.classList.remove('selected'); });
        if (!silent) updatePanel();
    };

    function updatePanel() {
        var count = selected.size;
        document.getElementById('selCount').textContent = count;

        if (count === 0) {
            panel.classList.remove('visible');
            cellsInput.value = '[]';
            return;
        }
        panel.classList.add('visible');

        // Calculate lanes and time range
        var lanes = new Set(), minSlot = '99:99', maxSlotEnd = '00:00';
        selected.forEach(function(key) {
            var parts = key.split(':');
            var cell = grid.querySelector('.pool-cell[data-row="' + parts[0] + '"][data-col="' + parts[1] + '"]');
            if (cell) {
                lanes.add(cell.dataset.lane);
                if (cell.dataset.slot < minSlot) minSlot = cell.dataset.slot;
                if (cell.dataset.slotEnd > maxSlotEnd) maxSlotEnd = cell.dataset.slotEnd;
            }
        });

        document.getElementById('selLanes').textContent = lanes.size;
        document.getElementById('selTime').textContent = minSlot + ' — ' + maxSlotEnd;

        // Build cells payload
        var payload = [];
        selected.forEach(function(key) {
            var parts = key.split(':');
            var cell = grid.querySelector('.pool-cell[data-row="' + parts[0] + '"][data-col="' + parts[1] + '"]');
            if (cell) {
                payload.push({ lane: parseInt(cell.dataset.lane), start: cell.dataset.slot, end: cell.dataset.slotEnd });
            }
        });
        cellsInput.value = JSON.stringify(payload);
    }

    // Auto-refresh grid state every 30s
    setInterval(function() {
        fetch('/api/pool/<?= (int) $pool->id ?>/state?date=<?= e($date) ?>')
            .then(function(r) { return r.json(); })
            .then(function(data) { refreshCells(data); })
            .catch(function() {});
    }, 30000);

    function refreshCells(data) {
        var cells = data.cells || {};
        var colorMap = {available:'#10B981', booked:'#3B82F6', in_progress:'#F59E0B', maintenance:'#EF4444', scheduled:'#8B5CF6'};
        grid.querySelectorAll('.pool-cell').forEach(function(el) {
            var lane = parseInt(el.dataset.lane);
            var slot = el.dataset.slot;
            if (cells[lane] && cells[lane][slot]) {
                var newStatus = cells[lane][slot].status || 'available';
                if (el.dataset.status !== newStatus && !el.classList.contains('selected')) {
                    el.dataset.status = newStatus;
                    el.className = 'pool-cell ' + newStatus;
                }
            }
        });
    }
});
</script>
<?php $__template->endSection(); ?>
