<?php
declare(strict_types=1);

use App\Core\Database;

return function (Database $db): void {
    $roles = [
        [
            'role_code'        => 'general_manager',
            'name_ar'          => 'المدير العام',
            'name_en'          => 'General Manager',
            'description_ar'   => 'إشراف تشغيلي كامل على جميع الأقسام',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 1,
            'category'         => 'management',
            'level'            => 1,
            'is_template'      => 1,
            'permissions'      => [
                'member.view', 'member.create', 'member.edit', 'member.archive', 'member.search',
                'member.view_financial', 'member.change_status', 'member.reports',
                'payment.view', 'payment.process_cash', 'payment.process_check', 'payment.process_visa',
                'subscription.view', 'subscription.collect', 'subscription.generate_batch',
                'installment.view', 'installment.create_plan',
                'fine.view', 'fine.impose', 'fine.collect',
                'cashier.view_queue', 'cashier.process_payment',
                'receipt.view', 'receipt.print',
                'carnet.view', 'carnet.issue', 'carnet.print',
                'interview.view', 'interview.schedule', 'interview.decide',
                'transfer.view', 'transfer.initiate', 'transfer.approve',
                'waiver.view', 'waiver.initiate', 'waiver.approve',
                'spouse.view', 'spouse.add', 'spouse.edit',
                'child.view', 'child.add', 'child.edit',
                'temp.view', 'temp.add', 'temp.edit',
                'document.view', 'document.upload',
                'hr.employee.view', 'hr.department.view', 'hr.attendance.view', 'hr.leave.view',
                'hr.payroll.view', 'hr.report.view',
                'accounting.reports.view', 'accounting.reports.trial_balance',
                'accounting.reports.balance_sheet', 'accounting.reports.income_statement',
                'sa.dashboard', 'sa.discipline.view', 'sa.facility.view', 'sa.coach.view',
                'sa.player.view', 'sa.academy.view', 'sa.group.view', 'sa.schedule.view',
                'facility.view', 'reservation.view',
                'inventory.view', 'warehouse.view', 'stock.view',
                'report.view_membership', 'report.view_financial', 'report.view_operations',
                'report.export', 'report.view_audit',
                'user.view', 'role.view',
                'settings.view',
                'alert.view',
                'support.view', 'support.assign',
            ],
        ],
        [
            'role_code'        => 'hr_manager',
            'name_ar'          => 'مدير الموارد البشرية',
            'name_en'          => 'HR Manager',
            'description_ar'   => 'إدارة كاملة لشؤون الموظفين والرواتب',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 0,
            'category'         => 'hr',
            'level'            => 1,
            'is_template'      => 1,
            'permissions'      => [
                'hr.employee.view', 'hr.employee.manage', 'hr.employee.view_salary', 'hr.employee.manage_salary',
                'hr.department.view', 'hr.department.manage',
                'hr.job_title.view', 'hr.job_title.manage',
                'hr.contract.view', 'hr.contract.manage',
                'hr.attendance.view', 'hr.attendance.manage', 'hr.attendance.approve',
                'hr.leave.view', 'hr.leave.manage', 'hr.leave.approve',
                'hr.payroll.view', 'hr.payroll.process', 'hr.payroll.approve',
                'hr.insurance.view', 'hr.insurance.manage',
                'hr.loan.view', 'hr.loan.manage', 'hr.loan.approve',
                'hr.disciplinary.view', 'hr.disciplinary.manage',
                'hr.overtime.view', 'hr.overtime.manage', 'hr.overtime.approve',
                'hr.eos.view', 'hr.eos.manage', 'hr.eos.approve',
                'hr.document.view', 'hr.document.manage',
                'hr.performance.view', 'hr.performance.manage',
                'hr.holiday.manage',
                'hr.schedule.manage',
                'hr.shifts.view', 'hr.shifts.manage',
                'hr.permissions.view', 'hr.permissions.approve',
                'hr.report.view', 'hr.tax.view',
            ],
        ],
        [
            'role_code'        => 'hr_officer',
            'name_ar'          => 'موظف موارد بشرية',
            'name_en'          => 'HR Officer',
            'description_ar'   => 'إدخال بيانات الموظفين والحضور بدون صلاحيات الموافقة',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 0,
            'category'         => 'hr',
            'level'            => 2,
            'is_template'      => 1,
            'permissions'      => [
                'hr.employee.view', 'hr.employee.manage',
                'hr.department.view',
                'hr.job_title.view',
                'hr.contract.view', 'hr.contract.manage',
                'hr.attendance.view', 'hr.attendance.manage',
                'hr.leave.view', 'hr.leave.manage', 'hr.leave.request',
                'hr.payroll.view',
                'hr.insurance.view', 'hr.insurance.manage',
                'hr.loan.view', 'hr.loan.manage',
                'hr.disciplinary.view',
                'hr.overtime.view', 'hr.overtime.create',
                'hr.eos.view',
                'hr.document.view', 'hr.document.manage',
                'hr.performance.view',
                'hr.shifts.view',
                'hr.permissions.view', 'hr.permissions.create',
                'hr.report.view',
            ],
        ],
        [
            'role_code'        => 'cashier_operator',
            'name_ar'          => 'أمين الصندوق',
            'name_en'          => 'Cashier Operator',
            'description_ar'   => 'معالجة المدفوعات وإدارة طابور الخزينة',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 0,
            'category'         => 'finance',
            'level'            => 2,
            'is_template'      => 1,
            'permissions'      => [
                'cashier.view_queue', 'cashier.process_payment', 'cashier.cancel_request',
                'payment.view', 'payment.process_cash', 'payment.process_check', 'payment.process_visa',
                'receipt.view', 'receipt.print',
                'member.view', 'member.search',
                'subscription.view', 'subscription.collect',
                'installment.view', 'installment.record_payment',
                'fine.view', 'fine.collect',
            ],
        ],
        [
            'role_code'        => 'accountant',
            'name_ar'          => 'محاسب',
            'name_en'          => 'Accountant',
            'description_ar'   => 'إدارة الحسابات والقيود والتقارير المالية',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 0,
            'category'         => 'finance',
            'level'            => 2,
            'is_template'      => 1,
            'permissions'      => [
                'accounting.coa.view', 'accounting.coa.manage',
                'accounting.journal.view', 'accounting.journal.create', 'accounting.journal.post',
                'accounting.journal_type.view', 'accounting.journal_type.manage',
                'accounting.fiscal_year.view', 'accounting.fiscal_year.manage',
                'accounting.period.view', 'accounting.period.close',
                'accounting.budget.view', 'accounting.budget.manage',
                'accounting.bank_account.view', 'accounting.bank_account.manage',
                'accounting.bank_recon.view', 'accounting.bank_recon.manage',
                'accounting.cost_center.view', 'accounting.cost_center.manage',
                'accounting.daily_tx.view', 'accounting.daily_tx.manage',
                'accounting.opening_entry.view', 'accounting.opening_entry.manage',
                'accounting.instruments.view', 'accounting.instruments.manage',
                'accounting.loans.view', 'accounting.loans.manage',
                'accounting.settlements.view', 'accounting.settlements.manage',
                'accounting.dimensions.view', 'accounting.dimensions.manage',
                'accounting.reports.view', 'accounting.reports.trial_balance',
                'accounting.reports.balance_sheet', 'accounting.reports.income_statement',
                'accounting.reports.general_ledger', 'accounting.reports.revenue_analysis',
                'accounting.reports.member_statement', 'accounting.reports.treasury',
                'payment.view',
                'subscription.view',
                'installment.view',
                'report.view_financial',
            ],
        ],
        [
            'role_code'        => 'sports_coordinator',
            'name_ar'          => 'منسق الأنشطة الرياضية',
            'name_en'          => 'Sports Coordinator',
            'description_ar'   => 'إدارة كاملة للأنشطة الرياضية والأكاديميات',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 0,
            'category'         => 'sports',
            'level'            => 1,
            'is_template'      => 1,
            'permissions'      => [
                'sa.dashboard',
                'sa.discipline.view', 'sa.discipline.manage',
                'sa.facility.view', 'sa.facility.manage',
                'sa.coach.view', 'sa.coach.manage',
                'sa.player.view', 'sa.player.manage',
                'sa.academy.view', 'sa.academy.manage',
                'sa.contract.view', 'sa.contract.manage', 'sa.contract.approve',
                'sa.program.view', 'sa.program.manage',
                'sa.group.view', 'sa.group.manage', 'sa.group.enroll',
                'sa.schedule.view', 'sa.schedule.manage',
                'sa.booking.view', 'sa.booking.manage', 'sa.booking.create',
                'sa.pricing.view', 'sa.pricing.manage',
                'sa.subscription.view', 'sa.subscription.collect', 'sa.subscription.exempt', 'sa.subscription.generate',
                'sa.attendance.view', 'sa.attendance.manage',
                'sa.waitlist.view', 'sa.waitlist.manage',
                'sa.medical.approve',
                'facility.view', 'facility.manage',
                'reservation.view', 'reservation.create', 'reservation.confirm', 'reservation.cancel',
                'scheduling.view', 'scheduling.manage_rules',
                'report.view_sports',
            ],
        ],
        [
            'role_code'        => 'academy_manager',
            'name_ar'          => 'مدير الأكاديمية',
            'name_en'          => 'Academy Manager',
            'description_ar'   => 'إدارة الأكاديميات والمجموعات والاشتراكات',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 0,
            'category'         => 'sports',
            'level'            => 2,
            'is_template'      => 1,
            'permissions'      => [
                'sa.dashboard',
                'sa.academy.view', 'sa.academy.manage',
                'sa.program.view', 'sa.program.manage',
                'sa.group.view', 'sa.group.manage', 'sa.group.enroll',
                'sa.schedule.view', 'sa.schedule.manage',
                'sa.player.view', 'sa.player.manage',
                'sa.coach.view',
                'sa.subscription.view', 'sa.subscription.collect', 'sa.subscription.generate',
                'sa.attendance.view', 'sa.attendance.manage',
                'sa.waitlist.view', 'sa.waitlist.manage',
                'sa.pricing.view',
            ],
        ],
        [
            'role_code'        => 'sports_coach',
            'name_ar'          => 'مدرب رياضي',
            'name_en'          => 'Sports Coach',
            'description_ar'   => 'تسجيل الحضور وعرض الجداول والمجموعات',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 0,
            'category'         => 'sports',
            'level'            => 3,
            'is_template'      => 1,
            'permissions'      => [
                'sa.attendance.view', 'sa.attendance.manage',
                'sa.group.view',
                'sa.schedule.view',
                'sa.player.view',
                'sa.dashboard',
            ],
        ],
        [
            'role_code'        => 'facilities_manager',
            'name_ar'          => 'مدير المنشآت',
            'name_en'          => 'Facilities Manager',
            'description_ar'   => 'إدارة المنشآت والحجوزات والجداول',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 0,
            'category'         => 'operations',
            'level'            => 1,
            'is_template'      => 1,
            'permissions'      => [
                'facility.view', 'facility.manage',
                'sa.facility.view', 'sa.facility.manage',
                'reservation.view', 'reservation.create', 'reservation.confirm', 'reservation.cancel',
                'scheduling.view', 'scheduling.manage_rules', 'scheduling.resolve',
                'sa.booking.view', 'sa.booking.manage', 'sa.booking.create',
                'sa.schedule.view', 'sa.schedule.manage',
                'member.view', 'member.search',
            ],
        ],
        [
            'role_code'        => 'receptionist',
            'name_ar'          => 'موظف الاستقبال',
            'name_en'          => 'Receptionist',
            'description_ar'   => 'استقبال الأعضاء والبحث وإدارة الحجوزات',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 0,
            'category'         => 'operations',
            'level'            => 2,
            'is_template'      => 1,
            'permissions'      => [
                'member.view', 'member.search',
                'carnet.view', 'carnet.view_log', 'carnet.record_guest', 'carnet.view_guests',
                'reservation.view', 'reservation.create',
                'sa.booking.view', 'sa.booking.create',
                'support.view', 'support.create',
            ],
        ],
        [
            'role_code'        => 'gate_guard',
            'name_ar'          => 'حارس البوابة',
            'name_en'          => 'Gate Guard',
            'description_ar'   => 'التحقق من هوية الأعضاء وتسجيل الضيوف',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 0,
            'category'         => 'security',
            'level'            => 3,
            'is_template'      => 1,
            'permissions'      => [
                'member.view', 'member.search',
                'carnet.view', 'carnet.view_log', 'carnet.record_guest', 'carnet.view_guests',
            ],
        ],
        [
            'role_code'        => 'it_admin',
            'name_ar'          => 'مسؤول تقنية المعلومات',
            'name_en'          => 'IT Administrator',
            'description_ar'   => 'إدارة المستخدمين والأدوار وإعدادات النظام',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 1,
            'category'         => 'it',
            'level'            => 1,
            'is_template'      => 1,
            'permissions'      => [
                'user.view', 'user.create', 'user.edit', 'user.deactivate',
                'user.assign_role', 'user.manage_permissions',
                'role.view', 'role.create', 'role.edit',
                'settings.view', 'settings.edit',
                'report.view_audit',
                'alert.view', 'alert.manage',
            ],
        ],
        [
            'role_code'        => 'department_head',
            'name_ar'          => 'رئيس قسم',
            'name_en'          => 'Department Head',
            'description_ar'   => 'رئيس قسم — عرض بيانات القسم والموافقة على الإجازات',
            'is_system'        => 0,
            'parent_role_id'   => null,
            'has_all_branches' => 0,
            'category'         => 'management',
            'level'            => 2,
            'is_template'      => 1,
            'permissions'      => [
                'hr.employee.view',
                'hr.attendance.view', 'hr.attendance.approve',
                'hr.leave.view', 'hr.leave.approve',
                'hr.overtime.view', 'hr.overtime.approve',
                'hr.permissions.view', 'hr.permissions.approve',
                'hr.performance.view', 'hr.performance.manage',
                'hr.report.view',
                'member.view', 'member.search',
                'report.view_operations',
            ],
        ],
    ];

    foreach ($roles as $roleData) {
        $permissions = $roleData['permissions'];
        unset($roleData['permissions']);

        $existing = $db->selectOne(
            "SELECT id FROM roles WHERE role_code = ?",
            [$roleData['role_code']]
        );

        if ($existing) {
            continue;
        }

        $roleData['created_at'] = date('Y-m-d H:i:s');
        $roleData['updated_at'] = date('Y-m-d H:i:s');
        $db->insert('roles', $roleData);

        $roleId = (int) $db->selectOne(
            "SELECT id FROM roles WHERE role_code = ?",
            [$roleData['role_code']]
        )['id'];

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