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

<?php $__template->section('page_actions'); ?>
<?php if (can('sa.group.manage')): ?>
<a href="/sa/groups/<?= (int) $group['id'] ?>/edit" class="btn btn-primary" style="margin-left:8px;"><i data-lucide="edit-3" style="width:15px;height:15px;vertical-align:middle;margin-left:4px;"></i> تعديل</a>
<?php endif; ?>
<a href="/sa/groups" 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
$dayNames = ['الأحد', 'الاثنين', 'الثلاثاء', 'الأربعاء', 'الخميس', 'الجمعة', 'السبت'];
$statusColors = ['active' => '#059669', 'paused' => '#D97706', 'completed' => '#6B7280', 'cancelled' => '#DC2626'];
$statusBgs = ['active' => '#ECFDF5', 'paused' => '#FEF3C7', 'completed' => '#F3F4F6', 'cancelled' => '#FEE2E2'];
$st = $group['status'] ?? 'active';
?>

<!-- Group Details -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;">
        <h3 style="margin:0;color:#0D7377;font-size:15px;">بيانات المجموعة</h3>
    </div>
    <div style="padding:20px;">
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr;gap:20px;">
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">الكود</div>
                <div style="font-weight:600;"><code style="background:#F3F4F6;padding:2px 8px;border-radius:4px;"><?= e($group['code']) ?></code></div>
            </div>
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">البرنامج</div>
                <div style="font-weight:600;"><?= e($group['program_name'] ?? '—') ?></div>
            </div>
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">المدرب</div>
                <div style="font-weight:600;"><?= e($group['coach_name'] ?? '—') ?></div>
            </div>
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">الحالة</div>
                <div>
                    <span style="background:<?= $statusBgs[$st] ?? '#F3F4F6' ?>;color:<?= $statusColors[$st] ?? '#6B7280' ?>;padding:3px 10px;border-radius:10px;font-size:12px;font-weight:600;">
                        <?= e($statuses[$st] ?? $st) ?>
                    </span>
                </div>
            </div>
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">السعة</div>
                <div style="font-weight:600;">
                    <span style="color:<?= (int)$group['current_count'] >= (int)$group['max_capacity'] ? '#DC2626' : '#059669' ?>;"><?= (int) $group['current_count'] ?></span>
                    / <?= (int) $group['max_capacity'] ?>
                    (أدنى: <?= (int) ($group['min_capacity'] ?? 0) ?>)
                </div>
            </div>
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">رسوم الأعضاء</div>
                <div style="font-weight:600;"><?= money((float) ($group['monthly_fee_member'] ?? 0)) ?></div>
            </div>
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">رسوم غير الأعضاء</div>
                <div style="font-weight:600;"><?= money((float) ($group['monthly_fee_nonmember'] ?? 0)) ?></div>
            </div>
            <div>
                <div style="font-size:12px;color:#6B7280;margin-bottom:4px;">الموسم</div>
                <div style="font-weight:600;">
                    <?php if (!empty($group['season_start'])): ?>
                    <?= e($group['season_start']) ?> — <?= e($group['season_end'] ?? '?') ?>
                    <?php else: ?>
                    —
                    <?php endif; ?>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Enrolled Players -->
<div class="card" style="margin-bottom:20px;">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;justify-content:space-between;">
        <h3 style="margin:0;color:#0D7377;font-size:15px;">اللاعبون المسجلون (<?= count($players) ?>)</h3>
    </div>

    <!-- Enroll Form -->
    <?php if ((int) $group['current_count'] < (int) $group['max_capacity'] && can('sa.group.enroll')): ?>
    <div style="padding:15px 20px;background:#F9FAFB;border-bottom:1px solid #E5E7EB;">
        <form method="POST" action="/sa/groups/<?= (int) $group['id'] ?>/enroll" style="display:flex;gap:10px;align-items:end;" id="enrollForm">
            <?= csrf_field() ?>
            <div style="flex:1;">
                <label class="form-label" style="font-size:12px;">تسجيل لاعب جديد</label>
                <select name="player_id" class="form-select" required id="enrollPlayerSelect"
                        data-searchable="true"
                        data-search-url="/api/sa/players/search?exclude_group=<?= (int) $group['id'] ?>"
                        data-search-min="2"
                        data-placeholder="ابحث بالاسم أو الرقم القومي أو المسلسل...">
                    <option value="">ابحث بالاسم أو الرقم القومي...</option>
                </select>
            </div>
            <button type="submit" class="btn btn-primary" style="padding:8px 20px;">
                <i data-lucide="user-plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> تسجيل
            </button>
        </form>
    </div>
    <?php endif; ?>

    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>الكود</th>
                    <th>الاسم</th>
                    <th>الهاتف</th>
                    <th>المستحقات</th>
                    <th>تاريخ التسجيل</th>
                    <th>إجراءات</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($players)): ?>
                <?php foreach ($players as $pl): ?>
                <tr<?= ($pl['status'] ?? '') === 'pending_payment' ? ' style="background:#FEF3C7;"' : '' ?>>
                    <td><code style="font-size:11px;background:#F3F4F6;padding:2px 6px;border-radius:4px;"><?= e($pl['player_code'] ?? '') ?></code></td>
                    <td style="font-weight:600;">
                        <a href="/sa/players/<?= (int) $pl['player_id'] ?>" style="color:inherit;text-decoration:none;"><?= e($pl['player_name']) ?></a>
                        <?php if (($pl['status'] ?? '') === 'pending_payment'): ?>
                        <span style="padding:2px 6px;border-radius:8px;font-size:10px;font-weight:700;background:#FEF3C7;color:#D97706;margin-right:5px;">في انتظار الدفع</span>
                        <?php endif; ?>
                    </td>
                    <td style="direction:ltr;text-align:right;"><?= e($pl['phone'] ?? '—') ?></td>
                    <td>
                        <?php if (($pl['status'] ?? '') === 'pending_payment'): ?>
                        <span style="padding:3px 8px;border-radius:8px;font-size:11px;font-weight:700;background:#FEF3C7;color:#D97706;">
                            في انتظار التحصيل
                        </span>
                        <?php elseif ((int) ($pl['unpaid_count'] ?? 0) > 0): ?>
                        <span style="padding:3px 8px;border-radius:8px;font-size:11px;font-weight:700;background:#FEE2E2;color:#DC2626;">
                            <?= (int) $pl['unpaid_count'] ?> غير مدفوع — <?= money((float) ($pl['unpaid_total'] ?? 0)) ?>
                        </span>
                        <?php else: ?>
                        <span style="padding:3px 8px;border-radius:8px;font-size:11px;font-weight:600;background:#ECFDF5;color:#059669;">سدد الكل</span>
                        <?php endif; ?>
                    </td>
                    <td><?= e($pl['enrolled_at'] ?? '') ?></td>
                    <td>
                        <?php if (can('sa.group.enroll')): ?>
                        <form method="POST" action="/sa/groups/<?= (int) $group['id'] ?>/remove-player" style="display:inline;" onsubmit="return confirm('هل تريد سحب هذا اللاعب من المجموعة؟');">
                            <?= csrf_field() ?>
                            <input type="hidden" name="player_id" value="<?= (int) $pl['player_id'] ?>">
                            <button type="submit" class="btn btn-sm btn-outline" style="font-size:12px;padding:4px 10px;color:#DC2626;border-color:#DC2626;">
                                <i data-lucide="user-minus" style="width:13px;height:13px;vertical-align:middle;"></i> سحب
                            </button>
                        </form>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php else: ?>
                <tr>
                    <td colspan="6" style="text-align:center;padding:30px;color:#6B7280;">لا يوجد لاعبون مسجلون بعد</td>
                </tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- Schedule -->
<div class="card">
    <div style="padding:15px 20px;border-bottom:1px solid #E5E7EB;display:flex;align-items:center;justify-content:space-between;">
        <h3 style="margin:0;color:#0D7377;font-size:15px;">الجدول الأسبوعي (<?= count($schedule) ?> حصة)</h3>
    </div>

    <!-- Current Schedule -->
    <?php if (!empty($schedule)): ?>
    <div class="table-responsive">
        <table class="data-table">
            <thead>
                <tr>
                    <th>اليوم</th>
                    <th>من</th>
                    <th>إلى</th>
                    <th>الوحدة/الملعب</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($schedule as $s): ?>
                <tr>
                    <td style="font-weight:600;"><?= e($dayNames[(int) $s['day_of_week']] ?? '') ?></td>
                    <td style="direction:ltr;text-align:right;"><?= e(substr($s['start_time'], 0, 5)) ?></td>
                    <td style="direction:ltr;text-align:right;"><?= e(substr($s['end_time'], 0, 5)) ?></td>
                    <td><?= e($s['unit_name'] ?? '—') ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php endif; ?>

    <!-- Save Schedule Form -->
    <?php if (can('sa.schedule.manage')): ?>
    <div style="padding:20px;border-top:1px solid #E5E7EB;">
        <h4 style="margin:0 0 15px 0;font-size:14px;color:#374151;">تحديث الجدول</h4>
        <form method="POST" action="/sa/groups/<?= (int) $group['id'] ?>/schedule" id="scheduleForm">
            <?= csrf_field() ?>
            <div id="scheduleEntries">
                <?php if (!empty($schedule)): ?>
                <?php foreach ($schedule as $idx => $s): ?>
                <div class="schedule-entry" style="display:grid;grid-template-columns:1fr 1fr 1fr 1fr auto;gap:10px;margin-bottom:10px;align-items:end;">
                    <div>
                        <?php if ($idx === 0): ?><label class="form-label" style="font-size:11px;">اليوم</label><?php endif; ?>
                        <select name="day_of_week[]" class="form-select">
                            <?php for ($d = 0; $d < 7; $d++): ?>
                            <option value="<?= $d ?>" <?= (int)$s['day_of_week'] === $d ? 'selected' : '' ?>><?= e($dayNames[$d]) ?></option>
                            <?php endfor; ?>
                        </select>
                    </div>
                    <div>
                        <?php if ($idx === 0): ?><label class="form-label" style="font-size:11px;">من</label><?php endif; ?>
                        <input type="time" name="start_time[]" value="<?= e(substr($s['start_time'], 0, 5)) ?>" class="form-input" style="direction:ltr;">
                    </div>
                    <div>
                        <?php if ($idx === 0): ?><label class="form-label" style="font-size:11px;">إلى</label><?php endif; ?>
                        <input type="time" name="end_time[]" value="<?= e(substr($s['end_time'], 0, 5)) ?>" class="form-input" style="direction:ltr;">
                    </div>
                    <div>
                        <?php if ($idx === 0): ?><label class="form-label" style="font-size:11px;">الوحدة</label><?php endif; ?>
                        <select name="facility_unit_id[]" class="form-select">
                            <?php foreach ($facilityUnits as $fu): ?>
                            <option value="<?= (int) $fu['id'] ?>" <?= (int)$s['facility_unit_id'] === (int)$fu['id'] ? 'selected' : '' ?>><?= e($fu['facility_name'] . ' - ' . $fu['name_ar']) ?></option>
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div>
                        <button type="button" class="btn btn-sm btn-outline" style="color:#DC2626;border-color:#DC2626;padding:6px 8px;" onclick="this.closest('.schedule-entry').remove();">
                            <i data-lucide="trash-2" style="width:14px;height:14px;"></i>
                        </button>
                    </div>
                </div>
                <?php endforeach; ?>
                <?php endif; ?>
            </div>
            <div style="display:flex;gap:10px;margin-top:10px;">
                <button type="button" class="btn btn-sm btn-outline" id="addScheduleEntry">
                    <i data-lucide="plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> إضافة حصة
                </button>
                <button type="submit" class="btn btn-sm btn-primary">
                    <i data-lucide="save" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> حفظ الجدول
                </button>
            </div>
        </form>
    </div>
    <?php endif; ?>

    <!-- Generate Training Sessions -->
    <?php if (can('sa.schedule.manage') && !empty($schedule)): ?>
    <div style="padding:20px;border-top:1px solid #E5E7EB;">
        <h4 style="margin:0 0 12px 0;font-size:14px;color:#374151;">توليد حصص تدريبية</h4>
        <form method="POST" action="/sa/groups/<?= (int) $group['id'] ?>/generate-sessions" style="display:flex;gap:12px;align-items:end;flex-wrap:wrap;">
            <?= csrf_field() ?>
            <div>
                <label class="form-label" style="font-size:11px;">من تاريخ</label>
                <input type="date" name="from_date" class="form-input" value="<?= date('Y-m-d') ?>" required style="direction:ltr;">
            </div>
            <div>
                <label class="form-label" style="font-size:11px;">إلى تاريخ</label>
                <input type="date" name="to_date" class="form-input" value="<?= date('Y-m-d', strtotime('+4 weeks')) ?>" required style="direction:ltr;">
            </div>
            <button type="submit" class="btn btn-sm btn-primary" onclick="return confirm('سيتم توليد حجوزات تدريبية لكل حصة في الجدول ضمن الفترة المحددة. متابعة؟');">
                <i data-lucide="calendar-plus" style="width:14px;height:14px;vertical-align:middle;margin-left:4px;"></i> توليد الحصص
            </button>
        </form>
    </div>
    <?php endif; ?>
</div>

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

    // Enrollment payment warning
    var enrollForm = document.getElementById('enrollForm');
    if (enrollForm) {
        enrollForm.addEventListener('submit', function(e) {
            var sel = document.getElementById('enrollPlayerSelect');
            var opt = sel.options[sel.selectedIndex];
            var unpaid = parseInt(opt.getAttribute('data-unpaid') || '0', 10);
            if (unpaid > 0) {
                if (!confirm('تنبيه: هذا اللاعب لديه ' + unpaid + ' اشتراك غير مدفوع!\nهل تريد تسجيله رغم ذلك؟')) {
                    e.preventDefault();
                }
            }
        });
    }

    var dayNames = <?= json_encode($dayNames) ?>;
    var facilityUnits = <?= json_encode($facilityUnits) ?>;

    document.getElementById('addScheduleEntry').addEventListener('click', function() {
        var container = document.getElementById('scheduleEntries');
        var entry = document.createElement('div');
        entry.className = 'schedule-entry';
        entry.style.cssText = 'display:grid;grid-template-columns:1fr 1fr 1fr 1fr auto;gap:10px;margin-bottom:10px;align-items:end;';

        var dayOptions = '';
        for (var d = 0; d < 7; d++) {
            dayOptions += '<option value="' + d + '">' + dayNames[d] + '</option>';
        }

        var unitOptions = '';
        for (var i = 0; i < facilityUnits.length; i++) {
            var u = facilityUnits[i];
            unitOptions += '<option value="' + u.id + '">' + u.facility_name + ' - ' + u.name_ar + '</option>';
        }

        entry.innerHTML = '<div><select name="day_of_week[]" class="form-select">' + dayOptions + '</select></div>' +
            '<div><input type="time" name="start_time[]" class="form-input" style="direction:ltr;"></div>' +
            '<div><input type="time" name="end_time[]" class="form-input" style="direction:ltr;"></div>' +
            '<div><select name="facility_unit_id[]" class="form-select">' + unitOptions + '</select></div>' +
            '<div><button type="button" class="btn btn-sm btn-outline" style="color:#DC2626;border-color:#DC2626;padding:6px 8px;" onclick="this.closest(\'.schedule-entry\').remove();"><i data-lucide="trash-2" style="width:14px;height:14px;"></i></button></div>';

        container.appendChild(entry);
        if (typeof lucide !== 'undefined') lucide.createIcons();
    });
});
</script>
<?php $__template->endSection(); ?>
