<?php
declare(strict_types=1);

/**
 * Phase 46: Subscription Rates & Membership Prices
 *
 * Seeds annual subscription rates per financial year (2023–2025),
 * current membership prices (with historical entries), and
 * the new numbering system business rule.
 */

return function (\App\Core\Database $db) {
    $now = date('Y-m-d H:i:s');

    // ─── Check service_catalog table exists ────────────────────────────────────
    $tableExists = $db->selectOne(
        "SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'service_catalog'"
    );
    if (!$tableExists) {
        echo "  [SKIP] service_catalog table does not exist.\n";
        return;
    }

    // ─── 1. Annual subscription rates per financial year ────────────────────────

    $annualRates = [
        // FY 2023 (2023-07-01 to 2024-06-30)
        ['SVC_ANNUAL_MEMBER_2023', 'اشتراك سنوي - عضو 2023', 'Annual Subscription - Member 2023', 410.00, '2023-07-01', '2024-06-30'],
        ['SVC_ANNUAL_SPOUSE_2023', 'اشتراك سنوي - زوج/ة 2023', 'Annual Subscription - Spouse 2023', 410.00, '2023-07-01', '2024-06-30'],
        ['SVC_ANNUAL_CHILD_2023', 'اشتراك سنوي - ابن 2023', 'Annual Subscription - Child 2023', 185.00, '2023-07-01', '2024-06-30'],
        ['SVC_ANNUAL_TEMP_2023', 'اشتراك سنوي - مؤقت 2023', 'Annual Subscription - Temp 2023', 185.00, '2023-07-01', '2024-06-30'],

        // FY 2024 (2024-07-01 to 2025-06-30)
        ['SVC_ANNUAL_MEMBER_2024', 'اشتراك سنوي - عضو 2024', 'Annual Subscription - Member 2024', 410.00, '2024-07-01', '2025-06-30'],
        ['SVC_ANNUAL_SPOUSE_2024', 'اشتراك سنوي - زوج/ة 2024', 'Annual Subscription - Spouse 2024', 410.00, '2024-07-01', '2025-06-30'],
        ['SVC_ANNUAL_CHILD_2024', 'اشتراك سنوي - ابن 2024', 'Annual Subscription - Child 2024', 185.00, '2024-07-01', '2025-06-30'],
        ['SVC_ANNUAL_TEMP_2024', 'اشتراك سنوي - مؤقت 2024', 'Annual Subscription - Temp 2024', 185.00, '2024-07-01', '2025-06-30'],

        // FY 2025 (2025-07-01 to 2026-06-30) — 20% increase
        ['SVC_ANNUAL_MEMBER_2025', 'اشتراك سنوي - عضو 2025', 'Annual Subscription - Member 2025', 492.00, '2025-07-01', '2026-06-30'],
        ['SVC_ANNUAL_SPOUSE_2025', 'اشتراك سنوي - زوج/ة 2025', 'Annual Subscription - Spouse 2025', 492.00, '2025-07-01', '2026-06-30'],
        ['SVC_ANNUAL_CHILD_2025', 'اشتراك سنوي - ابن 2025', 'Annual Subscription - Child 2025', 222.00, '2025-07-01', '2026-06-30'],
        ['SVC_ANNUAL_TEMP_2025', 'اشتراك سنوي - مؤقت 2025', 'Annual Subscription - Temp 2025', 222.00, '2025-07-01', '2026-06-30'],

        // General fallback rates (no effective_to)
        ['SVC_ANNUAL_MEMBER', 'اشتراك سنوي - عضو', 'Annual Subscription - Member', 492.00, '2025-07-01', null],
        ['SVC_ANNUAL_SPOUSE', 'اشتراك سنوي - زوج/ة', 'Annual Subscription - Spouse', 492.00, '2025-07-01', null],
        ['SVC_ANNUAL_CHILD', 'اشتراك سنوي - ابن', 'Annual Subscription - Child', 222.00, '2025-07-01', null],
        ['SVC_ANNUAL_TEMP', 'اشتراك سنوي - مؤقت', 'Annual Subscription - Temp', 222.00, '2025-07-01', null],
    ];

    foreach ($annualRates as [$code, $nameAr, $nameEn, $amount, $from, $to]) {
        $db->query(
            "INSERT INTO service_catalog (service_code, name_ar, name_en, base_amount, branch_id, effective_from, effective_to, is_active, created_at, updated_at)
             VALUES (?, ?, ?, ?, NULL, ?, ?, 1, ?, ?)
             ON DUPLICATE KEY UPDATE
                name_ar = VALUES(name_ar),
                name_en = VALUES(name_en),
                base_amount = VALUES(base_amount),
                effective_to = VALUES(effective_to),
                is_active = 1,
                updated_at = VALUES(updated_at)",
            [$code, $nameAr, $nameEn, $amount, $from, $to, $now, $now]
        );
    }

    echo "  [OK] Annual subscription rates seeded (2023–2025 + fallback).\n";

    // ─── 2. Membership prices ───────────────────────────────────────────────────

    $membershipPrices = [
        // Current prices (effective 2024-07-01, no end date)
        ['SVC_MEMBERSHIP_HIGH_QUAL', 'رسوم عضوية - مؤهل عالي', 'Membership Fee - High Qualification', 150000.00, '2024-07-01', null],
        ['SVC_MEMBERSHIP_MED_QUAL', 'رسوم عضوية - مؤهل متوسط', 'Membership Fee - Medium Qualification', 225000.00, '2024-07-01', null],
        ['SVC_MEMBERSHIP_NO_QUAL', 'رسوم عضوية - بدون مؤهل', 'Membership Fee - No Qualification', 300000.00, '2024-07-01', null],

        // Historical prices (before 2024-07-01)
        ['SVC_MEMBERSHIP_HIGH_QUAL_OLD', 'رسوم عضوية - مؤهل عالي (قديم)', 'Membership Fee - High Qualification (Old)', 114000.00, '2023-01-01', '2024-06-30'],
        ['SVC_MEMBERSHIP_MED_QUAL_OLD', 'رسوم عضوية - مؤهل متوسط (قديم)', 'Membership Fee - Medium Qualification (Old)', 171000.00, '2023-01-01', '2024-06-30'],
        ['SVC_MEMBERSHIP_NO_QUAL_OLD', 'رسوم عضوية - بدون مؤهل (قديم)', 'Membership Fee - No Qualification (Old)', 228000.00, '2023-01-01', '2024-06-30'],
    ];

    foreach ($membershipPrices as [$code, $nameAr, $nameEn, $amount, $from, $to]) {
        $db->query(
            "INSERT INTO service_catalog (service_code, name_ar, name_en, base_amount, branch_id, effective_from, effective_to, is_active, created_at, updated_at)
             VALUES (?, ?, ?, ?, NULL, ?, ?, 1, ?, ?)
             ON DUPLICATE KEY UPDATE
                name_ar = VALUES(name_ar),
                name_en = VALUES(name_en),
                base_amount = VALUES(base_amount),
                effective_to = VALUES(effective_to),
                is_active = 1,
                updated_at = VALUES(updated_at)",
            [$code, $nameAr, $nameEn, $amount, $from, $to, $now, $now]
        );
    }

    echo "  [OK] Membership prices seeded (current + historical).\n";

    // ─── 3. Business rule: new numbering system ─────────────────────────────────

    $ruleTableExists = $db->selectOne(
        "SELECT 1 FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = 'business_rules'"
    );
    if (!$ruleTableExists) {
        echo "  [SKIP] business_rules table does not exist.\n";
        return;
    }

    $ruleCode = 'NEW_NUMBERING_START_DATE';
    $ruleValue = json_encode(['date' => '2026-07-01', 'format' => '2/{seq}', 'start_seq' => 1001], JSON_UNESCAPED_UNICODE);

    $existingRule = $db->selectOne(
        "SELECT id FROM business_rules WHERE rule_code = ? AND branch_id IS NULL",
        [$ruleCode]
    );

    if ($existingRule) {
        $db->update('business_rules', [
            'current_value_json' => $ruleValue,
            'updated_at'         => $now,
        ], 'id = ?', [(int) $existingRule['id']]);
    } else {
        $db->insert('business_rules', [
            'rule_code'          => $ruleCode,
            'category'           => 'workflow',
            'name_ar'            => 'تاريخ بدء نظام الترقيم الجديد',
            'name_en'            => 'New Numbering System Start Date',
            'description_ar'     => 'يحدد تاريخ بدء نظام الترقيم الجديد وصيغة الرقم ورقم البداية',
            'description_en'     => 'Defines the start date, format, and starting sequence for the new numbering system',
            'parameters_json'    => null,
            'current_value_json' => $ruleValue,
            'data_type'          => 'json',
            'branch_id'          => null,
            'effective_from'     => '2026-07-01',
            'effective_to'       => null,
            'is_active'          => 1,
            'version'            => 1,
            'created_at'         => $now,
            'updated_at'         => $now,
            'created_by'         => null,
            'updated_by'         => null,
        ]);
    }

    echo "  [OK] Business rule NEW_NUMBERING_START_DATE seeded.\n";

    // ─── 4. Separation fee tiers (رسوم الفصل) ─────────────────────────────────

    $separationRules = [
        ['SEPARATION_FEE_YEAR_1', 'رسم فصل - السنة الأولى', '{"percentage":"30"}'],
        ['SEPARATION_FEE_YEAR_2', 'رسم فصل - السنة الثانية', '{"percentage":"20"}'],
        ['SEPARATION_FEE_YEAR_3', 'رسم فصل - السنة الثالثة', '{"percentage":"15"}'],
        ['SEPARATION_FEE_YEAR_4', 'رسم فصل - السنة الرابعة', '{"percentage":"10"}'],
        ['SEPARATION_FEE_YEAR_5', 'رسم فصل - السنة الخامسة', '{"percentage":"5"}'],
        ['SEPARATION_FEE_YEAR_6_PLUS', 'رسم فصل - السنة السادسة فما فوق', '{"percentage":"2.5"}'],
    ];

    foreach ($separationRules as [$code, $nameAr, $value]) {
        $existing = $db->selectOne("SELECT id FROM business_rules WHERE rule_code = ? AND branch_id IS NULL", [$code]);
        if (!$existing) {
            $db->insert('business_rules', [
                'rule_code'          => $code,
                'category'           => 'transfer',
                'name_ar'            => $nameAr,
                'name_en'            => 'Separation Fee - ' . $code,
                'description_ar'     => 'نسبة رسم الفصل من قيمة العضوية الجديدة',
                'description_en'     => 'Separation fee percentage from current membership value',
                'parameters_json'    => null,
                'current_value_json' => $value,
                'data_type'          => 'json',
                'branch_id'          => null,
                'effective_from'     => '2024-07-01',
                'effective_to'       => null,
                'is_active'          => 1,
                'version'            => 1,
                'created_at'         => $now,
                'updated_at'         => $now,
                'created_by'         => null,
                'updated_by'         => null,
            ]);
        }
    }

    echo "  [OK] Separation fee tiers seeded (year 1-6+).\n";

    // ─── 5. Form fees & key business rules ────────────────────────────────────

    $miscRules = [
        ['FORM_NEW_MEMBERSHIP_FEE', 'رسم استمارة عضوية جديدة', '{"form_amount":"500","martyrs_stamp":"5","total":"505"}', 'membership'],
        ['FORM_ADDITION_FEE', 'رسم استمارة إضافة', '{"amount":"570"}', 'membership'],
        ['FORM_TRANSFER_FEE', 'رسم استمارة فصل/تحويل', '{"amount":"570"}', 'transfer'],
        ['TEMPORARY_MEMBER_FEE', 'رسم العضو المؤقت', '{"percentage":"10"}', 'membership'],
        ['NANNY_FEE', 'رسم المربية', '{"percentage":"5"}', 'membership'],
        ['WAIVER_FEE', 'رسم التنازل عن العضوية', '{"percentage":"30"}', 'transfer'],
        ['ATHLETIC_CONVERSION_FEE', 'رسم تحويل العضوية الرياضية', '{"percentage":"50","min_years":8}', 'transfer'],
        ['FOREIGN_MEMBER_FEE', 'رسم العضو الأجنبي', '{"fee_usd":"10000","currency":"USD"}', 'membership'],
        ['MALE_CHILD_FREEZE_AGE', 'سن تجميد عضوية الابن', '{"value":25}', 'workflow'],
        ['DIVORCE_REQUEST_WINDOW', 'مهلة طلب فصل العضوية بعد الطلاق', '{"max_years":1}', 'transfer'],
        ['DIVORCE_MIN_MEMBERSHIP_YEARS', 'حد أدنى سنوات عضوية للطلاق', '{"min_years":5,"waived_if_children":true}', 'transfer'],
        ['DIVORCE_SAME_FORM_FEE', 'رسم فصل زوج/ة بنفس الاستمارة', '{"percentage":"10"}', 'transfer'],
        ['DIVORCE_JOINED_AFTER_FEE', 'رسم فصل زوج/ة منضم بعد العضوية', '{"percentage":"50"}', 'transfer'],
        ['FINE_ACCUMULATION_MAX_YEARS', 'حد أقصى تراكم الغرامات', '{"max_years":5,"drop_after":true}', 'penalties'],
        ['MEMBERSHIP_DROP_UNPAID_YEARS', 'إسقاط العضوية لعدم السداد', '{"years":5}', 'penalties'],
        ['REINSTATEMENT_WINDOW', 'مهلة إعادة العضوية بعد الإسقاط', '{"max_years":1}', 'workflow'],
        ['DEVELOPMENT_FEE', 'رسوم تنمية', '{"amount":"35"}', 'subscription'],
    ];

    foreach ($miscRules as [$code, $nameAr, $value, $category]) {
        $existing = $db->selectOne("SELECT id FROM business_rules WHERE rule_code = ? AND branch_id IS NULL", [$code]);
        if (!$existing) {
            $db->insert('business_rules', [
                'rule_code'          => $code,
                'category'           => $category,
                'name_ar'            => $nameAr,
                'name_en'            => $code,
                'description_ar'     => $nameAr,
                'description_en'     => $code,
                'parameters_json'    => null,
                'current_value_json' => $value,
                'data_type'          => 'json',
                'branch_id'          => null,
                'effective_from'     => '2024-07-01',
                'effective_to'       => null,
                'is_active'          => 1,
                'version'            => 1,
                'created_at'         => $now,
                'updated_at'         => $now,
                'created_by'         => null,
                'updated_by'         => null,
            ]);
        }
    }

    echo "  [OK] All business rules seeded (forms, fees, transfers, penalties).\n";

    // ─── 6. Subscription year adjustment rules ────────────────────────────────

    $yearAdjustments = [
        ['SUBSCRIPTION_YEAR_ADJUSTMENT_2023', 'تعديل اشتراك 2023 - خصم 50%', '{"discount_percentage":"50","note":"خصم 50% مطبق"}'],
        ['SUBSCRIPTION_YEAR_ADJUSTMENT_2025', 'تعديل اشتراك 2025 - زيادة 20%', '{"increase_percentage":"20","note":"زيادة 20% عن السنة السابقة"}'],
    ];

    foreach ($yearAdjustments as [$code, $nameAr, $value]) {
        $existing = $db->selectOne("SELECT id FROM business_rules WHERE rule_code = ? AND branch_id IS NULL", [$code]);
        if (!$existing) {
            $db->insert('business_rules', [
                'rule_code'          => $code,
                'category'           => 'subscription',
                'name_ar'            => $nameAr,
                'name_en'            => $code,
                'description_ar'     => $nameAr,
                'description_en'     => 'Year-specific subscription adjustment',
                'parameters_json'    => null,
                'current_value_json' => $value,
                'data_type'          => 'json',
                'branch_id'          => null,
                'effective_from'     => '2024-07-01',
                'effective_to'       => null,
                'is_active'          => 1,
                'version'            => 1,
                'created_at'         => $now,
                'updated_at'         => $now,
                'created_by'         => null,
                'updated_by'         => null,
            ]);
        }
    }

    echo "  [OK] Subscription year adjustments seeded (2023 discount, 2025 increase).\n";

    // ─── 7. Acquired member children fee tiers (أبناء العضو المكتسب) ──────────

    $acquiredChildRules = [
        ['DIVORCE_CHILD_UNDER_12', 'رسم ابن مكتسب عضوية - أقل من 12', '{"percentage":"15"}'],
        ['DIVORCE_CHILD_12_TO_16', 'رسم ابن مكتسب عضوية - 12 إلى 16', '{"percentage":"20"}'],
        ['DIVORCE_CHILD_16_TO_18', 'رسم ابن مكتسب عضوية - 16 إلى 18', '{"percentage":"25"}'],
        ['DIVORCE_CHILD_OVER_18', 'رسم ابن مكتسب عضوية - فوق 18', '{"percentage":"30"}'],
    ];

    foreach ($acquiredChildRules as [$code, $nameAr, $value]) {
        $existing = $db->selectOne("SELECT id FROM business_rules WHERE rule_code = ? AND branch_id IS NULL", [$code]);
        if (!$existing) {
            $db->insert('business_rules', [
                'rule_code'          => $code,
                'category'           => 'transfer',
                'name_ar'            => $nameAr,
                'name_en'            => $code,
                'description_ar'     => 'نسبة رسوم إضافة أبناء العضو المكتسب بعد الانفصال',
                'description_en'     => 'Fee percentage for acquired member children after separation',
                'parameters_json'    => null,
                'current_value_json' => $value,
                'data_type'          => 'json',
                'branch_id'          => null,
                'effective_from'     => '2024-07-01',
                'effective_to'       => null,
                'is_active'          => 1,
                'version'            => 1,
                'created_at'         => $now,
                'updated_at'         => $now,
                'created_by'         => null,
                'updated_by'         => null,
            ]);
        }
    }

    echo "  [OK] Acquired member children fee tiers seeded.\n";
};
