<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>الشبكة التفاعلية — <?= e($grid->name_ar) ?><?php $__template->endSection(); ?>
<?php $__template->section('page_actions'); ?>
<a href="/facility-grids/<?= (int) $grid->id ?>/plans" class="btn btn-outline">الخطط الشهرية</a>
<a href="/facility-grids/<?= (int) $grid->id ?>/schedules" class="btn btn-outline">الجداول</a>
<?php $__template->endSection(); ?>
<?php $__template->section('content'); ?>
<?php
$rows = (int) ($grid->rows_count ?? 6);
$cols = (int) ($grid->cols_count ?? 8);
$zones = $grid->getZones();
$zoneMap = [];
foreach ($zones as $z) { $zoneMap[(int)$z['row_index'] . '_' . (int)$z['col_index']] = $z; }
?>

<style>
.pool-grid-container { position:relative; overflow-x:auto; margin-bottom:20px; }
.pool-grid { border-collapse:collapse; width:100%; user-select:none; }
.pool-grid th { background:#F1F5F9; padding:8px 4px; font-size:12px; text-align:center; border:1px solid #E2E8F0; min-width:60px; }
.pool-grid td { border:1px solid #E2E8F0; padding:0; height:50px; min-width:60px; position:relative; cursor:crosshair; transition:background 0.1s; }
.pool-grid td.cell-empty { background:#fff; }
.pool-grid td.cell-occupied { cursor:pointer; }
.pool-grid td.cell-selected { background:#BFDBFE !important; outline:2px solid #2563EB; outline-offset:-2px; }
.pool-grid td.cell-selecting { background:#DBEAFE !important; }
.pool-grid td:hover:not(.cell-occupied) { background:#F0F9FF; }
.cell-content { padding:4px; font-size:10px; line-height:1.3; height:100%; display:flex; flex-direction:column; justify-content:center; align-items:center; text-align:center; }
.lane-header { cursor:pointer; font-weight:700; color:#0D7377; }
.lane-header:hover { background:#CCFBF1 !important; }

#assign-modal { display:none; position:fixed; top:0; left:0; right:0; bottom:0; background:rgba(0,0,0,0.5); z-index:1000; align-items:center; justify-content:center; }
#assign-modal.active { display:flex; }
#assign-modal .modal-body { background:#fff; border-radius:12px; padding:25px; width:90%; max-width:500px; max-height:80vh; overflow-y:auto; }
.selection-info { background:#EFF6FF; border:1px solid #BFDBFE; border-radius:8px; padding:12px; margin-bottom:15px; font-size:13px; }
</style>

<div class="card" style="padding:20px;">
    <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:15px;">
        <div>
            <h4 style="margin:0;"><?= e($grid->name_ar) ?> — الشبكة التفاعلية</h4>
            <small style="color:#6B7280;"><?= e($grid->row_label_ar ?? 'حارة') ?> × <?= e($grid->col_label_ar ?? 'عمود') ?> | <?= $rows ?>×<?= $cols ?></small>
        </div>
        <div style="display:flex;gap:8px;">
            <button id="btn-clear-selection" class="btn btn-sm btn-outline" style="display:none;">مسح التحديد</button>
            <button id="btn-assign" class="btn btn-sm btn-primary" style="display:none;">تعيين المحدد</button>
        </div>
    </div>

    <div class="pool-grid-container">
        <table class="pool-grid" id="pool-grid">
            <thead>
                <tr>
                    <th></th>
                    <?php for ($c = 1; $c <= $cols; $c++): ?>
                    <th class="lane-header" data-col="<?= $c ?>" title="اضغط لتحديد العمود كاملاً"><?= $c ?></th>
                    <?php endfor; ?>
                </tr>
            </thead>
            <tbody>
                <?php for ($r = 1; $r <= $rows; $r++): ?>
                <tr>
                    <th class="lane-header" data-row="<?= $r ?>" title="اضغط لتحديد الحارة كاملاً"><?= $r ?></th>
                    <?php for ($c = 1; $c <= $cols; $c++):
                        $key = $r . '_' . $c;
                        $zone = $zoneMap[$key] ?? null;
                        $occupied = $zone && !empty($zone['schedule_info']);
                    ?>
                    <td class="cell-empty" data-row="<?= $r ?>" data-col="<?= $c ?>"
                        <?php if ($zone && ($zone['color'] ?? '')): ?>style="background:<?= e($zone['color']) ?>20;"<?php endif; ?>>
                        <?php if ($zone && ($zone['label'] ?? '')): ?>
                        <div class="cell-content">
                            <span style="font-weight:600;"><?= e($zone['label'] ?? '') ?></span>
                        </div>
                        <?php endif; ?>
                    </td>
                    <?php endfor; ?>
                </tr>
                <?php endfor; ?>
            </tbody>
        </table>
    </div>

    <div style="display:flex;gap:15px;font-size:12px;color:#6B7280;margin-top:10px;">
        <span>&#9632; اسحب بالماوس لتحديد خلايا متعددة</span>
        <span>&#9632; اضغط على رقم الحارة/العمود لتحديد كامل</span>
        <span>&#9632; بعد التحديد اضغط "تعيين" لإسناد مدرب/أكاديمية</span>
    </div>
</div>

<!-- Assignment Modal -->
<div id="assign-modal">
    <div class="modal-body">
        <h4 style="margin-bottom:15px;color:#0D7377;">تعيين الخلايا المحددة</h4>
        <div class="selection-info" id="selection-info"></div>

        <form id="assign-form">
            <?= csrf_field() ?>
            <input type="hidden" name="zone_selection_type" id="sel-type" value="cells">
            <input type="hidden" name="zone_selection_json" id="sel-json" value="[]">

            <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;">
                <div style="grid-column:span 2;">
                    <label class="form-label">اسم الجدول <span style="color:#DC2626;">*</span></label>
                    <input type="text" name="schedule_name" class="form-input" required placeholder="مثال: تدريب أكاديمية السباحة">
                </div>
                <div>
                    <label class="form-label">يوم الأسبوع</label>
                    <select name="day_of_week" class="form-select">
                        <option value="0">الأحد</option><option value="1">الإثنين</option><option value="2">الثلاثاء</option>
                        <option value="3">الأربعاء</option><option value="4">الخميس</option><option value="5">الجمعة</option><option value="6">السبت</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">الفترة</label>
                    <div style="display:flex;gap:5px;"><input type="time" name="start_time" class="form-input" value="07:00" style="direction:ltr;"><input type="time" name="end_time" class="form-input" value="08:00" style="direction:ltr;"></div>
                </div>
                <div>
                    <label class="form-label">المدرب</label>
                    <input type="text" name="coach_name" class="form-input" placeholder="اسم المدرب">
                    <input type="hidden" name="coach_id" value="">
                </div>
                <div>
                    <label class="form-label">الأكاديمية</label>
                    <input type="text" name="academy_name" class="form-input" placeholder="اسم الأكاديمية">
                    <input type="hidden" name="academy_id" value="">
                </div>
                <div>
                    <label class="form-label">الفئة العمرية</label>
                    <select name="age_group" class="form-select">
                        <option value="">— الكل —</option>
                        <option value="4-6">4-6 سنوات</option><option value="7-9">7-9 سنوات</option>
                        <option value="10-12">10-12 سنة</option><option value="13-15">13-15 سنة</option>
                        <option value="16-18">16-18 سنة</option><option value="adults">كبار</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">الجنس</label>
                    <select name="gender" class="form-select">
                        <option value="mixed">مختلط</option><option value="male">ذكور</option><option value="female">إناث</option>
                    </select>
                </div>
                <div>
                    <label class="form-label">أقصى عدد</label>
                    <input type="number" name="max_occupants" value="8" min="1" max="50" class="form-input" style="direction:ltr;text-align:right;">
                </div>
                <div>
                    <label class="form-label">اللون</label>
                    <input type="color" name="color" value="#3B82F6" class="form-input" style="height:38px;padding:3px;">
                </div>
                <div>
                    <label class="form-label">تاريخ البداية</label>
                    <input type="date" name="effective_from" value="<?= date('Y-m-01') ?>" class="form-input" style="direction:ltr;">
                </div>
                <div>
                    <label class="form-label">تاريخ النهاية</label>
                    <input type="date" name="effective_to" value="<?= date('Y-m-t') ?>" class="form-input" style="direction:ltr;">
                </div>
            </div>

            <div style="margin-top:20px;display:flex;gap:10px;justify-content:flex-start;">
                <button type="submit" class="btn btn-primary">حفظ التعيين</button>
                <button type="button" id="btn-close-modal" class="btn btn-outline">إلغاء</button>
            </div>
        </form>
    </div>
</div>

<script>
(function() {
    const gridId = <?= (int) $grid->id ?>;
    const rows = <?= $rows ?>;
    const cols = <?= $cols ?>;
    const grid = document.getElementById('pool-grid');
    const btnAssign = document.getElementById('btn-assign');
    const btnClear = document.getElementById('btn-clear-selection');
    const modal = document.getElementById('assign-modal');
    const selInfo = document.getElementById('selection-info');
    const form = document.getElementById('assign-form');

    let selectedCells = new Set();
    let isSelecting = false;
    let startCell = null;

    function cellKey(r, c) { return r + '_' + c; }

    function clearSelection() {
        selectedCells.clear();
        grid.querySelectorAll('td.cell-selected, td.cell-selecting').forEach(td => {
            td.classList.remove('cell-selected', 'cell-selecting');
        });
        btnAssign.style.display = 'none';
        btnClear.style.display = 'none';
    }

    function updateSelectionUI() {
        grid.querySelectorAll('td[data-row]').forEach(td => {
            const key = cellKey(td.dataset.row, td.dataset.col);
            td.classList.toggle('cell-selected', selectedCells.has(key));
        });
        const count = selectedCells.size;
        btnAssign.style.display = count > 0 ? '' : 'none';
        btnClear.style.display = count > 0 ? '' : 'none';
        btnAssign.textContent = 'تعيين (' + count + ' خلية)';
    }

    // Drag selection on cells
    grid.querySelectorAll('td[data-row]').forEach(td => {
        td.addEventListener('mousedown', function(e) {
            e.preventDefault();
            if (!e.ctrlKey && !e.metaKey) clearSelection();
            isSelecting = true;
            startCell = { r: +this.dataset.row, c: +this.dataset.col };
            selectedCells.add(cellKey(startCell.r, startCell.c));
            updateSelectionUI();
        });

        td.addEventListener('mousemove', function(e) {
            if (!isSelecting || !startCell) return;
            const endR = +this.dataset.row, endC = +this.dataset.col;
            const minR = Math.min(startCell.r, endR), maxR = Math.max(startCell.r, endR);
            const minC = Math.min(startCell.c, endC), maxC = Math.max(startCell.c, endC);

            // Clear previous selecting state
            grid.querySelectorAll('td.cell-selecting').forEach(t => t.classList.remove('cell-selecting'));

            for (let r = minR; r <= maxR; r++) {
                for (let c = minC; c <= maxC; c++) {
                    const cell = grid.querySelector('td[data-row="'+r+'"][data-col="'+c+'"]');
                    if (cell) cell.classList.add('cell-selecting');
                    selectedCells.add(cellKey(r, c));
                }
            }
            updateSelectionUI();
        });
    });

    document.addEventListener('mouseup', function() {
        if (isSelecting) {
            isSelecting = false;
            grid.querySelectorAll('td.cell-selecting').forEach(td => {
                td.classList.remove('cell-selecting');
                td.classList.add('cell-selected');
            });
            updateSelectionUI();
        }
    });

    // Lane/column header selection
    grid.querySelectorAll('th.lane-header[data-row]').forEach(th => {
        th.addEventListener('click', function() {
            clearSelection();
            const row = +this.dataset.row;
            for (let c = 1; c <= cols; c++) selectedCells.add(cellKey(row, c));
            updateSelectionUI();
        });
    });

    grid.querySelectorAll('th.lane-header[data-col]').forEach(th => {
        th.addEventListener('click', function() {
            clearSelection();
            const col = +this.dataset.col;
            for (let r = 1; r <= rows; r++) selectedCells.add(cellKey(r, col));
            updateSelectionUI();
        });
    });

    btnClear.addEventListener('click', clearSelection);

    btnAssign.addEventListener('click', function() {
        if (selectedCells.size === 0) return;

        // Determine selection type
        const cells = Array.from(selectedCells).map(k => { const [r,c] = k.split('_'); return {row:+r, col:+c}; });
        const uniqueRows = [...new Set(cells.map(c=>c.row))];
        const uniqueCols = [...new Set(cells.map(c=>c.col))];

        let selType = 'cells';
        if (uniqueRows.length === 1 && uniqueCols.length === cols) selType = 'row';
        else if (uniqueCols.length === 1 && uniqueRows.length === rows) selType = 'column';
        else if (cells.length === rows * cols) selType = 'all';

        document.getElementById('sel-type').value = selType;
        document.getElementById('sel-json').value = JSON.stringify(cells);

        selInfo.innerHTML = '<strong>' + selectedCells.size + ' خلية محددة</strong> — نوع التحديد: ' +
            ({cells:'خلايا', row:'حارة كاملة', column:'عمود كامل', all:'الكل'}[selType] || selType);

        modal.classList.add('active');
    });

    document.getElementById('btn-close-modal').addEventListener('click', function() {
        modal.classList.remove('active');
    });

    modal.addEventListener('click', function(e) {
        if (e.target === modal) modal.classList.remove('active');
    });

    form.addEventListener('submit', function(e) {
        e.preventDefault();
        const formData = new FormData(form);
        fetch('/facility-grids/' + gridId + '/schedules', {
            method: 'POST',
            body: formData,
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                modal.classList.remove('active');
                clearSelection();
                location.reload();
            } else {
                alert(data.message || 'حدث خطأ');
            }
        })
        .catch(() => alert('حدث خطأ في الاتصال'));
    });
})();
</script>
<?php $__template->endSection(); ?>
