<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class AdvancedPermissionSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Reset cached roles and permissions
        app()[\Spatie\Permission\PermissionRegistrar::class]->forgetCachedPermissions();

        $modules = [
            'Customers' => 'customers',
            'Companies' => 'companies',
            'Transactions' => 'transactions',
            'Sales' => 'sales',
            'Bank & Cash' => 'treasuries',
            'Products & Services' => 'products',
            'Reports' => 'reports',
            'Utilities' => 'utilities',
            'Appearance' => 'appearance',
            'Plugins' => 'plugins',
            'Calendar' => 'calendar',
            'Leads' => 'leads',
            'Tasks' => 'tasks',
            'Contracts' => 'contracts',
            'Orders' => 'orders',
            'Settings' => 'settings',
            'Documents' => 'documents',
            'Loyalty' => 'loyalty',
            'WHMCS' => 'whmcs',
            'Sales Team' => 'sales_team',
            'Projects' => 'projects',
            'Invoices' => 'invoices',
            'Attendance' => 'attendance',
            'Payroll' => 'payroll',
        ];

        $actions = [
            'view' => 'عرض',
            'create' => 'خلق',
            'edit' => 'تعديل',
            'delete' => 'حذف',
            'full' => 'كل المعلومات',
        ];

        foreach ($modules as $moduleLabel => $moduleKey) {
            foreach ($actions as $actionKey => $actionLabel) {
                Permission::findOrCreate("{$actionKey} {$moduleKey}", 'web');
            }
        }

        // Special Programmer Permissions
        Permission::findOrCreate('view own projects', 'web');
        Permission::findOrCreate('update own project progress', 'web');
        Permission::findOrCreate('view own payments', 'web');

        // Create Programmer Role with limited access
        $programmerRole = Role::findOrCreate('programmer', 'web');
        $programmerRole->syncPermissions([
            'view own projects',
            'update own project progress',
            'view own payments',
        ]);

        // Create Admin role and assign all permissions
        $adminRole = Role::findOrCreate('admin', 'web');
        $adminRole->syncPermissions(Permission::all());
    }

}
