<?php
declare(strict_types=1);

/**
 * Phase 41: System Unification — Missing Business Rules
 *
 * Adds rules that were previously hardcoded in PHP code.
 * After this seed, ALL variable values are editable via /rules admin.
 */

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

    $newRules = [
        [
            'rule_code'          => 'MINOR_AGE_THRESHOLD',
            'category'           => 'age',
            'name_ar'            => 'سن القاصر (أقل من)',
            'name_en'            => 'Minor Age Threshold',
            'data_type'          => 'integer',
            'current_value_json' => '{"value":18}',
            'parameters_json'    => '{"value":"integer"}',
        ],
        [
            'rule_code'          => 'WORKING_MEMBER_MIN_AGE',
            'category'           => 'age',
            'name_ar'            => 'الحد الأدنى لسن العضوية العاملة',
            'name_en'            => 'Working Member Minimum Age',
            'data_type'          => 'integer',
            'current_value_json' => '{"value":21}',
            'parameters_json'    => '{"value":"integer"}',
        ],
        [
            'rule_code'          => 'CHILD_MANDATORY_SEPARATION_AGE',
            'category'           => 'age',
            'name_ar'            => 'سن الفصل الوجوبي للابن/الابنة',
            'name_en'            => 'Child Mandatory Separation Age',
            'data_type'          => 'integer',
            'current_value_json' => '{"value":25}',
            'parameters_json'    => '{"value":"integer"}',
        ],
        [
            'rule_code'          => 'CHILD_INCLUDED_MAX_AGE',
            'category'           => 'age',
            'name_ar'            => 'الحد الأقصى لسن الابن المشمول (بدون رسوم)',
            'name_en'            => 'Max Age for Included Child (free)',
            'data_type'          => 'integer',
            'current_value_json' => '{"value":18}',
            '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) {
            continue;
        }
        $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,
        ]));
    }
};
