<?php
declare(strict_types=1);

/**
 * Phase 39: Add form-session rules + fix CHILD_INCLUDED_MAX_COUNT.
 *
 * Business requirement:
 * - Initial membership form (505 EGP) includes 1 spouse + 2 children under 18 free.
 * - After activation, any modification needs a 570 EGP "addition form".
 * - Multiple additions within the SAME form session share one form fee.
 * - Form validity days controls how long an addition form stays open.
 */

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

    // ── New rules ────────────────────────────────────────────────────
    $newRules = [
        [
            'rule_code'          => 'INITIAL_FREE_SPOUSES_COUNT',
            'category'           => 'spouse_fee',
            'name_ar'            => 'عدد الزوجات المشمولات مجاناً في الاستمارة الأولى',
            'name_en'            => 'Free Spouses on Initial Form',
            'data_type'          => 'integer',
            'current_value_json' => '{"value":1}',
            'parameters_json'    => '{"value":"integer"}',
        ],
        [
            'rule_code'          => 'INITIAL_FREE_CHILDREN_COUNT',
            'category'           => 'children_fee',
            'name_ar'            => 'عدد الأبناء المشمولين مجاناً في الاستمارة الأولى (تحت السن)',
            'name_en'            => 'Free Children on Initial Form',
            'data_type'          => 'integer',
            'current_value_json' => '{"value":2}',
            'parameters_json'    => '{"value":"integer"}',
        ],
        [
            'rule_code'          => 'ADDITION_FORM_VALIDITY_DAYS',
            'category'           => 'financial',
            'name_ar'            => 'مدة صلاحية استمارة الإضافة/التعديل (أيام)',
            'name_en'            => 'Addition Form Validity Days',
            'data_type'          => 'integer',
            'current_value_json' => '{"value":30}',
            'parameters_json'    => '{"value":"integer"}',
        ],
    ];

    foreach ($newRules as $rule) {
        $exists = $db->selectOne(
            "SELECT id FROM business_rules WHERE rule_code = ? AND branch_id IS NULL",
            [$rule['rule_code']]
        );
        if (!$exists) {
            $db->insert('business_rules', array_merge($rule, [
                'branch_id'      => null,
                'effective_from' => $today,
                'effective_to'   => null,
                'version'        => 1,
                'is_active'      => 1,
                'created_at'     => $now,
                'updated_at'     => $now,
            ]));
        }
    }

    // ── Update CHILD_INCLUDED_MAX_COUNT from 3 → 2 ──────────────────
    // The club rule is: first 2 children under 18 are free on the initial form.
    // The existing seed had 3. We correct it here.
    $childRule = $db->selectOne(
        "SELECT id, current_value_json, version FROM business_rules WHERE rule_code = 'CHILD_INCLUDED_MAX_COUNT' AND branch_id IS NULL AND is_active = 1"
    );
    if ($childRule) {
        $currentValue = json_decode($childRule['current_value_json'], true);
        if (($currentValue['value'] ?? 3) === 3) {
            $newVersion = (int) $childRule['version'] + 1;
            $db->insert('rule_versions', [
                'rule_id'        => (int) $childRule['id'],
                'version_number' => $newVersion,
                'old_value_json' => $childRule['current_value_json'],
                'new_value_json' => '{"value":2}',
                'changed_by'     => null,
                'changed_at'     => $now,
                'change_reason'  => 'تصحيح: القاعدة الصحيحة هي طفلين مشمولين مجاناً وليس 3',
            ]);
            $db->update('business_rules', [
                'current_value_json' => '{"value":2}',
                'version'            => $newVersion,
                'updated_at'         => $now,
            ], '`id` = ?', [(int) $childRule['id']]);
        }
    }
};
