<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>المراية: <?= e($grid['name_ar']) ?><?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/mirror" 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
$rows = (int) $grid['rows_count'];
$cols = (int) $grid['cols_count'];
$gridId = (int) $grid['id'];

$boxMap = [];
foreach ($grid['boxes'] as $box) {
    $key = $box['row_index'] . '_' . $box['col_index'];
    $boxMap[$key] = $box;
}

$genderLabels = ['male' => 'أولاد', 'female' => 'بنات', 'mixed' => 'مختلط'];
$genderColors = ['male' => '#2563EB', 'female' => '#EC4899', 'mixed' => '#6B7280'];
?>

<!-- Grid Header -->
<div class="card" style="margin-bottom:15px;padding:15px 20px;display:flex;align-items:center;justify-content:space-between;">
    <div style="display:flex;align-items:center;gap:10px;">
        <i data-lucide="grid-3x3" style="width:20px;height:20px;color:#0D7377;"></i>
        <div>
            <span style="font-size:15px;font-weight:600;color:#1A1A2E;"><?= e($grid['name_ar']) ?></span>
            <span style="font-size:12px;color:#6B7280;margin-right:8px;"><?= e($grid['facility_name'] ?? '') ?></span>
        </div>
    </div>
    <div style="font-size:12px;color:#6B7280;">
        <?= $rows ?> × <?= $cols ?> = <?= $rows * $cols ?> خانة
    </div>
</div>

<!-- Interactive Grid -->
<div style="display:grid;grid-template-columns:repeat(<?= $cols ?>, 1fr);gap:10px;margin-bottom:20px;">
    <?php for ($r = 0; $r < $rows; $r++): ?>
        <?php for ($c = 0; $c < $cols; $c++):
            $key = $r . '_' . $c;
            $box = $boxMap[$key] ?? null;
            $boxId = $box ? (int) $box['id'] : 0;
            $traineeCount = $box ? (int) ($box['trainee_count'] ?? 0) : 0;
            $maxTrainees = $box ? (int) ($box['max_trainees'] ?? 5) : 5;
            $isFull = $traineeCount >= $maxTrainees;
            $gender = $box['gender'] ?? 'mixed';
            $gc = $genderColors[$gender] ?? '#6B7280';
            $coachDisplay = '';
            if (!empty($box['coach_full_name'])) $coachDisplay = $box['coach_full_name'];
            elseif (!empty($box['coach_name'])) $coachDisplay = $box['coach_name'];
            $academyDisplay = $box['academy_name'] ?? '';
        ?>
        <div class="mirror-box" data-box-id="<?= $boxId ?>" onclick="openBoxModal(<?= $boxId ?>)"
             style="border:2px solid <?= $isFull ? '#EF4444' : ($traineeCount > 0 ? '#0D7377' : '#E5E7EB') ?>;
                    border-radius:12px;padding:12px;min-height:140px;cursor:pointer;
                    background:<?= $isFull ? '#FEF2F2' : ($traineeCount > 0 ? '#F0FDFA' : 'white') ?>;
                    transition:all 0.2s;position:relative;">
            <!-- Box label/position -->
            <div style="position:absolute;top:4px;left:4px;font-size:10px;color:#9CA3AF;direction:ltr;">
                <?= $r + 1 ?>,<?= $c + 1 ?>
            </div>

            <?php if ($box && ($coachDisplay || $academyDisplay || $traineeCount > 0)): ?>
                <!-- Coach/Academy -->
                <?php if ($coachDisplay): ?>
                <div style="font-size:11px;font-weight:600;color:#0D7377;margin-bottom:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" title="<?= e($coachDisplay) ?>">
                    <i data-lucide="user" style="width:11px;height:11px;vertical-align:middle;margin-left:2px;"></i>
                    <?= e($coachDisplay) ?>
                </div>
                <?php endif; ?>
                <?php if ($academyDisplay): ?>
                <div style="font-size:10px;color:#6B7280;margin-bottom:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;">
                    <?= e($academyDisplay) ?>
                </div>
                <?php endif; ?>

                <!-- Age + Gender -->
                <?php if (!empty($box['age_group']) || $gender !== 'mixed'): ?>
                <div style="display:flex;gap:4px;margin-bottom:6px;flex-wrap:wrap;">
                    <?php if (!empty($box['age_group'])): ?>
                    <span style="font-size:9px;padding:1px 5px;border-radius:4px;background:#F3F4F6;color:#374151;"><?= e($box['age_group']) ?></span>
                    <?php endif; ?>
                    <span style="font-size:9px;padding:1px 5px;border-radius:4px;background:<?= $gc ?>15;color:<?= $gc ?>;"><?= $genderLabels[$gender] ?? '' ?></span>
                </div>
                <?php endif; ?>

                <!-- Trainees -->
                <div style="display:flex;flex-direction:column;gap:2px;">
                    <?php if (!empty($box['trainees'])):
                        foreach ($box['trainees'] as $t):
                            $tName = $t['player_full_name'] ?? $t['trainee_name'] ?? '';
                    ?>
                    <div style="font-size:10px;color:#374151;background:white;border:1px solid #E5E7EB;border-radius:4px;padding:2px 5px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;" title="<?= e($tName) ?>">
                        <?= e($tName) ?>
                    </div>
                    <?php endforeach; endif; ?>
                </div>

                <!-- Count -->
                <div style="position:absolute;bottom:4px;left:6px;font-size:10px;font-weight:700;color:<?= $isFull ? '#DC2626' : '#059669' ?>;direction:ltr;">
                    <?= $traineeCount ?>/<?= $maxTrainees ?>
                </div>
            <?php else: ?>
                <div style="display:flex;align-items:center;justify-content:center;height:100%;opacity:0.4;">
                    <i data-lucide="plus" style="width:24px;height:24px;color:#9CA3AF;"></i>
                </div>
            <?php endif; ?>
        </div>
        <?php endfor; ?>
    <?php endfor; ?>
</div>

<!-- Box Edit Modal -->
<div id="boxModal" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,0.5);z-index:1000;align-items:center;justify-content:center;">
    <div style="background:white;border-radius:16px;width:500px;max-width:95%;max-height:90vh;overflow-y:auto;box-shadow:0 25px 50px rgba(0,0,0,0.25);">
        <div style="padding:20px;border-bottom:1px solid #E5E7EB;display:flex;justify-content:space-between;align-items:center;">
            <h3 style="margin:0;font-size:16px;color:#0D7377;">تعديل الخانة</h3>
            <button onclick="closeBoxModal()" style="background:none;border:none;cursor:pointer;padding:5px;">
                <i data-lucide="x" style="width:20px;height:20px;color:#6B7280;"></i>
            </button>
        </div>

        <!-- Box Settings Form -->
        <form id="boxForm" method="POST" action="">
            <?= csrf_field() ?>
            <div style="padding:20px;">
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:15px;">
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">المدرب</label>
                        <select name="coach_id" class="form-select" id="modalCoachId">
                            <option value="0">— بدون —</option>
                            <?php foreach ($coaches as $coach): ?>
                            <option value="<?= (int) $coach['id'] ?>"><?= e($coach['full_name_ar']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">أو اسم يدوي</label>
                        <input type="text" name="coach_name" id="modalCoachName" class="form-input" placeholder="اسم المدرب">
                    </div>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:15px;">
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">الأكاديمية</label>
                        <select name="academy_id" class="form-select" id="modalAcademyId">
                            <option value="0">— بدون —</option>
                            <?php foreach ($academies as $ac): ?>
                            <option value="<?= (int) $ac['id'] ?>"><?= e($ac['name_ar']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">الفئة العمرية</label>
                        <input type="text" name="age_group" id="modalAgeGroup" class="form-input" placeholder="مثال: 4-6" style="direction:ltr;text-align:left;">
                    </div>
                </div>
                <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-bottom:15px;">
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">الجنس</label>
                        <select name="gender" class="form-select" id="modalGender">
                            <option value="mixed">مختلط</option>
                            <option value="male">أولاد</option>
                            <option value="female">بنات</option>
                        </select>
                    </div>
                    <div class="form-group" style="margin:0;">
                        <label class="form-label" style="font-size:12px;">أقصى عدد متدربين</label>
                        <input type="number" name="max_trainees" id="modalMaxTrainees" class="form-input" value="5" min="1" max="10" style="direction:ltr;text-align:center;">
                    </div>
                </div>
                <button type="submit" class="btn btn-primary" style="width:100%;">
                    <i data-lucide="save" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> حفظ إعدادات الخانة
                </button>
            </div>
        </form>

        <div style="border-top:1px solid #E5E7EB;padding:20px;">
            <h4 style="margin:0 0 10px;font-size:14px;color:#374151;">إضافة متدرب</h4>
            <form id="traineeForm" method="POST" action="" style="display:flex;gap:8px;flex-wrap:wrap;">
                <?= csrf_field() ?>
                <select name="player_id" class="form-select" style="flex:1;min-width:150px;">
                    <option value="0">— اختر لاعب —</option>
                    <?php foreach ($players as $p): ?>
                    <option value="<?= (int) $p['id'] ?>"><?= e($p['full_name_ar']) ?></option>
                    <?php endforeach; ?>
                </select>
                <input type="text" name="trainee_name" class="form-input" placeholder="أو اكتب اسم يدوي" style="flex:1;min-width:150px;">
                <button type="submit" class="btn btn-primary" style="white-space:nowrap;">
                    <i data-lucide="user-plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> إضافة
                </button>
            </form>
        </div>

        <!-- Current Trainees in Box -->
        <div id="modalTrainees" style="border-top:1px solid #E5E7EB;padding:15px 20px;display:none;">
            <h4 style="margin:0 0 10px;font-size:14px;color:#374151;">المتدربون الحاليون</h4>
            <div id="traineeList"></div>
        </div>
    </div>
</div>

<style>
.mirror-box:hover { transform:scale(1.02); box-shadow:0 4px 12px rgba(0,0,0,0.08); }
</style>

<script>
var gridId = <?= $gridId ?>;
var boxesData = <?= json_encode($grid['boxes'], JSON_UNESCAPED_UNICODE) ?>;

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

function openBoxModal(boxId) {
    if (!boxId) return;
    var box = boxesData.find(b => parseInt(b.id) === boxId);
    if (!box) return;

    document.getElementById('boxForm').action = '/mirror/' + gridId + '/box/' + boxId;
    document.getElementById('traineeForm').action = '/mirror/' + gridId + '/box/' + boxId + '/trainee';

    document.getElementById('modalCoachId').value = box.coach_id || '0';
    document.getElementById('modalCoachName').value = box.coach_name || '';
    document.getElementById('modalAcademyId').value = box.academy_id || '0';
    document.getElementById('modalAgeGroup').value = box.age_group || '';
    document.getElementById('modalGender').value = box.gender || 'mixed';
    document.getElementById('modalMaxTrainees').value = box.max_trainees || 5;

    // Render trainees
    var traineeDiv = document.getElementById('modalTrainees');
    var traineeList = document.getElementById('traineeList');
    traineeList.innerHTML = '';

    if (box.trainees && box.trainees.length > 0) {
        traineeDiv.style.display = 'block';
        box.trainees.forEach(function(t) {
            var name = t.player_full_name || t.trainee_name || '';
            var row = document.createElement('div');
            row.style.cssText = 'display:flex;justify-content:space-between;align-items:center;padding:6px 8px;background:#F9FAFB;border-radius:6px;margin-bottom:4px;font-size:13px;';
            row.innerHTML = '<span>' + escapeHtml(name) + '</span>' +
                '<div style="display:flex;gap:4px;">' +
                '<form method="POST" action="/mirror/' + gridId + '/trainee/' + t.id + '/remove" style="margin:0;">' +
                '<input type="hidden" name="_token" value="' + getCsrf() + '">' +
                '<button type="submit" style="background:none;border:none;cursor:pointer;color:#DC2626;font-size:11px;padding:2px 6px;" title="إزالة">✕</button>' +
                '</form>' +
                '</div>';
            traineeList.appendChild(row);
        });
    } else {
        traineeDiv.style.display = 'none';
    }

    document.getElementById('boxModal').style.display = 'flex';
}

function closeBoxModal() {
    document.getElementById('boxModal').style.display = 'none';
}

function getCsrf() {
    var el = document.querySelector('input[name="_token"]');
    return el ? el.value : '';
}

function escapeHtml(str) {
    var div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}

document.getElementById('boxModal').addEventListener('click', function(e) {
    if (e.target === this) closeBoxModal();
});
</script>

<?php $__template->endSection(); ?>
