{{-- resources/views/admin/enrollments/index.blade.php --}}
    <!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>مدیریت ثبت‌نام‌ها | perspolis Admin</title>
    <script src="https://my-perspolis.com/storage/app/public/3.4.17"></script>
    <style>
        @import url('https://my-perspolis.com/storage/app/public/css2.css');
        * { font-family: 'Vazirmatn', sans-serif; }
        .badge-active     { @apply px-2 py-0.5 rounded-full text-xs font-semibold bg-emerald-100 text-emerald-700; }
        .badge-pending    { @apply px-2 py-0.5 rounded-full text-xs font-semibold bg-amber-100 text-amber-700; }
        .badge-cancelled  { @apply px-2 py-0.5 rounded-full text-xs font-semibold bg-red-100 text-red-700; }
        .badge-draft      { @apply px-2 py-0.5 rounded-full text-xs font-semibold bg-slate-100 text-slate-600; }

        /* Hide schedule options that don't match selected pack */
        option.hidden-opt { display: none; }
    </style>
</head>
<body class="bg-slate-50 font-sans flex h-screen overflow-hidden">

{{-- ─── Sidebar ──────────────────────────────────────────────────── --}}
<aside class="w-64 bg-slate-900 text-white flex flex-col h-screen flex-shrink-0">
    <div class="h-16 flex items-center justify-center border-b border-slate-800">
        <svg class="w-8 h-8 text-emerald-400 ml-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                  d="M3.055 11H5a2 2 0 012 2v1a2 2 0 002 2 2 2 0 012 2v2.945M8 3.935V5.5A2.5 2.5 0 0010.5 8h.5a2 2 0 012 2 2 2 0 104 0 2 2 0 012-2h1.064M15 20.488V18a2 2 0 012-2h3.064M21 12a9 9 0 11-18 0 9 9 0 0118 0z"/>
        </svg>
        <h1 class="text-xl font-bold tracking-wider">EduGoal Admin</h1>
    </div>
    <nav class="flex-1 px-4 py-6 space-y-2 overflow-y-auto">
        <a href="{{ route('admin.dashboard') }}"
           class="flex items-center px-4 py-3 text-slate-300 hover:bg-slate-800 hover:text-white rounded-lg transition">
            <span class="font-medium">داشبورد</span>
        </a>
        <a href="{{ route('admin.schools') }}"
           class="flex items-center px-4 py-3 text-slate-300 hover:bg-slate-800 hover:text-white rounded-lg transition">
            <span class="font-medium">مدارس</span>
        </a>
        <a href="{{ route('admin.packs') }}"
           class="flex items-center px-4 py-3 text-slate-300 hover:bg-slate-800 hover:text-white rounded-lg transition">
            <span class="font-medium">پک‌ها</span>
        </a>
        <a href="{{ route('admin.schedules') }}"
           class="flex items-center px-4 py-3 text-slate-300 hover:bg-slate-800 hover:text-white rounded-lg transition">
            <span class="font-medium">زمان‌بندی‌ها</span>
        </a>
        <a href="{{ route('admin.enrollments') }}"
           class="flex items-center px-4 py-3 bg-emerald-600 text-white rounded-lg">
            <span class="font-medium">ثبت‌نام‌ها</span>
        </a>
    </nav>
    <div class="p-4 border-t border-slate-800">
        <form method="POST" action="#">
            @csrf
            <button type="submit" class="w-full text-right px-4 py-2 text-slate-400 hover:text-white transition text-sm">
                خروج
            </button>
        </form>
    </div>
</aside>

{{-- ─── Main Content ─────────────────────────────────────────────── --}}
<div class="flex-1 flex flex-col h-screen overflow-hidden text-slate-800">

    <header class="h-16 bg-white shadow-sm flex items-center justify-between px-8 z-10">
        <h2 class="text-xl font-bold text-slate-800">مدیریت ثبت‌نام‌ها</h2>
        <div class="w-10 h-10 rounded-full bg-emerald-500 flex items-center justify-center text-white font-bold text-sm">A</div>
    </header>

    <main class="flex-1 overflow-x-hidden overflow-y-auto bg-slate-50 p-8">

        {{-- Flash Messages --}}
        @if(session('success'))
            <div class="mb-6 p-4 bg-emerald-50 border border-emerald-200 text-emerald-800 rounded-lg text-sm">
                ✅ {{ session('success') }}
            </div>
        @endif
        @if(session('error'))
            <div class="mb-6 p-4 bg-red-50 border border-red-200 text-red-800 rounded-lg text-sm">
                ❌ {{ session('error') }}
            </div>
        @endif

        {{-- ── Filter Panel ──────────────────────────────────────── --}}
        <div class="bg-white rounded-xl shadow-sm border border-slate-100 p-6 mb-6">
            <h3 class="text-sm font-semibold text-slate-600 mb-4">فیلتر ثبت‌نام‌ها</h3>
            <form method="GET" action="{{ route('admin.enrollments') }}" id="filterForm"
                  class="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-4 gap-4">

                {{-- 1. Pack filter --}}
                <div>
                    <label class="block text-xs font-medium text-slate-500 mb-1">پک</label>
                    <select name="pack_id" id="packSelect"
                            class="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-emerald-400 outline-none bg-white">
                        <option value="">-- همه پک‌ها --</option>
                        @foreach($packs as $pack)
                            <option value="{{ $pack->id }}"
                                {{ request('pack_id') == $pack->id ? 'selected' : '' }}>
                                {{ $pack->school->name ?? '—' }} › {{ $pack->name }}
                            </option>
                        @endforeach
                    </select>
                </div>

                {{-- 2. Schedule filter — options carry data-pack-id so JS can filter them --}}
                <div>
                    <label class="block text-xs font-medium text-slate-500 mb-1">زمان‌بندی</label>
                    <select name="schedule_id" id="scheduleSelect"
                            class="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-emerald-400 outline-none bg-white">
                        <option value="">-- همه زمان‌بندی‌ها --</option>
                        @foreach($schedules as $schedule)
                            @php
                                $days  = ['','دوشنبه','سه‌شنبه','چهارشنبه','پنج‌شنبه','جمعه','شنبه','یک‌شنبه'];
                                $day   = $days[$schedule->day_of_week] ?? '—';
                                $start = \Carbon\Carbon::parse($schedule->start_time)->format('H:i');
                                $end   = \Carbon\Carbon::parse($schedule->end_time)->format('H:i');
                                $packName = $schedule->pack->name ?? '—';
                                $school   = $schedule->pack->school->name ?? '—';
                            @endphp
                            <option value="{{ $schedule->id }}"
                                    data-pack-id="{{ $schedule->pack_id }}"
                                {{ request('schedule_id') == $schedule->id ? 'selected' : '' }}>
                                {{ $school }} › {{ $packName }} | {{ $day }} {{ $start }}–{{ $end }}
                            </option>
                        @endforeach
                    </select>
                </div>

                {{-- 3. Status filter --}}
                <div>
                    <label class="block text-xs font-medium text-slate-500 mb-1">وضعیت</label>
                    <select name="status"
                            class="w-full border border-slate-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-emerald-400 outline-none bg-white"
                            onchange="document.getElementById('filterForm').submit()">
                        <option value="">-- همه وضعیت‌ها --</option>
                        <option value="active"          {{ request('status') == 'active'          ? 'selected' : '' }}>فعال</option>
                        <option value="pending_payment" {{ request('status') == 'pending_payment' ? 'selected' : '' }}>در انتظار پرداخت</option>
                        <option value="cancelled"       {{ request('status') == 'cancelled'       ? 'selected' : '' }}>لغو شده</option>
                        <option value="draft"           {{ request('status') == 'draft'           ? 'selected' : '' }}>پیش‌نویس</option>
                    </select>
                </div>

                {{-- 4. Search --}}
                <div>
                    <label class="block text-xs font-medium text-slate-500 mb-1">جستجو (نام / موبایل)</label>
                    <div class="flex gap-2">
                        <input type="text" name="search" value="{{ request('search') }}"
                               placeholder="نام یا شماره تلفن..."
                               class="flex-1 border border-slate-200 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-emerald-400 outline-none">
                        <button type="submit"
                                class="px-4 py-2 bg-emerald-600 text-white rounded-lg text-sm hover:bg-emerald-700 transition">
                            جستجو
                        </button>
                    </div>
                </div>

            </form>

            {{-- Active filter chips --}}
            @if(request()->hasAny(['pack_id','schedule_id','status','search']))
                <div class="flex flex-wrap gap-2 mt-4 pt-4 border-t border-slate-100">
                    <span class="text-xs text-slate-400 self-center">فیلترهای فعال:</span>
                    @if(request('pack_id'))
                        @php $selectedPack = $packs->firstWhere('id', request('pack_id')); @endphp
                        <span class="inline-flex items-center gap-1 px-3 py-1 bg-emerald-50 text-emerald-700 rounded-full text-xs font-medium">
                            پک: {{ $selectedPack?->name ?? request('pack_id') }}
                            <a href="{{ request()->fullUrlWithQuery(['pack_id' => null, 'schedule_id' => null]) }}" class="hover:text-emerald-900">✕</a>
                        </span>
                    @endif
                    @if(request('schedule_id'))
                        @php $selectedSched = $schedules->firstWhere('id', request('schedule_id')); @endphp
                        @php
                            $days2 = ['','دوشنبه','سه‌شنبه','چهارشنبه','پنج‌شنبه','جمعه','شنبه','یک‌شنبه'];
                        @endphp
                        <span class="inline-flex items-center gap-1 px-3 py-1 bg-blue-50 text-blue-700 rounded-full text-xs font-medium">
                            زمان: {{ $days2[$selectedSched?->day_of_week] ?? '—' }}
                            {{ $selectedSched ? \Carbon\Carbon::parse($selectedSched->start_time)->format('H:i') : '' }}
                            <a href="{{ request()->fullUrlWithQuery(['schedule_id' => null]) }}" class="hover:text-blue-900">✕</a>
                        </span>
                    @endif
                    @if(request('status'))
                        @php $statusLabels = ['active'=>'فعال','pending_payment'=>'در انتظار پرداخت','cancelled'=>'لغو شده','draft'=>'پیش‌نویس']; @endphp
                        <span class="inline-flex items-center gap-1 px-3 py-1 bg-amber-50 text-amber-700 rounded-full text-xs font-medium">
                            وضعیت: {{ $statusLabels[request('status')] ?? request('status') }}
                            <a href="{{ request()->fullUrlWithQuery(['status' => null]) }}" class="hover:text-amber-900">✕</a>
                        </span>
                    @endif
                    @if(request('search'))
                        <span class="inline-flex items-center gap-1 px-3 py-1 bg-slate-100 text-slate-700 rounded-full text-xs font-medium">
                            جستجو: {{ request('search') }}
                            <a href="{{ request()->fullUrlWithQuery(['search' => null]) }}" class="hover:text-slate-900">✕</a>
                        </span>
                    @endif
                    <a href="{{ route('admin.enrollments') }}"
                       class="inline-flex items-center gap-1 px-3 py-1 bg-red-50 text-red-600 rounded-full text-xs font-medium hover:bg-red-100 transition">
                        پاک کردن همه ✕
                    </a>
                </div>
            @endif
        </div>

        {{-- ── Stats Row ──────────────────────────────────────────── --}}
        <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6">
            <div class="bg-white rounded-xl border border-slate-100 shadow-sm p-5 flex items-center gap-4">
                <div class="p-3 bg-emerald-100 rounded-lg text-emerald-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0z"/>
                    </svg>
                </div>
                <div>
                    <p class="text-xs text-slate-500">کل نتایج</p>
                    <p class="text-2xl font-bold text-slate-800">{{ $enrollments->total() }}</p>
                </div>
            </div>
            <div class="bg-white rounded-xl border border-slate-100 shadow-sm p-5 flex items-center gap-4">
                <div class="p-3 bg-blue-100 rounded-lg text-blue-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                </div>
                <div>
                    <p class="text-xs text-slate-500">فعال</p>
                    <p class="text-2xl font-bold text-slate-800">{{ $stats['active'] }}</p>
                </div>
            </div>
            <div class="bg-white rounded-xl border border-slate-100 shadow-sm p-5 flex items-center gap-4">
                <div class="p-3 bg-amber-100 rounded-lg text-amber-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                </div>
                <div>
                    <p class="text-xs text-slate-500">در انتظار پرداخت</p>
                    <p class="text-2xl font-bold text-slate-800">{{ $stats['pending_payment'] }}</p>
                </div>
            </div>
            <div class="bg-white rounded-xl border border-slate-100 shadow-sm p-5 flex items-center gap-4">
                <div class="p-3 bg-red-100 rounded-lg text-red-600">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
                              d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z"/>
                    </svg>
                </div>
                <div>
                    <p class="text-xs text-slate-500">لغو شده</p>
                    <p class="text-2xl font-bold text-slate-800">{{ $stats['cancelled'] }}</p>
                </div>
            </div>
        </div>

        {{-- ── Enrollments Table ───────────────────────────────────── --}}
        <div class="bg-white rounded-xl shadow-sm border border-slate-100 overflow-hidden">
            <div class="px-6 py-4 border-b border-slate-100 flex justify-between items-center">
                <h3 class="text-base font-semibold text-slate-800">لیست ثبت‌نام‌ها</h3>
                <span class="text-sm text-slate-400">
                    {{ $enrollments->firstItem() ?? 0 }}–{{ $enrollments->lastItem() ?? 0 }}
                    از {{ $enrollments->total() }}
                </span>
            </div>

            <div class="overflow-x-auto">
                <table class="w-full text-right text-sm">
                    <thead>
                    <tr class="bg-slate-50 text-slate-500 text-xs border-b border-slate-100">
                        <th class="px-4 py-3 font-medium">#</th>
                        <th class="px-4 py-3 font-medium">نام بازیکن</th>
                        <th class="px-4 py-3 font-medium">تلفن</th>
                        <th class="px-4 py-3 font-medium">تاریخ تولد</th>
                        <th class="px-4 py-3 font-medium">کد ملی</th>
                        <th class="px-4 py-3 font-medium">ولی / سرپرست</th>
                        <th class="px-4 py-3 font-medium">پک</th>
                        <th class="px-4 py-3 font-medium">زمان‌بندی</th>
                        <th class="px-4 py-3 font-medium">وضعیت</th>
                        <th class="px-4 py-3 font-medium">تاریخ ثبت</th>
                        <th class="px-4 py-3 font-medium">عملیات</th>
                    </tr>
                    </thead>
                    <tbody class="divide-y divide-slate-50">
                    @forelse($enrollments as $enrollment)
                        @php
                            $statusMap = [
                                'active'          => ['فعال',              'badge-active'],
                                'pending_payment' => ['در انتظار پرداخت', 'badge-pending'],
                                'cancelled'       => ['لغو شده',           'badge-cancelled'],
                                'draft'           => ['پیش‌نویس',          'badge-draft'],
                            ];
                            [$sLabel, $sCls] = $statusMap[$enrollment->status] ?? [$enrollment->status, 'badge-draft'];

                            // Collect all schedules for this enrollment's pack
                            $packSchedules = $enrollment->pack?->schedules ?? collect();
                            $days3 = ['','دوشنبه','سه‌شنبه','چهارشنبه','پنج‌شنبه','جمعه','شنبه','یک‌شنبه'];
                        @endphp
                        <tr class="hover:bg-slate-50 transition-colors">
                            <td class="px-4 py-3 text-slate-400 text-xs">{{ $enrollment->id }}</td>

                            {{-- Player name --}}
                            <td class="px-4 py-3 font-medium text-slate-800">
                                {{ $enrollment->user->name ?? '—' }}
                                @if($enrollment->user?->parent_id)
                                    <span class="block text-xs text-slate-400 font-normal">
                                        فرزند: {{ $enrollment->user->parent->name ?? '—' }}
                                    </span>
                                @endif
                            </td>

                            {{-- Phone --}}
                            <td class="px-4 py-3 text-slate-600 font-mono text-xs" dir="ltr">
                                {{ $enrollment->user->phone ?? '—' }}
                            </td>

                            {{-- Birth date --}}
                            <td class="px-4 py-3 text-slate-600 text-xs">
                                {{ $enrollment->user->birth_date ?? '—' }}
                            </td>

                            {{-- National ID --}}
                            <td class="px-4 py-3 text-slate-600 text-xs font-mono">
                                {{ $enrollment->user->national_id ?? '—' }}
                            </td>

                            {{-- Guardian --}}
                            <td class="px-4 py-3 text-slate-600 text-xs">
                                @if($enrollment->user?->guardian_name)
                                    <span class="font-medium">{{ $enrollment->user->guardian_name }}</span>
                                    <span class="block font-mono" dir="ltr">{{ $enrollment->user->guardian_phone }}</span>
                                @else
                                    —
                                @endif
                            </td>

                            {{-- Pack --}}
                            <td class="px-4 py-3 text-xs">
                                <span class="font-medium text-slate-700">{{ $enrollment->pack->name ?? '—' }}</span>
                                <span class="block text-slate-400">{{ $enrollment->pack->school->name ?? '—' }}</span>
                                <span class="block text-slate-400">
                                    سن {{ $enrollment->pack->min_age ?? '?' }}–{{ $enrollment->pack->max_age ?? '?' }}
                                </span>
                            </td>

                            {{-- Schedules for this pack --}}
                            <td class="px-4 py-3 text-xs text-slate-600">
                                @forelse($packSchedules as $sch)
                                    <span class="inline-flex items-center gap-1 mb-1 px-2 py-0.5 bg-slate-100 rounded text-slate-700 whitespace-nowrap">
                                        {{ $days3[$sch->day_of_week] ?? '—' }}
                                        {{ \Carbon\Carbon::parse($sch->start_time)->format('H:i') }}–{{ \Carbon\Carbon::parse($sch->end_time)->format('H:i') }}
                                    </span><br>
                                @empty
                                    <span class="text-slate-400">—</span>
                                @endforelse
                            </td>

                            {{-- Status --}}
                            <td class="px-4 py-3">
                                <span class="{{ $sCls }}">{{ $sLabel }}</span>
                            </td>

                            {{-- Enrolled at --}}
                            <td class="px-4 py-3 text-slate-500 text-xs" dir="ltr">
                                {{ $enrollment->created_at?->format('Y-m-d') ?? '—' }}
                            </td>

                            {{-- Actions --}}
                            <td class="px-4 py-3">
                                <button
                                    onclick="openChangePack(
                                        {{ $enrollment->id }},
                                        {{ $enrollment->pack_id }},
                                        '{{ addslashes($enrollment->user->name ?? '') }}',
                                        '{{ $enrollment->status }}'
                                    )"
                                    class="px-3 py-1 text-xs bg-blue-50 text-blue-600 border border-blue-200 rounded-lg hover:bg-blue-100 transition whitespace-nowrap">
                                    تغییر پک
                                </button>
                            </td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="11" class="text-center py-16 text-slate-400 text-sm">
                                هیچ ثبت‌نامی یافت نشد.
                            </td>
                        </tr>
                    @endforelse
                    </tbody>
                </table>
            </div>

            {{-- Pagination --}}
            @if($enrollments->hasPages())
                <div class="px-6 py-4 border-t border-slate-100">
                    {{ $enrollments->appends(request()->query())->links() }}
                </div>
            @endif
        </div>

    </main>
</div>

{{-- ─── Change Pack Modal ────────────────────────────────────────── --}}
<div id="changePackModal"
     class="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 hidden items-center justify-center p-4">
    <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-6">
        <div class="flex justify-between items-center mb-5">
            <h3 class="text-lg font-bold text-slate-800">تغییر پک ثبت‌نام</h3>
            <button onclick="closeChangePack()" class="text-slate-400 hover:text-slate-600 transition">
                <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </div>

        <p class="text-xs text-slate-500 mb-0.5">بازیکن:</p>
        <p id="modalPlayerName" class="font-semibold text-slate-800 mb-5"></p>

        <form id="changePackForm" method="POST" action="{{ route('admin.enrollments.changePack') }}">
            @csrf
            @method('PATCH')
            <input type="hidden" name="enrollment_id" id="modalEnrollmentId">

            {{-- New Pack --}}
            <div class="mb-4">
                <label class="block text-sm font-medium text-slate-700 mb-1">پک جدید</label>
                <select name="new_pack_id" id="modalPackSelect"
                        class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-emerald-400 outline-none bg-white"
                        onchange="updateModalSchedules()">
                    @foreach($packs as $pack)
                        <option value="{{ $pack->id }}">
                            {{ $pack->school->name ?? '—' }} › {{ $pack->name }}
                            (سن {{ $pack->min_age }}–{{ $pack->max_age }} | ظرفیت {{ $pack->capacity }})
                        </option>
                    @endforeach
                </select>
            </div>

            {{-- Schedules preview for selected pack --}}
            <div class="mb-4">
                <label class="block text-sm font-medium text-slate-700 mb-1">زمان‌بندی‌های این پک</label>
                <div id="modalScheduleList"
                     class="min-h-[40px] bg-slate-50 border border-slate-200 rounded-lg px-3 py-2 text-xs text-slate-600 space-y-1">
                    {{-- Filled by JS --}}
                </div>
            </div>

            {{-- Status --}}
            <div class="mb-6">
                <label class="block text-sm font-medium text-slate-700 mb-1">وضعیت</label>
                <select name="status" id="modalStatus"
                        class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm focus:ring-2 focus:ring-emerald-400 outline-none bg-white">
                    <option value="active">فعال</option>
                    <option value="pending_payment">در انتظار پرداخت</option>
                    <option value="cancelled">لغو شده</option>
                    <option value="draft">پیش‌نویس</option>
                </select>
            </div>

            <div class="flex gap-3">
                <button type="submit"
                        class="flex-1 py-2.5 bg-emerald-600 text-white text-sm font-semibold rounded-lg hover:bg-emerald-700 transition">
                    ذخیره تغییرات
                </button>
                <button type="button" onclick="closeChangePack()"
                        class="flex-1 py-2.5 bg-slate-100 text-slate-700 text-sm font-semibold rounded-lg hover:bg-slate-200 transition">
                    انصراف
                </button>
            </div>
        </form>
    </div>
</div>

<script>
    // ── Schedule data map: pack_id → array of schedule strings ──────────────────
    const packSchedules = {
        @foreach($packs as $pack)
        "{{ $pack->id }}": [
            @foreach($pack->schedules as $sch)
                @php
                    $daysJs = ['','دوشنبه','سه‌شنبه','چهارشنبه','پنج‌شنبه','جمعه','شنبه','یک‌شنبه'];
                @endphp
                "{{ $daysJs[$sch->day_of_week] ?? '—' }} {{ \Carbon\Carbon::parse($sch->start_time)->format('H:i') }}–{{ \Carbon\Carbon::parse($sch->end_time)->format('H:i') }}",
            @endforeach
        ],
        @endforeach
    };

    // ── Modal open/close ─────────────────────────────────────────────────────────
    function openChangePack(enrollmentId, currentPackId, playerName, currentStatus) {
        document.getElementById('modalEnrollmentId').value = enrollmentId;
        document.getElementById('modalPlayerName').textContent = playerName;

        // Pre-select current pack
        const packSel = document.getElementById('modalPackSelect');
        for (let opt of packSel.options) {
            opt.selected = (opt.value == currentPackId);
        }

        // Pre-select current status
        const statusSel = document.getElementById('modalStatus');
        for (let opt of statusSel.options) {
            opt.selected = (opt.value === currentStatus);
        }

        updateModalSchedules();

        const modal = document.getElementById('changePackModal');
        modal.classList.remove('hidden');
        modal.classList.add('flex');
    }

    function closeChangePack() {
        const modal = document.getElementById('changePackModal');
        modal.classList.add('hidden');
        modal.classList.remove('flex');
    }

    // ── Update schedule preview inside the modal ─────────────────────────────────
    function updateModalSchedules() {
        const packId = document.getElementById('modalPackSelect').value;
        const list   = document.getElementById('modalScheduleList');
        const scheds = packSchedules[packId] || [];

        if (scheds.length === 0) {
            list.innerHTML = '<span class="text-slate-400">زمان‌بندی‌ای ثبت نشده</span>';
            return;
        }
        list.innerHTML = scheds.map(s =>
            `<div class="flex items-center gap-1">
            <span class="w-2 h-2 rounded-full bg-emerald-400 inline-block"></span>
            ${s}
        </div>`
        ).join('');
    }

    // ── Close modal on backdrop click ────────────────────────────────────────────
    document.getElementById('changePackModal').addEventListener('click', function (e) {
        if (e.target === this) closeChangePack();
    });

    // ── Pack → Schedule filter in the filter bar ─────────────────────────────────
    const packSelect     = document.getElementById('packSelect');
    const scheduleSelect = document.getElementById('scheduleSelect');

    function syncScheduleDropdown() {
        const selectedPack = packSelect.value;
        let hasVisible = false;

        Array.from(scheduleSelect.options).forEach(opt => {
            if (!opt.value) return; // keep the "all" option
            const match = !selectedPack || opt.dataset.packId === selectedPack;
            opt.style.display = match ? '' : 'none';
            if (match && opt.value) hasVisible = true;
        });

        // If current selected schedule no longer matches, reset it
        const current = scheduleSelect.value;
        if (current) {
            const currentOpt = scheduleSelect.querySelector(`option[value="${current}"]`);
            if (currentOpt && currentOpt.style.display === 'none') {
                scheduleSelect.value = '';
            }
        }
    }

    packSelect.addEventListener('change', function () {
        syncScheduleDropdown();
        document.getElementById('filterForm').submit();
    });

    scheduleSelect.addEventListener('change', function () {
        document.getElementById('filterForm').submit();
    });

    // Run on page load to apply any pre-selected pack filter
    syncScheduleDropdown();
</script>

</body>
</html>
