<?php
declare(strict_types=1);

use App\Core\Database;

/**
 * Demo data seeder for El Captain.
 * Creates fake members, subscriptions, and transactions for the demo instance.
 */
return function (Database $db): void {
    $existing = $db->selectOne("SELECT COUNT(*) as cnt FROM members");
    if ($existing && (int)$existing['cnt'] > 5) {
        return; // Already seeded
    }

    $branchId = (int)($db->selectOne("SELECT id FROM branches LIMIT 1")['id'] ?? 1);

    // --- Demo Members ---
    $members = [
        ['full_name_ar' => 'أحمد محمد علي',       'full_name_en' => 'Ahmed Mohamed Ali',       'national_id' => '29001011234567', 'phone' => '01001234567', 'gender' => 'male',   'membership_type' => 'regular'],
        ['full_name_ar' => 'سارة أحمد حسن',       'full_name_en' => 'Sara Ahmed Hassan',       'national_id' => '29205021234567', 'phone' => '01012345678', 'gender' => 'female', 'membership_type' => 'regular'],
        ['full_name_ar' => 'محمود خالد إبراهيم',   'full_name_en' => 'Mahmoud Khaled Ibrahim',  'national_id' => '28803031234567', 'phone' => '01112345678', 'gender' => 'male',   'membership_type' => 'vip'],
        ['full_name_ar' => 'فاطمة عبدالله محمد',   'full_name_en' => 'Fatma Abdullah Mohamed',  'national_id' => '29507041234567', 'phone' => '01212345678', 'gender' => 'female', 'membership_type' => 'regular'],
        ['full_name_ar' => 'عمر حسام الدين',       'full_name_en' => 'Omar Hossam Eldin',       'national_id' => '29009051234567', 'phone' => '01512345678', 'gender' => 'male',   'membership_type' => 'vip'],
        ['full_name_ar' => 'نور الهدى سمير',       'full_name_en' => 'Nour El Hoda Samir',      'national_id' => '29301061234567', 'phone' => '01023456789', 'gender' => 'female', 'membership_type' => 'regular'],
        ['full_name_ar' => 'يوسف عادل فهمي',       'full_name_en' => 'Youssef Adel Fahmy',      'national_id' => '28506071234567', 'phone' => '01123456789', 'gender' => 'male',   'membership_type' => 'regular'],
        ['full_name_ar' => 'مريم طارق سعيد',       'full_name_en' => 'Mariam Tarek Saeed',      'national_id' => '29708081234567', 'phone' => '01223456789', 'gender' => 'female', 'membership_type' => 'regular'],
        ['full_name_ar' => 'كريم وليد حسن',        'full_name_en' => 'Karim Waleed Hassan',     'national_id' => '29102091234567', 'phone' => '01523456789', 'gender' => 'male',   'membership_type' => 'vip'],
        ['full_name_ar' => 'هبة مصطفى نبيل',       'full_name_en' => 'Heba Mostafa Nabil',      'national_id' => '29404101234567', 'phone' => '01034567890', 'gender' => 'female', 'membership_type' => 'regular'],
        ['full_name_ar' => 'حسن علاء محمود',       'full_name_en' => 'Hassan Alaa Mahmoud',     'national_id' => '28801111234567', 'phone' => '01134567890', 'gender' => 'male',   'membership_type' => 'regular'],
        ['full_name_ar' => 'دينا شريف أحمد',       'full_name_en' => 'Dina Sherif Ahmed',       'national_id' => '29606121234567', 'phone' => '01234567890', 'gender' => 'female', 'membership_type' => 'vip'],
        ['full_name_ar' => 'تامر جمال عبدالرحمن',   'full_name_en' => 'Tamer Gamal Abdelrahman', 'national_id' => '28703131234567', 'phone' => '01534567890', 'gender' => 'male',   'membership_type' => 'regular'],
        ['full_name_ar' => 'ياسمين حاتم فؤاد',     'full_name_en' => 'Yasmine Hatem Fouad',     'national_id' => '29808141234567', 'phone' => '01045678901', 'gender' => 'female', 'membership_type' => 'regular'],
        ['full_name_ar' => 'عبدالرحمن سامي خليل',  'full_name_en' => 'Abdelrahman Samy Khalil', 'national_id' => '29205151234567', 'phone' => '01145678901', 'gender' => 'male',   'membership_type' => 'regular'],
    ];

    $memberIds = [];
    $memberNumber = 1001;

    foreach ($members as $m) {
        $existingMember = $db->selectOne("SELECT id FROM members WHERE national_id = ?", [$m['national_id']]);
        if ($existingMember) {
            $memberIds[] = (int)$existingMember['id'];
            $memberNumber++;
            continue;
        }

        $id = $db->insert('members', [
            'membership_number' => (string)$memberNumber,
            'full_name_ar'      => $m['full_name_ar'],
            'full_name_en'      => $m['full_name_en'],
            'national_id'       => $m['national_id'],
            'phone'             => $m['phone'],
            'gender'            => $m['gender'],
            'membership_type'   => $m['membership_type'],
            'branch_id'         => $branchId,
            'status'            => 'active',
            'join_date'         => date('Y-m-d', strtotime('-' . rand(30, 365) . ' days')),
            'created_at'        => date('Y-m-d H:i:s'),
            'updated_at'        => date('Y-m-d H:i:s'),
        ]);
        $memberIds[] = $id;
        $memberNumber++;
    }

    // --- Demo Subscriptions ---
    $subscriptionTypes = ['monthly', 'quarterly', 'annual'];
    foreach ($memberIds as $i => $memberId) {
        $type = $subscriptionTypes[$i % 3];
        $startDate = date('Y-m-d', strtotime('-' . rand(1, 60) . ' days'));
        $endDate = match($type) {
            'monthly'   => date('Y-m-d', strtotime($startDate . ' +1 month')),
            'quarterly' => date('Y-m-d', strtotime($startDate . ' +3 months')),
            'annual'    => date('Y-m-d', strtotime($startDate . ' +1 year')),
        };
        $amount = match($type) {
            'monthly'   => 500.00,
            'quarterly' => 1350.00,
            'annual'    => 5000.00,
        };

        $existing = $db->selectOne(
            "SELECT id FROM subscriptions WHERE member_id = ? AND start_date = ?",
            [$memberId, $startDate]
        );
        if ($existing) continue;

        $db->insert('subscriptions', [
            'member_id'         => $memberId,
            'subscription_type' => $type,
            'start_date'        => $startDate,
            'end_date'          => $endDate,
            'amount'            => $amount,
            'status'            => 'active',
            'created_at'        => date('Y-m-d H:i:s'),
            'updated_at'        => date('Y-m-d H:i:s'),
        ]);
    }

    // --- Demo Payments/Receipts ---
    $paymentMethods = ['cash', 'card', 'bank_transfer'];
    foreach ($memberIds as $i => $memberId) {
        $amount = match($i % 3) {
            0 => 500.00,
            1 => 1350.00,
            2 => 5000.00,
        };

        $existing = $db->selectOne(
            "SELECT id FROM receipts WHERE member_id = ? LIMIT 1",
            [$memberId]
        );
        if ($existing) continue;

        $db->insert('receipts', [
            'member_id'      => $memberId,
            'receipt_number' => 'RCP-' . str_pad((string)($i + 1), 6, '0', STR_PAD_LEFT),
            'amount'         => $amount,
            'payment_method' => $paymentMethods[$i % 3],
            'description'    => 'اشتراك ' . match($i % 3) { 0 => 'شهري', 1 => 'ربع سنوي', 2 => 'سنوي' },
            'paid_at'        => date('Y-m-d H:i:s', strtotime('-' . rand(1, 30) . ' days')),
            'created_by'     => 1,
            'created_at'     => date('Y-m-d H:i:s'),
            'updated_at'     => date('Y-m-d H:i:s'),
        ]);
    }
};
