<?php
namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use App\Models\{Permission, Role, User};

class RbacSeeder extends Seeder {
    public array $mods = [
        'dashboard'  => ['view'],
        'quarry'     => ['view','create','edit','delete','approve'],
        'production' => ['view','create','edit','delete','approve'],
        'inventory'  => ['view','create','edit','delete','approve'],
        'fleet'      => ['view','create','edit','delete','approve'],
        'sales'      => ['view','create','edit','delete','approve'],
        'purchase'   => ['view','create','edit','delete','approve'],
        'projects'   => ['view','create','edit','delete','approve'],
        'hr'         => ['view','create','edit','delete','approve'],
        'payroll'    => ['view','create','edit','delete','approve'],
        'finance'    => ['view','create','edit','delete','approve'],
        'hse'        => ['view','create','edit','delete','approve'],
        'reports'    => ['view'],
        'docs'       => ['view','create','delete'],
        'settings'   => ['view','edit'],
        'users'      => ['view','create','edit','delete'],
    ];

    public function run(): void {
        $perms = [];
        foreach ($this->mods as $mod => $acts) {
            foreach ($acts as $act) {
                $p = Permission::firstOrCreate(
                    ['name' => "$mod.$act"],
                    ['module' => $mod, 'label' => ucfirst($act).' '.ucfirst($mod)]
                );
                $perms[$p->name] = $p->id;
            }
        }
        $all = array_values($perms);
        $v = fn($m) => array_filter($all, fn($id) => str_starts_with(array_search($id, $perms), "$m."));
        $viewAll = array_values(array_filter($all, fn($id) => str_ends_with(array_search($id, $perms), '.view')));

        $roles = [
            ['super-admin', 'Super Admin', 'Full system access', $all, 1],
            ['general-manager', 'General Manager', 'Approves everything except user admin', array_values(array_diff($all, $v('users'))), 0],
            ['quarry-manager', 'Quarry Manager', 'Quarries, production, dispatch, HSE', [...$v('dashboard'), ...$v('quarry'), ...$v('production'), ...$v('inventory'), ...$v('fleet'), ...$v('sales'), ...$v('hse'), ...$v('docs'), ...$v('reports')], 0],
            ['production-officer', 'Production Officer', 'Crusher output & QC', [...$v('dashboard'), ...$v('production'), 'quarry.view', 'inventory.view', 'docs.view', 'reports.view'], 0],
            ['store-keeper', 'Store Keeper', 'Stores & GRN', [...$v('dashboard'), ...$v('inventory'), 'purchase.view', 'docs.view', 'reports.view'], 0],
            ['fleet-officer', 'Fleet Officer', 'Workshop & transport', [...$v('dashboard'), ...$v('fleet'), 'inventory.view', 'docs.view', 'reports.view'], 0],
            ['sales-officer', 'Sales Officer', 'Quotes, orders, dispatch, cash', [...$v('dashboard'), ...$v('sales'), 'inventory.view', 'docs.view', 'reports.view'], 0],
            ['purchase-officer', 'Purchase Officer', 'Buying & supplier bills', [...$v('dashboard'), ...$v('purchase'), 'inventory.view', 'docs.view', 'reports.view'], 0],
            ['project-manager', 'Project Manager', 'Sites, BOQ, IPCs', [...$v('dashboard'), ...$v('projects'), ...$v('docs'), 'inventory.view', 'hr.view', 'reports.view'], 0],
            ['hr-officer', 'HR Officer', 'People, leave, attendance', [...$v('dashboard'), ...$v('hr'), ...$v('docs'), 'payroll.view', 'reports.view'], 0],
            ['accountant', 'Accountant', 'Money, taxes, payroll', [...$v('dashboard'), ...$v('finance'), ...$v('payroll'), 'sales.view', 'purchase.view', 'docs.view', 'reports.view', 'settings.view'], 0],
            ['hse-officer', 'HSE Officer', 'Safety & environment', [...$v('dashboard'), ...$v('hse'), ...$v('docs'), 'quarry.view', 'hr.view', 'reports.view'], 0],
            ['auditor', 'Auditor', 'Read-only + reports', [...$viewAll, 'reports.view'], 0],
        ];
        $roleIds = [];
        foreach ($roles as [$slug, $name, $desc, $names, $sys]) {
            $ids = array_values(array_unique(array_filter(array_map(fn($n) => is_int($n) ? $n : ($perms[$n] ?? null), $names))));
            $role = Role::updateOrCreate(['slug' => $slug], ['name' => $name, 'description' => $desc, 'is_system' => (bool) $sys]);
            $role->permissions()->sync($ids);
            $roleIds[$slug] = $role->id;
        }

        $users = [
            ['System Administrator', 'admin', 'admin@nowills.com.gh', 'super-admin', 'Admin#2026'],
            ['Yaw Mensah', 'Yaw Mensah', 'yaw.mensah@nowills.com.gh', 'quarry-manager', 'Demo#2026'],
            ['Ama Serwaa', 'ama', 'ama.serwaa@nowills.com.gh', 'accountant', 'Demo#2026'],
            ['Kwame Asante', 'kwame', 'kwame.asante@nowills.com.gh', 'hr-officer', 'Demo#2026'],
            ['Kofi Boateng', 'kofi', 'kofi.boateng@nowills.com.gh', 'sales-officer', 'Demo#2026'],
        ];
        foreach ($users as [$name, $uname, $email, $role, $pw]) {
            $u = User::updateOrCreate(['username' => $uname], [
                'name' => $name, 'email' => $email, 'password' => Hash::make($pw),
                'phone' => '0244000000', 'is_active' => true,
            ]);
            $u->roles()->syncWithoutDetaching([$roleIds[$role]]);
        }
    }
}
