<?php
declare(strict_types=1);

use App\Core\Database;

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

    // ─── New Roles ──────────────────────────────────────────────────────────────

    $newRoles = [
        [
            'role_code'      => 'membership_cashier',
            'name_ar'        => 'أمين خزنة العضويات',
            'name_en'        => 'Membership Cashier',
            'description_ar' => 'تحصيل مدفوعات العضويات وإدارة الوردية',
            'is_system'      => 1,
            'category'       => 'finance',
            'level'          => 2,
            'permissions'    => [
                'cashier.view_queue', 'cashier.process_payment', 'cashier.cancel_request',
                'cashier.view_custody',
                'treasury.open_session', 'treasury.close_session', 'treasury.initiate_settlement',
                'treasury.view_custody', 'treasury.view_sessions',
                'member.view', 'member.search',
                'receipts.print',
            ],
        ],
        [
            'role_code'      => 'sports_cashier',
            'name_ar'        => 'أمين خزنة الأنشطة',
            'name_en'        => 'Sports Cashier',
            'description_ar' => 'تحصيل مدفوعات الأنشطة الرياضية وإدارة الوردية',
            'is_system'      => 1,
            'category'       => 'finance',
            'level'          => 2,
            'permissions'    => [
                'treasury.view_dashboard', 'treasury.collect_payment',
                'treasury.open_session', 'treasury.close_session', 'treasury.initiate_settlement',
                'treasury.view_custody', 'treasury.view_sessions', 'treasury.view_settlements',
                'sa.subscription.collect',
                'member.view', 'member.search',
                'receipts.print',
            ],
        ],
        [
            'role_code'      => 'main_cashier',
            'name_ar'        => 'أمين الخزنة الرئيسية',
            'name_en'        => 'Main Cashier',
            'description_ar' => 'استلام التسويات من الخزن الفرعية وإيداعات البنك',
            'is_system'      => 1,
            'category'       => 'finance',
            'level'          => 1,
            'permissions'    => [
                'cashier.view_queue', 'cashier.receive_settlement',
                'cashier.manage_deposits', 'cashier.confirm_deposit', 'cashier.view_custody',
                'treasury.view_settlements',
                'member.view', 'member.search',
                'receipts.print',
            ],
        ],
        [
            'role_code'      => 'sports_officer',
            'name_ar'        => 'موظف الأنشطة الرياضية',
            'name_en'        => 'Sports Officer',
            'description_ar' => 'إدارة اللاعبين والمجموعات والحجوزات',
            'is_system'      => 1,
            'category'       => 'operations',
            'level'          => 2,
            'permissions'    => [
                'sa.dashboard', 'sa.player.view', 'sa.player.manage',
                'sa.group.view', 'sa.group.manage', 'sa.group.enroll',
                'sa.schedule.view', 'sa.schedule.manage',
                'sa.booking.view', 'sa.booking.create', 'sa.booking.manage',
                'sa.subscription.view', 'sa.subscription.generate',
                'sa.attendance.view', 'sa.attendance.manage',
                'sa.waitlist.view', 'sa.waitlist.manage',
                'sa.locker.view', 'sa.locker.manage',
                'sa.locker_rental.view', 'sa.locker_rental.create',
            ],
        ],
        [
            'role_code'      => 'sports_director',
            'name_ar'        => 'مدير الأنشطة الرياضية',
            'name_en'        => 'Sports Director',
            'description_ar' => 'إدارة كاملة للأنشطة الرياضية والتقارير والإعفاءات',
            'is_system'      => 1,
            'category'       => 'management',
            'level'          => 1,
            'permissions'    => [
                'sa.dashboard', 'sa.player.view', 'sa.player.manage',
                'sa.group.view', 'sa.group.manage', 'sa.group.enroll',
                'sa.schedule.view', 'sa.schedule.manage',
                'sa.booking.view', 'sa.booking.create', 'sa.booking.manage',
                'sa.subscription.view', 'sa.subscription.generate', 'sa.subscription.collect', 'sa.subscription.exempt',
                'sa.attendance.view', 'sa.attendance.manage',
                'sa.waitlist.view', 'sa.waitlist.manage',
                'sa.discipline.view', 'sa.discipline.manage',
                'sa.facility.view', 'sa.facility.manage',
                'sa.coach.view', 'sa.coach.manage',
                'sa.program.view', 'sa.program.manage',
                'sa.pricing.view', 'sa.pricing.manage',
                'sa.academy.view', 'sa.academy.manage',
                'sa.contract.view', 'sa.contract.manage', 'sa.contract.approve',
                'sa.medical.approve',
                'sa.locker.view', 'sa.locker.manage',
                'sa.locker_rental.view', 'sa.locker_rental.create', 'sa.locker_rental.manage', 'sa.locker_rental.evict',
                'sa.mirror.view', 'sa.pool-grid.manage',
                'report.view_operations',
            ],
        ],
    ];

    foreach ($newRoles as $roleDef) {
        $permissions = $roleDef['permissions'];
        unset($roleDef['permissions']);

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

        $roleId = $db->insert('roles', array_merge($roleDef, [
            'is_active'   => 1,
            'created_at'  => $now,
            'updated_at'  => $now,
        ]));

        foreach ($permissions as $permKey) {
            $db->insert('role_permissions', [
                'role_id'        => $roleId,
                'permission_key' => $permKey,
                'granted_at'     => $now,
            ]);
        }
    }

    // ─── Update Existing Roles ──────────────────────────────────────────────────

    $updates = [
        'treasury_manager' => [
            'cashier.receive_settlement', 'cashier.manage_deposits', 'cashier.confirm_deposit',
            'cashier.view_custody', 'treasury.view_dashboard',
            'treasury.view_custody', 'treasury.view_sessions', 'treasury.view_settlements',
        ],
        'treasury_officer' => [
            'cashier.view_queue', 'cashier.process_payment',
            'treasury.open_session', 'treasury.close_session', 'treasury.view_custody',
        ],
        'auditor' => [
            'treasury.view_dashboard', 'treasury.view_custody', 'treasury.view_sessions', 'treasury.view_settlements',
            'cashier.view_queue', 'cashier.view_custody',
            'sa.dashboard', 'sa.subscription.view', 'sa.booking.view',
            'sa.locker.view', 'sa.locker_rental.view',
        ],
    ];

    foreach ($updates as $roleCode => $permsToAdd) {
        $role = $db->selectOne("SELECT id FROM roles WHERE role_code = ?", [$roleCode]);
        if (!$role) continue;

        $roleId = (int) $role['id'];

        foreach ($permsToAdd as $permKey) {
            $exists = $db->selectOne(
                "SELECT 1 FROM role_permissions WHERE role_id = ? AND permission_key = ?",
                [$roleId, $permKey]
            );
            if (!$exists) {
                $db->insert('role_permissions', [
                    'role_id'        => $roleId,
                    'permission_key' => $permKey,
                    'granted_at'     => $now,
                ]);
            }
        }
    }
};
