<?php
declare(strict_types=1);

use App\Core\Database;

return function (Database $db): void {
    $ts = date('Y-m-d H:i:s');
    $today = date('Y-m-d');

    // ══════════════════════════════════════════════════════════════════
    // 1. DISCIPLINE — Swimming (ensure exists)
    // ══════════════════════════════════════════════════════════════════
    $existing = $db->selectOne("SELECT id FROM sa_disciplines WHERE code = 'SWIMMING'", []);
    if (!$existing) {
        $db->insert('sa_disciplines', [
            'code'           => 'SWIMMING',
            'name_ar'        => 'السباحة',
            'name_en'        => 'Swimming',
            'category'       => 'aquatic',
            'icon'           => 'waves',
            'description_ar' => 'رياضة السباحة بأنواعها — حرة، ظهر، صدر، فراشة',
            'config_json'    => json_encode([
                'age_groups' => [
                    ['code' => 'u6', 'label_ar' => 'تحت 6', 'min_age' => 4, 'max_age' => 5],
                    ['code' => 'u8', 'label_ar' => 'تحت 8', 'min_age' => 6, 'max_age' => 7],
                    ['code' => 'u10', 'label_ar' => 'تحت 10', 'min_age' => 8, 'max_age' => 9],
                    ['code' => 'u12', 'label_ar' => 'تحت 12', 'min_age' => 10, 'max_age' => 11],
                    ['code' => 'u14', 'label_ar' => 'تحت 14', 'min_age' => 12, 'max_age' => 13],
                    ['code' => 'u16', 'label_ar' => 'تحت 16', 'min_age' => 14, 'max_age' => 15],
                    ['code' => 'u18', 'label_ar' => 'تحت 18', 'min_age' => 16, 'max_age' => 17],
                    ['code' => 'senior', 'label_ar' => 'كبار', 'min_age' => 18, 'max_age' => 99],
                ],
                'skill_levels' => [
                    ['code' => 'beginner', 'label_ar' => 'مبتدئ'],
                    ['code' => 'intermediate', 'label_ar' => 'متوسط'],
                    ['code' => 'advanced', 'label_ar' => 'متقدم'],
                    ['code' => 'elite', 'label_ar' => 'نخبة'],
                ],
            ], JSON_UNESCAPED_UNICODE),
            'sort_order'     => 1,
            'is_active'      => 1,
            'is_archived'    => 0,
            'created_at'     => $ts,
            'updated_at'     => $ts,
        ]);
    }
    $swimId = (int) $db->selectOne("SELECT id FROM sa_disciplines WHERE code = 'SWIMMING'", [])['id'];

    // ══════════════════════════════════════════════════════════════════
    // 2. FACILITY — Main Swimming Pool (Olympic 50m, 8 lanes)
    // ══════════════════════════════════════════════════════════════════
    $existingFac = $db->selectOne("SELECT id FROM sa_facilities WHERE code = 'POOL-MAIN'", []);
    if (!$existingFac) {
        $db->insert('sa_facilities', [
            'code'                 => 'POOL-MAIN',
            'name_ar'              => 'حمام السباحة الأوليمبي',
            'name_en'              => 'Olympic Swimming Pool',
            'facility_type'        => 'pool',
            'discipline_id'        => $swimId,
            'location_description' => 'المبنى الرياضي — الطابق الأرضي — خلف الملاعب',
            'operating_hours_json' => json_encode([
                'start'        => '06:00',
                'end'          => '22:00',
                'slot_minutes' => 60,
            ]),
            'is_active'    => 1,
            'is_archived'  => 0,
            'branch_id'    => 1,
            'created_at'   => $ts,
            'updated_at'   => $ts,
        ]);
    }
    $poolId = (int) $db->selectOne("SELECT id FROM sa_facilities WHERE code = 'POOL-MAIN'", [])['id'];

    // ══════════════════════════════════════════════════════════════════
    // 3. FACILITY UNITS — 8 Lanes (shared mode, capacity 8 each)
    // ══════════════════════════════════════════════════════════════════
    $lanes = [
        ['code' => 'LANE-1', 'name_ar' => 'حارة 1', 'name_en' => 'Lane 1', 'sort' => 1, 'depth' => '1.8m'],
        ['code' => 'LANE-2', 'name_ar' => 'حارة 2', 'name_en' => 'Lane 2', 'sort' => 2, 'depth' => '1.8m'],
        ['code' => 'LANE-3', 'name_ar' => 'حارة 3', 'name_en' => 'Lane 3', 'sort' => 3, 'depth' => '2.0m'],
        ['code' => 'LANE-4', 'name_ar' => 'حارة 4', 'name_en' => 'Lane 4', 'sort' => 4, 'depth' => '2.0m'],
        ['code' => 'LANE-5', 'name_ar' => 'حارة 5', 'name_en' => 'Lane 5', 'sort' => 5, 'depth' => '2.0m'],
        ['code' => 'LANE-6', 'name_ar' => 'حارة 6', 'name_en' => 'Lane 6', 'sort' => 6, 'depth' => '2.0m'],
        ['code' => 'LANE-7', 'name_ar' => 'حارة 7', 'name_en' => 'Lane 7', 'sort' => 7, 'depth' => '1.8m'],
        ['code' => 'LANE-8', 'name_ar' => 'حارة 8', 'name_en' => 'Lane 8', 'sort' => 8, 'depth' => '1.8m'],
    ];

    $laneIds = [];
    foreach ($lanes as $lane) {
        $existing = $db->selectOne(
            "SELECT id FROM sa_facility_units WHERE facility_id = ? AND code = ?",
            [$poolId, $lane['code']]
        );
        if (!$existing) {
            $db->insert('sa_facility_units', [
                'facility_id'     => $poolId,
                'code'            => $lane['code'],
                'name_ar'         => $lane['name_ar'],
                'name_en'         => $lane['name_en'],
                'unit_type'       => 'lane',
                'booking_mode'    => 'shared',
                'max_capacity'    => 8,
                'sort_order'      => $lane['sort'],
                'dimensions_json' => json_encode(['length' => 50, 'width' => 2.5, 'depth' => $lane['depth']]),
                'config_json'     => json_encode(['surface' => 'tiled', 'heated' => true, 'lane_number' => $lane['sort']]),
                'is_active'       => 1,
                'created_at'      => $ts,
                'updated_at'      => $ts,
            ]);
            $laneIds[$lane['code']] = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id", [])['id'];
        } else {
            $laneIds[$lane['code']] = (int) $existing['id'];
        }
    }

    // ══════════════════════════════════════════════════════════════════
    // 4. TIME BRACKETS — Peak / Off-Peak / Weekend
    // ══════════════════════════════════════════════════════════════════
    $brackets = [
        ['name_ar' => 'ذروة صباحية', 'name_en' => 'Morning Peak', 'type' => 'peak', 'start' => '06:00:00', 'end' => '09:00:00', 'days' => [0,1,2,3,4]],
        ['name_ar' => 'عادي صباحي', 'name_en' => 'Morning Off-Peak', 'type' => 'off_peak', 'start' => '09:00:00', 'end' => '14:00:00', 'days' => [0,1,2,3,4]],
        ['name_ar' => 'ذروة بعد الظهر', 'name_en' => 'Afternoon Peak', 'type' => 'peak', 'start' => '14:00:00', 'end' => '18:00:00', 'days' => [0,1,2,3,4]],
        ['name_ar' => 'عادي مسائي', 'name_en' => 'Evening Off-Peak', 'type' => 'off_peak', 'start' => '18:00:00', 'end' => '22:00:00', 'days' => [0,1,2,3,4]],
        ['name_ar' => 'نهاية أسبوع', 'name_en' => 'Weekend', 'type' => 'weekend', 'start' => '06:00:00', 'end' => '22:00:00', 'days' => [5,6]],
    ];

    $bracketIds = [];
    foreach ($brackets as $b) {
        $existing = $db->selectOne(
            "SELECT id FROM sa_time_brackets WHERE facility_id = ? AND name_ar = ?",
            [$poolId, $b['name_ar']]
        );
        if (!$existing) {
            $db->insert('sa_time_brackets', [
                'facility_id'       => $poolId,
                'name_ar'           => $b['name_ar'],
                'name_en'           => $b['name_en'],
                'bracket_type'      => $b['type'],
                'start_time'        => $b['start'],
                'end_time'          => $b['end'],
                'days_of_week_json' => json_encode($b['days']),
                'is_active'         => 1,
                'created_at'        => $ts,
                'updated_at'        => $ts,
            ]);
            $bracketIds[$b['name_ar']] = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id", [])['id'];
        } else {
            $bracketIds[$b['name_ar']] = (int) $existing['id'];
        }
    }

    // ══════════════════════════════════════════════════════════════════
    // 5. PRICING RULES — Per lane × bracket × group size
    // ══════════════════════════════════════════════════════════════════
    // Pricing matrix:
    //   Peak:     member 200/person, non-member 300/person (1-3), 150/250 (4-8)
    //   Off-Peak: member 120/person, non-member 180/person (1-3), 100/150 (4-8)
    //   Weekend:  member 250/person, non-member 350/person (1-3), 180/280 (4-8)

    $pricingMatrix = [
        'ذروة صباحية'      => [['min'=>1,'max'=>3,'m'=>200,'nm'=>300], ['min'=>4,'max'=>8,'m'=>150,'nm'=>250]],
        'عادي صباحي'       => [['min'=>1,'max'=>3,'m'=>120,'nm'=>180], ['min'=>4,'max'=>8,'m'=>100,'nm'=>150]],
        'ذروة بعد الظهر'   => [['min'=>1,'max'=>3,'m'=>200,'nm'=>300], ['min'=>4,'max'=>8,'m'=>150,'nm'=>250]],
        'عادي مسائي'       => [['min'=>1,'max'=>3,'m'=>120,'nm'=>180], ['min'=>4,'max'=>8,'m'=>100,'nm'=>150]],
        'نهاية أسبوع'      => [['min'=>1,'max'=>3,'m'=>250,'nm'=>350], ['min'=>4,'max'=>8,'m'=>180,'nm'=>280]],
    ];

    foreach ($laneIds as $laneCode => $laneId) {
        foreach ($pricingMatrix as $bracketName => $tiers) {
            $bracketId = $bracketIds[$bracketName];
            foreach ($tiers as $tier) {
                $existing = $db->selectOne(
                    "SELECT id FROM sa_pricing_rules WHERE facility_unit_id = ? AND time_bracket_id = ? AND group_size_min = ? AND effective_from = ?",
                    [$laneId, $bracketId, $tier['min'], $today]
                );
                if (!$existing) {
                    $db->insert('sa_pricing_rules', [
                        'facility_unit_id'          => $laneId,
                        'time_bracket_id'           => $bracketId,
                        'group_size_min'            => $tier['min'],
                        'group_size_max'            => $tier['max'],
                        'price_per_person_member'   => $tier['m'],
                        'price_per_person_nonmember'=> $tier['nm'],
                        'effective_from'            => $today,
                        'effective_to'              => null,
                        'is_active'                 => 1,
                        'created_at'                => $ts,
                        'updated_at'                => $ts,
                    ]);
                }
            }
        }
    }

    // ══════════════════════════════════════════════════════════════════
    // 6. COACHES — 4 swimming coaches
    // ══════════════════════════════════════════════════════════════════
    $coaches = [
        ['code' => 'COACH-SWIM-01', 'name_ar' => 'أحمد محمد حسن', 'name_en' => 'Ahmed Mohamed Hassan', 'phone' => '01001234501', 'nid' => '28501011234567', 'gender' => 'male', 'type' => 'staff', 'payment' => 'monthly_fixed', 'monthly' => 8000],
        ['code' => 'COACH-SWIM-02', 'name_ar' => 'سارة أحمد علي', 'name_en' => 'Sara Ahmed Ali', 'phone' => '01001234502', 'nid' => '29002021234567', 'gender' => 'female', 'type' => 'staff', 'payment' => 'monthly_fixed', 'monthly' => 7500],
        ['code' => 'COACH-SWIM-03', 'name_ar' => 'محمد إبراهيم', 'name_en' => 'Mohamed Ibrahim', 'phone' => '01001234503', 'nid' => '28803031234567', 'gender' => 'male', 'type' => 'contract', 'payment' => 'per_session', 'session' => 250],
        ['code' => 'COACH-SWIM-04', 'name_ar' => 'نورهان سعيد', 'name_en' => 'Nourhan Said', 'phone' => '01001234504', 'nid' => '29204041234567', 'gender' => 'female', 'type' => 'contract', 'payment' => 'per_player', 'session' => 50],
    ];

    $coachIds = [];
    foreach ($coaches as $c) {
        $existing = $db->selectOne("SELECT id FROM sa_coaches WHERE code = ?", [$c['code']]);
        if (!$existing) {
            $db->insert('sa_coaches', [
                'code'            => $c['code'],
                'full_name_ar'    => $c['name_ar'],
                'full_name_en'    => $c['name_en'],
                'national_id'     => $c['nid'],
                'phone'           => $c['phone'],
                'gender'          => $c['gender'],
                'employment_type' => $c['type'],
                'payment_model'   => $c['payment'],
                'monthly_rate'    => $c['payment'] === 'monthly_fixed' ? $c['monthly'] : null,
                'session_rate'    => in_array($c['payment'], ['per_session','per_player']) ? $c['session'] : null,
                'max_groups'      => 6,
                'is_active'       => 1,
                'is_archived'     => 0,
                'branch_id'       => 1,
                'created_at'      => $ts,
                'updated_at'      => $ts,
            ]);
            $coachIds[$c['code']] = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id", [])['id'];
        } else {
            $coachIds[$c['code']] = (int) $existing['id'];
        }
    }

    // Link coaches to swimming discipline
    foreach ($coachIds as $coachCode => $coachId) {
        $existing = $db->selectOne(
            "SELECT id FROM sa_coach_disciplines WHERE coach_id = ? AND discipline_id = ?",
            [$coachId, $swimId]
        );
        if (!$existing) {
            $db->insert('sa_coach_disciplines', [
                'coach_id'             => $coachId,
                'discipline_id'        => $swimId,
                'specialization_level' => 'primary',
            ]);
        }
    }

    // ══════════════════════════════════════════════════════════════════
    // 7. PROGRAMS — Swimming Training Programs
    // ══════════════════════════════════════════════════════════════════
    $programs = [
        ['code' => 'SWIM-BEG', 'name_ar' => 'تعليم سباحة — مبتدئين', 'name_en' => 'Swimming Beginners', 'type' => 'training', 'age_from' => 5, 'age_to' => 12, 'skill' => 'beginner', 'duration' => 45, 'per_week' => 3],
        ['code' => 'SWIM-INT', 'name_ar' => 'سباحة متوسط', 'name_en' => 'Swimming Intermediate', 'type' => 'training', 'age_from' => 8, 'age_to' => 16, 'skill' => 'intermediate', 'duration' => 60, 'per_week' => 3],
        ['code' => 'SWIM-ADV', 'name_ar' => 'سباحة متقدم', 'name_en' => 'Swimming Advanced', 'type' => 'competitive', 'age_from' => 10, 'age_to' => 18, 'skill' => 'advanced', 'duration' => 90, 'per_week' => 5],
        ['code' => 'SWIM-FIT', 'name_ar' => 'سباحة لياقة — كبار', 'name_en' => 'Adult Fitness Swimming', 'type' => 'recreational', 'age_from' => 18, 'age_to' => 65, 'skill' => 'beginner', 'duration' => 60, 'per_week' => 3],
    ];

    $programIds = [];
    foreach ($programs as $p) {
        $existing = $db->selectOne("SELECT id FROM sa_programs WHERE code = ?", [$p['code']]);
        if (!$existing) {
            $db->insert('sa_programs', [
                'code'                     => $p['code'],
                'name_ar'                  => $p['name_ar'],
                'name_en'                  => $p['name_en'],
                'discipline_id'            => $swimId,
                'academy_id'               => null,
                'program_type'             => $p['type'],
                'age_from'                 => $p['age_from'],
                'age_to'                   => $p['age_to'],
                'gender_restriction'       => null,
                'skill_level'              => $p['skill'],
                'description_ar'           => 'برنامج ' . $p['name_ar'],
                'session_duration_minutes' => $p['duration'],
                'sessions_per_week'        => $p['per_week'],
                'is_active'                => 1,
                'is_archived'              => 0,
                'created_at'               => $ts,
                'updated_at'               => $ts,
            ]);
            $programIds[$p['code']] = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id", [])['id'];
        } else {
            $programIds[$p['code']] = (int) $existing['id'];
        }
    }

    // ══════════════════════════════════════════════════════════════════
    // 8. GROUPS — Training Groups with Schedules
    // ══════════════════════════════════════════════════════════════════
    $groups = [
        // Beginners — 2 groups
        ['code' => 'GRP-SWIM-B1', 'name_ar' => 'مبتدئين أ (أحد-ثلاثاء-خميس)', 'program' => 'SWIM-BEG', 'coach' => 'COACH-SWIM-02', 'fee_m' => 800, 'fee_nm' => 1200, 'days' => [0,2,4], 'start' => '09:00:00', 'end' => '09:45:00', 'lanes' => ['LANE-1','LANE-2']],
        ['code' => 'GRP-SWIM-B2', 'name_ar' => 'مبتدئين ب (اثنين-أربعاء-سبت)', 'program' => 'SWIM-BEG', 'coach' => 'COACH-SWIM-04', 'fee_m' => 800, 'fee_nm' => 1200, 'days' => [1,3,6], 'start' => '10:00:00', 'end' => '10:45:00', 'lanes' => ['LANE-1','LANE-2']],
        // Intermediate
        ['code' => 'GRP-SWIM-I1', 'name_ar' => 'متوسط أ (أحد-ثلاثاء-خميس)', 'program' => 'SWIM-INT', 'coach' => 'COACH-SWIM-01', 'fee_m' => 1000, 'fee_nm' => 1500, 'days' => [0,2,4], 'start' => '15:00:00', 'end' => '16:00:00', 'lanes' => ['LANE-3','LANE-4']],
        ['code' => 'GRP-SWIM-I2', 'name_ar' => 'متوسط ب (اثنين-أربعاء-سبت)', 'program' => 'SWIM-INT', 'coach' => 'COACH-SWIM-03', 'fee_m' => 1000, 'fee_nm' => 1500, 'days' => [1,3,6], 'start' => '15:00:00', 'end' => '16:00:00', 'lanes' => ['LANE-3','LANE-4']],
        // Advanced
        ['code' => 'GRP-SWIM-A1', 'name_ar' => 'متقدم — فريق السباحة', 'program' => 'SWIM-ADV', 'coach' => 'COACH-SWIM-01', 'fee_m' => 1500, 'fee_nm' => 2200, 'days' => [0,1,2,3,4], 'start' => '06:00:00', 'end' => '07:30:00', 'lanes' => ['LANE-4','LANE-5','LANE-6']],
        // Fitness adults
        ['code' => 'GRP-SWIM-F1', 'name_ar' => 'لياقة كبار (مسائي)', 'program' => 'SWIM-FIT', 'coach' => 'COACH-SWIM-03', 'fee_m' => 600, 'fee_nm' => 900, 'days' => [0,2,4], 'start' => '19:00:00', 'end' => '20:00:00', 'lanes' => ['LANE-7','LANE-8']],
    ];

    $seasonStart = date('Y-m-01');
    $seasonEnd = date('Y-12-31');

    foreach ($groups as $g) {
        $existing = $db->selectOne("SELECT id FROM sa_groups WHERE code = ?", [$g['code']]);
        if (!$existing) {
            $db->insert('sa_groups', [
                'code'                   => $g['code'],
                'name_ar'                => $g['name_ar'],
                'program_id'             => $programIds[$g['program']],
                'coach_id'               => $coachIds[$g['coach']],
                'min_capacity'           => 4,
                'max_capacity'           => 12,
                'current_count'          => 0,
                'is_full'                => 0,
                'monthly_fee_member'     => $g['fee_m'],
                'monthly_fee_nonmember'  => $g['fee_nm'],
                'season_start'           => $seasonStart,
                'season_end'             => $seasonEnd,
                'status'                 => 'active',
                'is_archived'            => 0,
                'created_at'             => $ts,
                'updated_at'             => $ts,
            ]);
            $groupId = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id", [])['id'];
        } else {
            $groupId = (int) $existing['id'];
        }

        // Insert schedule entries for this group
        foreach ($g['days'] as $day) {
            foreach ($g['lanes'] as $laneCode) {
                $laneId = $laneIds[$laneCode];
                $existingSch = $db->selectOne(
                    "SELECT id FROM sa_group_schedule WHERE group_id = ? AND facility_unit_id = ? AND day_of_week = ? AND start_time = ?",
                    [$groupId, $laneId, $day, $g['start']]
                );
                if (!$existingSch) {
                    $db->insert('sa_group_schedule', [
                        'group_id'         => $groupId,
                        'facility_unit_id' => $laneId,
                        'day_of_week'      => $day,
                        'start_time'       => $g['start'],
                        'end_time'         => $g['end'],
                        'is_active'        => 1,
                    ]);
                }
            }
        }
    }

    // ══════════════════════════════════════════════════════════════════
    // 9. SAMPLE PLAYERS — 20 registered swimmers
    // ══════════════════════════════════════════════════════════════════
    $players = [
        ['name_ar' => 'يوسف أحمد محمد', 'type' => 'member', 'gender' => 'male', 'dob' => '2012-03-15', 'nid' => '31203151234567', 'phone' => '01112345001'],
        ['name_ar' => 'مريم خالد حسن', 'type' => 'member', 'gender' => 'female', 'dob' => '2011-07-22', 'nid' => '31107221234567', 'phone' => '01112345002'],
        ['name_ar' => 'عمر محمود سعيد', 'type' => 'non_member', 'gender' => 'male', 'dob' => '2013-01-10', 'nid' => '31301101234567', 'phone' => '01112345003'],
        ['name_ar' => 'فاطمة علي إبراهيم', 'type' => 'member', 'gender' => 'female', 'dob' => '2010-11-05', 'nid' => '31011051234567', 'phone' => '01112345004'],
        ['name_ar' => 'أحمد حسام الدين', 'type' => 'member', 'gender' => 'male', 'dob' => '2009-06-18', 'nid' => '30906181234567', 'phone' => '01112345005'],
        ['name_ar' => 'نور الهدى سامي', 'type' => 'non_member', 'gender' => 'female', 'dob' => '2012-09-30', 'nid' => '31209301234567', 'phone' => '01112345006'],
        ['name_ar' => 'كريم عبدالرحمن', 'type' => 'member', 'gender' => 'male', 'dob' => '2008-04-12', 'nid' => '30804121234567', 'phone' => '01112345007'],
        ['name_ar' => 'جنى محمد فوزي', 'type' => 'member', 'gender' => 'female', 'dob' => '2010-12-25', 'nid' => '31012251234567', 'phone' => '01112345008'],
        ['name_ar' => 'ياسين طارق', 'type' => 'non_member', 'gender' => 'male', 'dob' => '2011-02-14', 'nid' => '31102141234567', 'phone' => '01112345009'],
        ['name_ar' => 'سلمى وليد نبيل', 'type' => 'member', 'gender' => 'female', 'dob' => '2013-08-07', 'nid' => '31308071234567', 'phone' => '01112345010'],
        ['name_ar' => 'حسن محمد رضا', 'type' => 'member', 'gender' => 'male', 'dob' => '2007-05-20', 'nid' => '30705201234567', 'phone' => '01112345011'],
        ['name_ar' => 'ريم أشرف سعد', 'type' => 'member', 'gender' => 'female', 'dob' => '2008-10-03', 'nid' => '30810031234567', 'phone' => '01112345012'],
        ['name_ar' => 'عبدالله سمير', 'type' => 'non_member', 'gender' => 'male', 'dob' => '2006-01-28', 'nid' => '30601281234567', 'phone' => '01112345013'],
        ['name_ar' => 'هنا وائل عبدالحميد', 'type' => 'member', 'gender' => 'female', 'dob' => '2007-07-16', 'nid' => '30707161234567', 'phone' => '01112345014'],
        ['name_ar' => 'محمد أيمن', 'type' => 'member', 'gender' => 'male', 'dob' => '1985-03-10', 'nid' => '28503101234567', 'phone' => '01112345015'],
        ['name_ar' => 'منى حسين', 'type' => 'member', 'gender' => 'female', 'dob' => '1990-11-22', 'nid' => '29011221234567', 'phone' => '01112345016'],
        ['name_ar' => 'طارق عبدالعزيز', 'type' => 'non_member', 'gender' => 'male', 'dob' => '1982-06-05', 'nid' => '28206051234567', 'phone' => '01112345017'],
        ['name_ar' => 'ليلى فريد', 'type' => 'member', 'gender' => 'female', 'dob' => '1995-09-18', 'nid' => '29509181234567', 'phone' => '01112345018'],
        ['name_ar' => 'مصطفى جمال', 'type' => 'member', 'gender' => 'male', 'dob' => '1988-12-01', 'nid' => '28812011234567', 'phone' => '01112345019'],
        ['name_ar' => 'دينا محمود', 'type' => 'non_member', 'gender' => 'female', 'dob' => '1993-04-14', 'nid' => '29304141234567', 'phone' => '01112345020'],
    ];

    $playerIds = [];
    $serial = (int) ($db->selectOne("SELECT COUNT(*) as cnt FROM sa_players", [])['cnt'] ?? 0);
    foreach ($players as $p) {
        $existing = $db->selectOne("SELECT id FROM sa_players WHERE national_id = ?", [$p['nid']]);
        if (!$existing) {
            $serial++;
            $db->insert('sa_players', [
                'player_type'          => $p['type'],
                'registration_serial'  => 'SAP-' . str_pad((string) $serial, 5, '0', STR_PAD_LEFT),
                'full_name_ar'         => $p['name_ar'],
                'national_id'          => $p['nid'],
                'date_of_birth'        => $p['dob'],
                'gender'               => $p['gender'],
                'phone'                => $p['phone'],
                'medical_status'       => 'fit',
                'medical_expiry_date'  => date('Y-m-d', strtotime('+1 year')),
                'card_status'          => 'active',
                'registration_fee_paid'=> 1,
                'is_archived'          => 0,
                'branch_id'            => 1,
                'created_at'           => $ts,
                'updated_at'           => $ts,
            ]);
            $playerIds[] = (int) $db->selectOne("SELECT LAST_INSERT_ID() as id", [])['id'];
        } else {
            $playerIds[] = (int) $existing['id'];
        }
    }

    // ══════════════════════════════════════════════════════════════════
    // 10. ENROLL PLAYERS IN GROUPS
    // ══════════════════════════════════════════════════════════════════
    $groupCodes = ['GRP-SWIM-B1', 'GRP-SWIM-B2', 'GRP-SWIM-I1', 'GRP-SWIM-I2', 'GRP-SWIM-A1', 'GRP-SWIM-F1'];

    // Distribute players across groups
    $assignments = [
        'GRP-SWIM-B1' => array_slice($playerIds, 0, 4),    // First 4 kids → beginners A
        'GRP-SWIM-B2' => array_slice($playerIds, 4, 3),    // Next 3 → beginners B
        'GRP-SWIM-I1' => array_slice($playerIds, 7, 3),    // Next 3 → intermediate A
        'GRP-SWIM-I2' => array_slice($playerIds, 10, 4),   // Next 4 → intermediate B
        'GRP-SWIM-A1' => array_slice($playerIds, 10, 4),   // Same 4 older kids → advanced
        'GRP-SWIM-F1' => array_slice($playerIds, 14, 6),   // Last 6 adults → fitness
    ];

    foreach ($assignments as $gCode => $pIds) {
        $gRow = $db->selectOne("SELECT id FROM sa_groups WHERE code = ?", [$gCode]);
        if (!$gRow) continue;
        $gId = (int) $gRow['id'];

        foreach ($pIds as $pId) {
            $existing = $db->selectOne(
                "SELECT id FROM sa_group_players WHERE group_id = ? AND player_id = ? AND status = 'active'",
                [$gId, $pId]
            );
            if (!$existing) {
                $db->insert('sa_group_players', [
                    'group_id'    => $gId,
                    'player_id'   => $pId,
                    'enrolled_at' => $today,
                    'status'      => 'active',
                ]);
            }
        }

        // Update group count
        $count = (int) ($db->selectOne(
            "SELECT COUNT(*) as cnt FROM sa_group_players WHERE group_id = ? AND status = 'active'",
            [$gId]
        )['cnt'] ?? 0);
        $db->update('sa_groups', [
            'current_count' => $count,
            'is_full'       => $count >= 12 ? 1 : 0,
        ], 'id = ?', [$gId]);
    }

    // ══════════════════════════════════════════════════════════════════
    // 11. SAMPLE BOOKINGS — Training sessions for this week + hourly
    // ══════════════════════════════════════════════════════════════════
    // Generate training bookings for the current week (Sun-Sat)
    $weekStart = date('Y-m-d', strtotime('last sunday'));
    if (date('w') == 0) $weekStart = $today;

    $bookingNum = (int) ($db->selectOne("SELECT COUNT(*) as cnt FROM sa_bookings", [])['cnt'] ?? 0);

    foreach ($groups as $g) {
        $gRow = $db->selectOne("SELECT id FROM sa_groups WHERE code = ?", [$g['code']]);
        if (!$gRow) continue;
        $gId = (int) $gRow['id'];

        foreach ($g['days'] as $dayOfWeek) {
            $bookDate = date('Y-m-d', strtotime($weekStart . " +{$dayOfWeek} days"));
            if ($bookDate > date('Y-m-d', strtotime($weekStart . ' +6 days'))) continue;

            // One booking per lane for training
            foreach ($g['lanes'] as $laneCode) {
                $laneId = $laneIds[$laneCode];
                $existing = $db->selectOne(
                    "SELECT id FROM sa_bookings WHERE facility_unit_id = ? AND booking_date = ? AND start_time = ? AND booking_type = 'training' AND status != 'cancelled'",
                    [$laneId, $bookDate, $g['start']]
                );
                if (!$existing) {
                    $bookingNum++;
                    $db->insert('sa_bookings', [
                        'booking_number'    => 'BK-' . str_pad((string) $bookingNum, 6, '0', STR_PAD_LEFT),
                        'facility_unit_id'  => $laneId,
                        'booking_type'      => 'training',
                        'booking_date'      => $bookDate,
                        'start_time'        => $g['start'],
                        'end_time'          => $g['end'],
                        'group_id'          => $gId,
                        'coach_id'          => $coachIds[$g['coach']],
                        'booker_type'       => 'academy',
                        'booker_name'       => 'تمرين: ' . $g['name_ar'],
                        'participant_count'  => 6,
                        'spots_reserved'    => 6,
                        'status'            => $bookDate < $today ? 'completed' : 'confirmed',
                        'payment_status'    => 'paid',
                        'branch_id'         => 1,
                        'created_at'        => $ts,
                        'updated_at'        => $ts,
                    ]);
                }
            }
        }
    }

    // Add some hourly bookings for today/tomorrow
    $hourlyBookings = [
        ['lane' => 'LANE-5', 'date' => $today, 'start' => '10:00:00', 'end' => '11:00:00', 'name' => 'حسام كمال', 'count' => 2, 'type' => 'member'],
        ['lane' => 'LANE-6', 'date' => $today, 'start' => '10:00:00', 'end' => '11:00:00', 'name' => 'خالد عبدالله', 'count' => 3, 'type' => 'non_member'],
        ['lane' => 'LANE-7', 'date' => $today, 'start' => '11:00:00', 'end' => '12:00:00', 'name' => 'سمير فؤاد', 'count' => 4, 'type' => 'member'],
        ['lane' => 'LANE-8', 'date' => $today, 'start' => '14:00:00', 'end' => '15:00:00', 'name' => 'ريهام ناصر', 'count' => 2, 'type' => 'member'],
        ['lane' => 'LANE-5', 'date' => date('Y-m-d', strtotime('+1 day')), 'start' => '09:00:00', 'end' => '10:00:00', 'name' => 'وليد شكري', 'count' => 5, 'type' => 'non_member'],
        ['lane' => 'LANE-6', 'date' => date('Y-m-d', strtotime('+1 day')), 'start' => '16:00:00', 'end' => '17:00:00', 'name' => 'أمينة صلاح', 'count' => 3, 'type' => 'member'],
    ];

    foreach ($hourlyBookings as $hb) {
        $laneId = $laneIds[$hb['lane']];
        $existing = $db->selectOne(
            "SELECT id FROM sa_bookings WHERE facility_unit_id = ? AND booking_date = ? AND start_time = ? AND booking_type = 'hourly' AND status != 'cancelled'",
            [$laneId, $hb['date'], $hb['start']]
        );
        if (!$existing) {
            $bookingNum++;
            $db->insert('sa_bookings', [
                'booking_number'    => 'BK-' . str_pad((string) $bookingNum, 6, '0', STR_PAD_LEFT),
                'facility_unit_id'  => $laneId,
                'booking_type'      => 'hourly',
                'booking_date'      => $hb['date'],
                'start_time'        => $hb['start'],
                'end_time'          => $hb['end'],
                'booker_type'       => $hb['type'] === 'member' ? 'member' : 'guest',
                'booker_name'       => $hb['name'],
                'participant_count' => $hb['count'],
                'spots_reserved'    => $hb['count'],
                'total_amount'      => $hb['count'] * ($hb['type'] === 'member' ? 120 : 180),
                'status'            => 'confirmed',
                'payment_status'    => 'paid',
                'branch_id'         => 1,
                'created_at'        => $ts,
                'updated_at'        => $ts,
            ]);
        }
    }

    // ══════════════════════════════════════════════════════════════════
    // 12. BLACKOUT DATES — Maintenance next Monday
    // ══════════════════════════════════════════════════════════════════
    $nextMonday = date('Y-m-d', strtotime('next monday'));
    $existing = $db->selectOne(
        "SELECT id FROM sa_blackout_dates WHERE facility_id = ? AND blackout_date = ?",
        [$poolId, $nextMonday]
    );
    if (!$existing) {
        $db->insert('sa_blackout_dates', [
            'facility_id'   => $poolId,
            'blackout_date' => $nextMonday,
            'start_time'    => '06:00:00',
            'end_time'      => '10:00:00',
            'reason'        => 'صيانة دورية — تنظيف الفلاتر',
            'created_at'    => $ts,
        ]);
    }
};
