<?php
declare(strict_types=1);

use App\Core\Database;

return function (Database $db): void {
    $roles = [
        ['role_code' => 'super_admin',         'name_ar' => 'المدير العام للنظام',  'name_en' => 'Super Admin',          'description_ar' => 'صلاحيات كاملة على جميع الوحدات',       'is_system' => 1],
        ['role_code' => 'board_member',         'name_ar' => 'عضو مجلس أمناء',      'name_en' => 'Board Member',         'description_ar' => 'الموافقة والرفض والعقوبات والتقارير',    'is_system' => 1],
        ['role_code' => 'membership_director',  'name_ar' => 'مدير العضويات',       'name_en' => 'Membership Director',  'description_ar' => 'إدارة العضويات والمقابلات والمستندات',   'is_system' => 1],
        ['role_code' => 'membership_officer',   'name_ar' => 'موظف العضويات',       'name_en' => 'Membership Officer',   'description_ar' => 'إدخال البيانات ورفع المستندات',         'is_system' => 1],
        ['role_code' => 'treasury_manager',     'name_ar' => 'مدير الخزينة',        'name_en' => 'Treasury Manager',     'description_ar' => 'معالجة المدفوعات وإلغاء الإيصالات',     'is_system' => 1],
        ['role_code' => 'treasury_officer',     'name_ar' => 'أمين الخزينة',        'name_en' => 'Treasury Officer',     'description_ar' => 'معالجة المدفوعات وإصدار الإيصالات',     'is_system' => 1],
        ['role_code' => 'sales_agent',          'name_ar' => 'موظف المبيعات',       'name_en' => 'Sales Agent',          'description_ar' => 'استقبال الأعضاء وإصدار الاستمارات',      'is_system' => 1],
        ['role_code' => 'security_officer',     'name_ar' => 'ضابط الأمن',          'name_en' => 'Security Officer',     'description_ar' => 'التحقق من هوية الأعضاء عند البوابة',    'is_system' => 1],
        ['role_code' => 'report_viewer',        'name_ar' => 'مراجع التقارير',      'name_en' => 'Report Viewer',        'description_ar' => 'عرض التقارير فقط',                      'is_system' => 1],
        ['role_code' => 'auditor',              'name_ar' => 'المراجع',             'name_en' => 'Auditor',              'description_ar' => 'الوصول للقراءة فقط لجميع البيانات',     'is_system' => 1],
    ];

    $permissionMap = [
        'super_admin'        => ['*'],
        'board_member'       => [
            'member.view', 'member.search', 'member.view_financial', 'member.change_status',
            'spouse.view', 'child.view', 'temp.view',
            'interview.conduct', 'interview.decide', 'interview.view',
            'transfer.approve', 'transfer.view', 'separation.approve', 'separation.view',
            'waiver.approve', 'waiver.view',
            'fine.impose', 'fine.view', 'fine.waive',
            'report.view_membership', 'report.view_financial', 'report.view_operations', 'report.view_audit',
            'payment.view', 'subscription.view', 'subscription.exempt',
            'user.view', 'settings.view',
        ],
        'membership_director' => [
            'member.create', 'member.view', 'member.edit', 'member.archive', 'member.search', 'member.view_financial', 'member.change_status',
            'spouse.add', 'spouse.edit', 'spouse.remove', 'spouse.view',
            'child.add', 'child.edit', 'child.remove', 'child.view', 'child.freeze', 'child.separate',
            'temp.add', 'temp.edit', 'temp.remove', 'temp.view',
            'interview.schedule', 'interview.view',
            'transfer.initiate', 'transfer.view', 'separation.initiate', 'separation.view',
            'document.upload', 'document.view', 'document.delete',
            'carnet.print', 'carnet.replace', 'carnet.view_log',
            'forms.view',
            'report.view_membership',
        ],
        'membership_officer' => [
            'member.create', 'member.view', 'member.edit', 'member.search',
            'spouse.add', 'spouse.edit', 'spouse.view',
            'child.add', 'child.edit', 'child.view',
            'temp.add', 'temp.edit', 'temp.view',
            'document.upload', 'document.view',
            'forms.view',
        ],
        'treasury_manager' => [
            'payment.process_cash', 'payment.process_check', 'payment.process_visa', 'payment.view', 'payment.void_receipt', 'payment.refund',
            'installment.create_plan', 'installment.record_payment', 'installment.view', 'installment.modify_plan',
            'subscription.collect', 'subscription.view', 'subscription.generate_batch',
            'fine.collect', 'fine.view',
            'report.view_financial',
            'member.view', 'member.search', 'member.view_financial',
        ],
        'treasury_officer' => [
            'payment.process_cash', 'payment.process_check', 'payment.process_visa', 'payment.view',
            'installment.record_payment', 'installment.view',
            'subscription.collect', 'subscription.view',
            'fine.collect', 'fine.view',
            'member.view', 'member.search', 'member.view_financial',
        ],
        'sales_agent' => [
            'member.view', 'member.search',
            'forms.view',
        ],
        'security_officer' => [
            'member.view', 'member.search',
            'carnet.view_log',
        ],
        'report_viewer' => [
            'report.view_membership', 'report.view_financial', 'report.view_operations', 'report.view_audit', 'report.export',
            'member.view', 'member.search', 'member.view_financial',
        ],
        'auditor' => [
            'report.view_membership', 'report.view_financial', 'report.view_operations', 'report.view_audit', 'report.export',
            'member.view', 'member.search', 'member.view_financial',
            'user.view', 'settings.view',
            'payment.view', 'subscription.view', 'installment.view', 'fine.view',
            'transfer.view', 'separation.view', 'waiver.view',
            'spouse.view', 'child.view', 'temp.view',
            'document.view', 'carnet.view_log',
            'interview.view',
        ],
    ];

    foreach ($roles as $role) {
        $existing = $db->selectOne("SELECT id FROM roles WHERE role_code = ?", [$role['role_code']]);
        if ($existing) {
            continue;
        }

        $roleId = $db->insert('roles', [
            'role_code'      => $role['role_code'],
            'name_ar'        => $role['name_ar'],
            'name_en'        => $role['name_en'],
            'description_ar' => $role['description_ar'],
            'is_system'      => $role['is_system'],
            'is_active'      => 1,
            'created_at'     => date('Y-m-d H:i:s'),
            'updated_at'     => date('Y-m-d H:i:s'),
        ]);

        $permissions = $permissionMap[$role['role_code']] ?? [];
        foreach ($permissions as $permKey) {
            $db->insert('role_permissions', [
                'role_id'        => $roleId,
                'permission_key' => $permKey,
                'granted_at'     => date('Y-m-d H:i:s'),
            ]);
        }
    }
};