<?php $__template->layout('Layout.main'); ?>
<?php $__template->section('title'); ?>تعيين لاعب في مجموعة سباحة<?php $__template->endSection(); ?>

<?php $__template->section('page_actions'); ?>
<a href="/sa/swimming" 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 if ($mode === 'list'): ?>
<!-- Unassigned Players List -->
<div class="card">
    <div style="padding:14px 16px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;justify-content:space-between;">
        <span style="font-weight:700;font-size:15px;">اللاعبين المتاحين للتعيين (<?= count($players) ?>)</span>
        <a href="/sa/swimming/register" class="btn btn-primary" style="font-size:12px;"><i data-lucide="user-plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i>تسجيل جديد</a>
    </div>
    <?php if (empty($players)): ?>
    <div style="padding:40px;text-align:center;">
        <div style="width:64px;height:64px;border-radius:50%;background:#F3F4F6;display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
            <i data-lucide="users" style="width:28px;height:28px;color:#9CA3AF;"></i>
        </div>
        <p style="font-size:14px;color:#6B7280;margin-bottom:12px;">لا يوجد لاعبين بانتظار التعيين في مجموعة سباحة</p>
        <a href="/sa/swimming/register" class="btn btn-primary">تسجيل لاعب جديد</a>
    </div>
    <?php else: ?>
    <div style="overflow-x:auto;">
        <table style="width:100%;border-collapse:collapse;font-size:13px;">
            <thead>
                <tr style="background:#F9FAFB;">
                    <th style="padding:10px 14px;text-align:right;font-weight:600;">اللاعب</th>
                    <th style="padding:10px 14px;text-align:center;font-weight:600;">العمر</th>
                    <th style="padding:10px 14px;text-align:center;font-weight:600;">النوع</th>
                    <th style="padding:10px 14px;text-align:center;font-weight:600;">الحالة الطبية</th>
                    <th style="padding:10px 14px;text-align:center;font-weight:600;">تاريخ التسجيل</th>
                    <th style="padding:10px 14px;text-align:center;font-weight:600;">إجراء</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($players as $pl):
                    $age = $pl['date_of_birth'] ? (int) date_diff(date_create($pl['date_of_birth']), date_create())->y : null;
                    $medicalLabels = ['fit' => ['لائق','#059669','#ECFDF5'], 'pending' => ['بانتظار','#D97706','#FEF3C7'], 'conditional' => ['مشروط','#2563EB','#EFF6FF']];
                    $ml = $medicalLabels[$pl['medical_status']] ?? [$pl['medical_status'],'#6B7280','#F3F4F6'];
                ?>
                <tr style="border-bottom:1px solid #F3F4F6;">
                    <td style="padding:10px 14px;">
                        <div style="display:flex;align-items:center;gap:8px;">
                            <div style="width:32px;height:32px;border-radius:50%;background:#F3F4F6;overflow:hidden;flex-shrink:0;">
                                <?php if ($pl['photo_path']): ?>
                                <img src="/<?= e($pl['photo_path']) ?>" style="width:100%;height:100%;object-fit:cover;" alt="">
                                <?php else: ?>
                                <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;"><i data-lucide="user" style="width:14px;height:14px;color:#9CA3AF;"></i></div>
                                <?php endif; ?>
                            </div>
                            <span style="font-weight:600;"><?= e($pl['full_name_ar']) ?></span>
                        </div>
                    </td>
                    <td style="padding:10px 14px;text-align:center;"><?= $age !== null ? $age . ' سنة' : '—' ?></td>
                    <td style="padding:10px 14px;text-align:center;">
                        <span style="font-size:11px;padding:2px 8px;border-radius:4px;background:<?= $pl['player_type'] === 'member' ? '#ECFDF5' : '#FEF3C7' ?>;color:<?= $pl['player_type'] === 'member' ? '#059669' : '#D97706' ?>;">
                            <?= $pl['player_type'] === 'member' ? 'عضو' : 'غير عضو' ?>
                        </span>
                    </td>
                    <td style="padding:10px 14px;text-align:center;">
                        <span style="font-size:11px;padding:2px 8px;border-radius:4px;background:<?= $ml[2] ?>;color:<?= $ml[1] ?>;font-weight:600;"><?= $ml[0] ?></span>
                    </td>
                    <td style="padding:10px 14px;text-align:center;color:#6B7280;font-size:12px;direction:ltr;"><?= e(substr($pl['created_at'], 0, 10)) ?></td>
                    <td style="padding:10px 14px;text-align:center;">
                        <a href="/sa/swimming/assign/<?= (int) $pl['id'] ?>" class="btn btn-primary" style="font-size:11px;padding:4px 12px;">تعيين</a>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>
</div>

<?php elseif ($mode === 'assign'): ?>
<!-- Assignment View for Specific Player -->

<?php
$done = isset($_GET['done']) && $_GET['done'] === '1';
if ($done): ?>
<!-- Success State -->
<div class="card" style="text-align:center;padding:40px;">
    <div style="width:64px;height:64px;border-radius:50%;background:#ECFDF5;display:flex;align-items:center;justify-content:center;margin:0 auto 16px;">
        <i data-lucide="check-circle" style="width:32px;height:32px;color:#059669;"></i>
    </div>
    <h3 style="font-size:18px;font-weight:700;color:#1A1A2E;margin-bottom:8px;">تم تعيين اللاعب بنجاح</h3>
    <p style="font-size:13px;color:#6B7280;margin-bottom:4px;">تم إرسال طلب الدفع إلى خزينة الأنشطة الرياضية</p>
    <p style="font-size:12px;color:#9CA3AF;margin-bottom:20px;">سيتم تفعيل اللاعب تلقائياً بمجرد تأكيد الدفع</p>
    <div style="display:flex;gap:10px;justify-content:center;">
        <a href="/sa/swimming" class="btn btn-primary">لوحة التحكم</a>
        <a href="/sa/swimming/register" class="btn btn-outline">تسجيل لاعب آخر</a>
        <a href="/sa/swimming/assign" class="btn btn-outline">تعيين آخر</a>
    </div>
</div>
<?php else: ?>

<!-- Player Info -->
<div class="card" style="margin-bottom:16px;">
    <div style="padding:14px 16px;display:flex;align-items:center;gap:12px;">
        <div style="width:48px;height:48px;border-radius:8px;overflow:hidden;background:#F3F4F6;flex-shrink:0;">
            <?php if (!empty($player['photo_path'])): ?>
            <img src="/<?= e($player['photo_path']) ?>" style="width:100%;height:100%;object-fit:cover;" alt="">
            <?php else: ?>
            <div style="width:100%;height:100%;display:flex;align-items:center;justify-content:center;color:#9CA3AF;"><i data-lucide="user" style="width:20px;height:20px;"></i></div>
            <?php endif; ?>
        </div>
        <div style="flex:1;">
            <div style="font-size:15px;font-weight:700;color:#1A1A2E;"><?= e($player['full_name_ar']) ?></div>
            <div style="font-size:12px;color:#6B7280;margin-top:2px;display:flex;align-items:center;gap:6px;flex-wrap:wrap;">
                <?php if ($playerAge !== null): ?><span><?= $playerAge ?> سنة</span><?php endif; ?>
                <?php if (($player['player_type'] ?? '') === 'member'): ?>
                <span style="background:#ECFDF5;color:#059669;padding:1px 8px;border-radius:10px;font-size:11px;font-weight:600;">عضو</span>
                <?php else: ?>
                <span style="background:#FEF2F2;color:#DC2626;padding:1px 8px;border-radius:10px;font-size:11px;font-weight:600;">غير عضو</span>
                <?php endif; ?>
                <span>• <?= $player['medical_status'] === 'fit' ? 'لائق طبياً' : ($player['medical_status'] === 'pending' ? 'بانتظار الموافقة' : $player['medical_status']) ?></span>
            </div>
        </div>
    </div>
</div>

<!-- Discipline Filter -->
<?php if (!empty($disciplines)): ?>
<div class="card" style="margin-bottom:16px;">
    <div style="padding:14px 16px;display:flex;align-items:center;gap:12px;">
        <label style="font-size:13px;font-weight:700;white-space:nowrap;"><i data-lucide="filter" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i>النشاط الرياضي:</label>
        <select id="disciplineFilter" onchange="filterByDiscipline(this.value)" style="flex:1;padding:8px 12px;border:1px solid #D1D5DB;border-radius:8px;font-size:13px;">
            <?php foreach ($disciplines as $d): ?>
            <option value="<?= (int) $d['id'] ?>" <?= (int) $d['id'] === ($selectedDiscipline ?? 0) ? 'selected' : '' ?>><?= e($d['name_ar']) ?></option>
            <?php endforeach; ?>
        </select>
    </div>
</div>
<script>
function filterByDiscipline(id) {
    var url = new URL(window.location.href);
    url.searchParams.set('discipline_id', id);
    window.location.href = url.toString();
}
</script>
<?php endif; ?>

<!-- Groups Selection -->
<div class="card">
    <div style="padding:14px 16px;border-bottom:1px solid #E5E7EB;">
        <span style="font-weight:700;font-size:14px;"><i data-lucide="users" style="width:16px;height:16px;vertical-align:middle;margin-left:6px;"></i>اختر المجموعة</span>
    </div>
    <?php if (empty($groups)): ?>
    <div style="padding:30px;text-align:center;color:#9CA3AF;font-size:13px;">لا توجد مجموعات نشطة لهذا النشاط الرياضي</div>
    <?php else: ?>
    <div style="padding:16px;">
        <?php
        $groupedByProgram = [];
        foreach ($groups as $g) {
            $groupedByProgram[$g['program_name']][] = $g;
        }
        ?>
        <?php foreach ($groupedByProgram as $progName => $progGroups): ?>
        <div style="margin-bottom:20px;">
            <div style="font-size:13px;font-weight:700;color:#374151;margin-bottom:10px;padding-bottom:6px;border-bottom:1px solid #E5E7EB;"><?= e($progName) ?></div>
            <div style="display:grid;grid-template-columns:repeat(auto-fill, minmax(280px, 1fr));gap:10px;">
                <?php foreach ($progGroups as $g):
                    $capacity = (int) ($g['max_capacity'] ?? 0);
                    $current = (int) ($g['current_count'] ?? 0);
                    $isFull = $capacity > 0 && $current >= $capacity;
                    $pct = $capacity > 0 ? round(($current / $capacity) * 100) : 0;
                    $barColor = $isFull ? '#DC2626' : ($pct >= 70 ? '#F59E0B' : '#059669');

                    $ageOk = true;
                    if ($playerAge !== null) {
                        if (!empty($g['min_age']) && $playerAge < (int) $g['min_age']) $ageOk = false;
                        if (!empty($g['max_age']) && $playerAge > (int) $g['max_age']) $ageOk = false;
                        if (!empty($g['age_from']) && $playerAge < (int) $g['age_from']) $ageOk = false;
                        if (!empty($g['age_to']) && $playerAge > (int) $g['age_to']) $ageOk = false;
                    }

                    $isMember = ($player['player_type'] ?? '') === 'member';
                    $feeMember = (float) $g['monthly_fee_member'];
                    $feeNonMember = (float) $g['monthly_fee_nonmember'];
                    $fee = $isMember ? $feeMember : $feeNonMember;
                ?>
                <div class="group-card" data-group-id="<?= (int) $g['id'] ?>" data-fee="<?= $fee ?>"
                     style="border:2px solid #E5E7EB;border-radius:8px;padding:12px;cursor:<?= ($isFull || !$ageOk) ? 'not-allowed' : 'pointer' ?>;opacity:<?= ($isFull || !$ageOk) ? '0.5' : '1' ?>;transition:border-color 0.2s;"
                     <?php if (!$isFull && $ageOk): ?>onclick="selectGroup(<?= (int) $g['id'] ?>, <?= $fee ?>)"<?php endif; ?>>
                    <div style="display:flex;justify-content:space-between;align-items:flex-start;margin-bottom:6px;">
                        <span style="font-size:13px;font-weight:700;color:#1A1A2E;"><?= e($g['name_ar']) ?></span>
                        <?php if ($isFull): ?>
                        <span style="font-size:10px;background:#FEF2F2;color:#DC2626;padding:2px 6px;border-radius:4px;">ممتلئة</span>
                        <?php elseif (!$ageOk): ?>
                        <span style="font-size:10px;background:#FEF2F2;color:#DC2626;padding:2px 6px;border-radius:4px;">عمر غير مناسب</span>
                        <?php endif; ?>
                    </div>
                    <?php if ($g['coach_name']): ?>
                    <div style="font-size:11px;color:#6B7280;margin-bottom:4px;"><i data-lucide="user" style="width:11px;height:11px;vertical-align:middle;margin-left:4px;"></i><?= e($g['coach_name']) ?></div>
                    <?php endif; ?>
                    <div style="display:flex;align-items:center;gap:6px;margin-bottom:6px;">
                        <div style="flex:1;height:5px;background:#E5E7EB;border-radius:3px;overflow:hidden;">
                            <div style="height:100%;width:<?= $pct ?>%;background:<?= $barColor ?>;border-radius:3px;"></div>
                        </div>
                        <span style="font-size:10px;color:#6B7280;"><?= $current ?>/<?= $capacity ?></span>
                    </div>
                    <div style="font-size:11px;margin-top:4px;">
                        <?php if ($isMember): ?>
                        <span style="font-weight:700;color:#059669;background:#ECFDF5;padding:2px 6px;border-radius:4px;">عضو: <?= number_format($feeMember) ?> ج.م</span>
                        <span style="color:#9CA3AF;margin-right:6px;text-decoration:line-through;">غير عضو: <?= number_format($feeNonMember) ?> ج.م</span>
                        <?php else: ?>
                        <span style="font-weight:700;color:#DC2626;background:#FEF2F2;padding:2px 6px;border-radius:4px;">غير عضو: <?= number_format($feeNonMember) ?> ج.م</span>
                        <span style="color:#9CA3AF;margin-right:6px;text-decoration:line-through;">عضو: <?= number_format($feeMember) ?> ج.م</span>
                        <?php endif; ?>
                    </div>
                </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>
    </div>

    <!-- Confirm Assignment -->
    <div id="assignConfirm" style="display:none;padding:16px;border-top:1px solid #E5E7EB;background:#F9FAFB;">
        <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;">
            <div>
                <span style="font-size:13px;font-weight:700;color:#1A1A2E;">المجموعة المختارة: </span>
                <span id="selectedGroupName" style="font-size:13px;color:#2563EB;font-weight:600;"></span>
            </div>
            <div style="text-align:left;">
                <div style="font-size:14px;font-weight:700;color:#059669;">
                    <span id="selectedFee">0</span> ج.م
                </div>
                <div style="font-size:11px;color:#6B7280;" id="selectedFeeType">
                    (<?= $isMember ? 'سعر الأعضاء' : 'سعر غير الأعضاء' ?>)
                </div>
            </div>
        </div>
        <button type="button" id="confirmAssignBtn" class="btn btn-primary" style="width:100%;padding:10px;font-size:14px;" onclick="confirmAssignment()">
            <i data-lucide="check" style="width:15px;height:15px;vertical-align:middle;margin-left:6px;"></i>تأكيد التعيين وإرسال للخزينة
        </button>
        <div id="assignError" style="display:none;margin-top:10px;padding:8px 12px;background:#FEF2F2;color:#DC2626;border-radius:6px;font-size:12px;"></div>
    </div>
    <?php endif; ?>
</div>

<script>
let selectedGroupId = null;

function selectGroup(groupId, fee) {
    selectedGroupId = groupId;
    document.querySelectorAll('.group-card').forEach(c => c.style.borderColor = '#E5E7EB');
    const card = document.querySelector('[data-group-id="' + groupId + '"]');
    if (card) card.style.borderColor = '#2563EB';

    document.getElementById('selectedGroupName').textContent = card.querySelector('span').textContent;
    document.getElementById('selectedFee').textContent = fee.toLocaleString();
    document.getElementById('assignConfirm').style.display = 'block';
}

function confirmAssignment() {
    if (!selectedGroupId) return;
    const btn = document.getElementById('confirmAssignBtn');
    const errDiv = document.getElementById('assignError');
    errDiv.style.display = 'none';
    btn.disabled = true;
    btn.textContent = 'جاري التعيين...';

    const csrfToken = document.querySelector('meta[name="csrf-token"]') ? document.querySelector('meta[name="csrf-token"]').content : '';

    fetch('/sa/swimming/assign/<?= (int) ($playerId ?? 0) ?>/group', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ group_id: selectedGroupId, _csrf_token: csrfToken })
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) {
            window.location.href = data.redirect || window.location.href + '?done=1';
        } else {
            errDiv.textContent = data.error || 'حدث خطأ';
            errDiv.style.display = 'block';
            btn.disabled = false;
            btn.textContent = 'تأكيد التعيين وإرسال للخزينة';
        }
    })
    .catch(() => {
        errDiv.textContent = 'فشل الاتصال بالسيرفر';
        errDiv.style.display = 'block';
        btn.disabled = false;
        btn.textContent = 'تأكيد التعيين وإرسال للخزينة';
    });
}
</script>

<?php endif; ?>
<?php endif; ?>

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