<?php

namespace Database\Seeders;

use App\Models\Role;
use App\Models\Permission;
use App\Models\User;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\Hash;

class RolesAndPermissionsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        // Create Permissions grouped by modules
        $permissions = [
            // Dashboard & System
            'system' => [
                ['name' => 'dashboard.view', 'display_name' => 'View Dashboard', 'description' => 'Can view main dashboard'],
                ['name' => 'analytics.view', 'display_name' => 'View Analytics', 'description' => 'Can view analytics and reports'],
                ['name' => 'settings.manage', 'display_name' => 'Manage Settings', 'description' => 'Can manage system settings'],
                ['name' => 'users.manage', 'display_name' => 'Manage Users', 'description' => 'Can manage user accounts'],
                ['name' => 'roles.manage', 'display_name' => 'Manage Roles', 'description' => 'Can manage roles and permissions'],
            ],

            // Customer Management
            'customers' => [
                ['name' => 'customers.view', 'display_name' => 'View Customers', 'description' => 'Can view customer list'],
                ['name' => 'customers.create', 'display_name' => 'Create Customers', 'description' => 'Can create new customers'],
                ['name' => 'customers.update', 'display_name' => 'Edit Customers', 'description' => 'Can edit customer information'],
                ['name' => 'customers.delete', 'display_name' => 'Delete Customers', 'description' => 'Can delete customers'],
                ['name' => 'customers.details', 'display_name' => 'View Customer Details', 'description' => 'Can view detailed customer information'],
            ],

            // Vehicle Management
            'vehicles' => [
                ['name' => 'vehicles.view', 'display_name' => 'View Vehicles', 'description' => 'Can view vehicle list'],
                ['name' => 'vehicles.create', 'display_name' => 'Create Vehicles', 'description' => 'Can register new vehicles'],
                ['name' => 'vehicles.update', 'display_name' => 'Edit Vehicles', 'description' => 'Can edit vehicle information'],
                ['name' => 'vehicles.delete', 'display_name' => 'Delete Vehicles', 'description' => 'Can delete vehicles'],
                ['name' => 'vehicles.history', 'display_name' => 'View Vehicle History', 'description' => 'Can view vehicle service history'],
            ],

            // Service Orders
            'service-orders' => [
                ['name' => 'service-orders.view', 'display_name' => 'View Service Orders', 'description' => 'Can view service orders'],
                ['name' => 'service-orders.create', 'display_name' => 'Create Service Orders', 'description' => 'Can create new service orders'],
                ['name' => 'service-orders.update', 'display_name' => 'Edit Service Orders', 'description' => 'Can edit service orders'],
                ['name' => 'service-orders.delete', 'display_name' => 'Delete Service Orders', 'description' => 'Can delete service orders'],
                ['name' => 'service-orders.approve', 'display_name' => 'Approve Service Orders', 'description' => 'Can approve service orders'],
                ['name' => 'service-orders.complete', 'display_name' => 'Complete Service Orders', 'description' => 'Can mark service orders as complete'],
            ],

            // Job Cards
            'job-cards' => [
                ['name' => 'job-cards.view', 'display_name' => 'View Job Cards', 'description' => 'Can view job cards'],
                ['name' => 'job-cards.create', 'display_name' => 'Create Job Cards', 'description' => 'Can create new job cards'],
                ['name' => 'job-cards.update', 'display_name' => 'Edit Job Cards', 'description' => 'Can edit job cards'],
                ['name' => 'job-cards.delete', 'display_name' => 'Delete Job Cards', 'description' => 'Can delete job cards'],
                ['name' => 'job-cards.assign', 'display_name' => 'Assign Job Cards', 'description' => 'Can assign job cards to technicians'],
            ],

            // Work Orders
            'work-orders' => [
                ['name' => 'work-orders.view', 'display_name' => 'View Work Orders', 'description' => 'Can view work orders'],
                ['name' => 'work-orders.create', 'display_name' => 'Create Work Orders', 'description' => 'Can create new work orders'],
                ['name' => 'work-orders.update', 'display_name' => 'Edit Work Orders', 'description' => 'Can edit work orders'],
                ['name' => 'work-orders.delete', 'display_name' => 'Delete Work Orders', 'description' => 'Can delete work orders'],
                ['name' => 'work-orders.complete', 'display_name' => 'Complete Work Orders', 'description' => 'Can mark work orders as complete'],
            ],

            // Appointments
            'appointments' => [
                ['name' => 'appointments.view', 'display_name' => 'View Appointments', 'description' => 'Can view appointments'],
                ['name' => 'appointments.create', 'display_name' => 'Create Appointments', 'description' => 'Can schedule new appointments'],
                ['name' => 'appointments.update', 'display_name' => 'Edit Appointments', 'description' => 'Can edit appointments'],
                ['name' => 'appointments.delete', 'display_name' => 'Delete Appointments', 'description' => 'Can cancel appointments'],
                ['name' => 'appointments.confirm', 'display_name' => 'Confirm Appointments', 'description' => 'Can confirm appointments'],
            ],

            // Inventory Management
            'inventory' => [
                ['name' => 'inventory.view', 'display_name' => 'View Inventory', 'description' => 'Can view inventory items'],
                ['name' => 'inventory.create', 'display_name' => 'Create Parts', 'description' => 'Can add new parts to inventory'],
                ['name' => 'inventory.update', 'display_name' => 'Edit Parts', 'description' => 'Can edit part information'],
                ['name' => 'inventory.delete', 'display_name' => 'Delete Parts', 'description' => 'Can delete parts from inventory'],
                ['name' => 'inventory.stock', 'display_name' => 'Manage Stock', 'description' => 'Can manage stock levels'],
                ['name' => 'inventory.stock-movements', 'display_name' => 'View Stock Movements', 'description' => 'Can view stock movement history'],
                ['name' => 'inventory.purchase-orders', 'display_name' => 'Manage Purchase Orders', 'description' => 'Can create and manage purchase orders'],
                ['name' => 'inventory.purchase-orders-approve', 'display_name' => 'Approve Purchase Orders', 'description' => 'Can approve purchase orders'],
            ],

            // Technician Management
            'technicians' => [
                ['name' => 'technicians.view', 'display_name' => 'View Technicians', 'description' => 'Can view technician list'],
                ['name' => 'technicians.create', 'display_name' => 'Create Technicians', 'description' => 'Can add new technicians'],
                ['name' => 'technicians.update', 'display_name' => 'Edit Technicians', 'description' => 'Can edit technician information'],
                ['name' => 'technicians.delete', 'display_name' => 'Delete Technicians', 'description' => 'Can remove technicians'],
                ['name' => 'technicians.view-performance', 'display_name' => 'View Technician Performance', 'description' => 'Can view technician performance metrics'],
                ['name' => 'technicians.schedules', 'display_name' => 'Manage Technician Schedules', 'description' => 'Can manage technician work schedules'],
            ],

            // Inspections
            'inspections' => [
                ['name' => 'inspections.view', 'display_name' => 'View Inspections', 'description' => 'Can view vehicle inspections'],
                ['name' => 'inspections.create', 'display_name' => 'Create Inspections', 'description' => 'Can create new inspections'],
                ['name' => 'inspections.update', 'display_name' => 'Edit Inspections', 'description' => 'Can edit inspection results'],
                ['name' => 'inspections.approve', 'display_name' => 'Approve Inspections', 'description' => 'Can approve inspection results'],
                ['name' => 'inspections.reschedule', 'display_name' => 'Schedule Reinspections', 'description' => 'Can schedule reinspections'],
            ],

            // Estimates & Diagnosis
            'estimates' => [
                ['name' => 'estimates.view', 'display_name' => 'View Estimates', 'description' => 'Can view estimates'],
                ['name' => 'estimates.create', 'display_name' => 'Create Estimates', 'description' => 'Can create new estimates'],
                ['name' => 'estimates.update', 'display_name' => 'Edit Estimates', 'description' => 'Can edit estimates'],
                ['name' => 'estimates.approve', 'display_name' => 'Approve Estimates', 'description' => 'Can approve estimates'],
                ['name' => 'diagnosis.view', 'display_name' => 'View Diagnosis', 'description' => 'Can view diagnosis results'],
                ['name' => 'diagnosis.create', 'display_name' => 'Create Diagnosis', 'description' => 'Can create diagnosis reports'],
            ],

            // Reports & Analytics
            'reports' => [
                ['name' => 'reports.view', 'display_name' => 'View Reports', 'description' => 'Can view business reports'],
                ['name' => 'reports.create', 'display_name' => 'Create Reports', 'description' => 'Can generate new reports'],
                ['name' => 'reports.export', 'display_name' => 'Export Reports', 'description' => 'Can export reports to various formats'],
                ['name' => 'reports.financial', 'display_name' => 'View Financial Reports', 'description' => 'Can view financial and revenue reports'],
            ],

            // Timesheets
            'timesheets' => [
                ['name' => 'timesheets.view', 'display_name' => 'View Timesheets', 'description' => 'Can view timesheet records'],
                ['name' => 'timesheets.create', 'display_name' => 'Create Timesheets', 'description' => 'Can create timesheet entries'],
                ['name' => 'timesheets.update', 'display_name' => 'Edit Timesheets', 'description' => 'Can edit timesheet entries'],
                ['name' => 'timesheets.approve', 'display_name' => 'Approve Timesheets', 'description' => 'Can approve timesheet entries'],
            ],
        ];

        // Create permissions
        foreach ($permissions as $module => $modulePermissions) {
            foreach ($modulePermissions as $permission) {
                Permission::firstOrCreate(
                    ['name' => $permission['name']],
                    [
                        'display_name' => $permission['display_name'],
                        'description' => $permission['description'],
                        'module' => $module,
                        'is_active' => true,
                    ]
                );
            }
        }

        // Create Roles
        $roles = [
            [
                'name' => 'super_admin',
                'display_name' => 'Super Administrator',
                'description' => 'Full system access with all permissions',
                'permissions' => 'all' // Special case - gets all permissions
            ],
            [
                'name' => 'manager',
                'display_name' => 'Manager',
                'description' => 'Management level access with most permissions',
                'permissions' => [
                    'dashboard.view', 'analytics.view', 'settings.manage',
                    'customers.view', 'customers.create', 'customers.update', 'customers.details',
                    'vehicles.view', 'vehicles.create', 'vehicles.update', 'vehicles.history',
                    'service-orders.view', 'service-orders.create', 'service-orders.update', 'service-orders.approve', 'service-orders.complete',
                    'job-cards.view', 'job-cards.create', 'job-cards.update', 'job-cards.assign',
                    'work-orders.view', 'work-orders.create', 'work-orders.update', 'work-orders.complete',
                    'appointments.view', 'appointments.create', 'appointments.update', 'appointments.confirm',
                    'inventory.view', 'inventory.create', 'inventory.update', 'inventory.stock', 'inventory.stock-movements', 'inventory.purchase-orders', 'inventory.purchase-orders-approve',
                    'technicians.view', 'technicians.create', 'technicians.update', 'technicians.view-performance', 'technicians.schedules',
                    'inspections.view', 'inspections.create', 'inspections.update', 'inspections.approve', 'inspections.reschedule',
                    'estimates.view', 'estimates.create', 'estimates.update', 'estimates.approve', 'diagnosis.view', 'diagnosis.create',
                    'reports.view', 'reports.create', 'reports.export', 'reports.financial',
                    'timesheets.view', 'timesheets.approve',
                ]
            ],
            [
                'name' => 'service_advisor',
                'display_name' => 'Service Advisor',
                'description' => 'Customer service and appointment management',
                'permissions' => [
                    'dashboard.view',
                    'customers.view', 'customers.create', 'customers.update', 'customers.details',
                    'vehicles.view', 'vehicles.create', 'vehicles.update', 'vehicles.history',
                    'service-orders.view', 'service-orders.create', 'service-orders.update',
                    'appointments.view', 'appointments.create', 'appointments.update', 'appointments.confirm',
                    'estimates.view', 'estimates.create', 'diagnosis.view',
                    'inventory.view', 'inventory.stock-movements',
                    'inspections.view', 'inspections.create',
                ]
            ],
            [
                'name' => 'technician',
                'display_name' => 'Technician',
                'description' => 'Workshop technician with job execution permissions',
                'permissions' => [
                    'dashboard.view',
                    'customers.view', 'customers.details',
                    'vehicles.view', 'vehicles.history',
                    'service-orders.view',
                    'job-cards.view', 'job-cards.update',
                    'work-orders.view', 'work-orders.update', 'work-orders.complete',
                    'inventory.view', 'inventory.stock-movements',
                    'inspections.view', 'inspections.create', 'inspections.update',
                    'diagnosis.view', 'diagnosis.create',
                    'timesheets.view', 'timesheets.create', 'timesheets.update',
                ]
            ],
            [
                'name' => 'inventory_manager',
                'display_name' => 'Inventory Manager',
                'description' => 'Inventory and parts management specialist',
                'permissions' => [
                    'dashboard.view',
                    'inventory.view', 'inventory.create', 'inventory.update', 'inventory.stock', 'inventory.stock-movements',
                    'inventory.purchase-orders', 'inventory.purchase-orders-approve',
                    'service-orders.view', 'work-orders.view',
                    'reports.view', 'reports.create', 'reports.export',
                ]
            ],
            [
                'name' => 'customer_portal',
                'display_name' => 'Customer Portal',
                'description' => 'Limited customer portal access',
                'permissions' => [
                    'appointments.view',
                    'vehicles.view', 'vehicles.history',
                    'service-orders.view',
                    'estimates.view',
                ]
            ],
        ];

        // Create roles and assign permissions
        foreach ($roles as $roleData) {
            $role = Role::firstOrCreate(
                ['name' => $roleData['name']],
                [
                    'display_name' => $roleData['display_name'],
                    'description' => $roleData['description'],
                    'is_active' => true,
                ]
            );

            // Assign permissions to role
            if ($roleData['permissions'] === 'all') {
                // Super admin gets all permissions
                $allPermissions = Permission::where('is_active', true)->get();
                $role->permissions()->sync($allPermissions->pluck('id')->toArray());
            } else {
                // Get permission IDs by names
                $permissionIds = Permission::whereIn('name', $roleData['permissions'])
                    ->where('is_active', true)
                    ->pluck('id')
                    ->toArray();
                
                $role->permissions()->sync($permissionIds);
            }
        }

        // Create dedicated super admin user
        $superAdminUser = User::firstOrCreate(
            ['email' => 'admin@admin.com'],
            [
                'name' => 'Super Administrator',
                'password' => Hash::make('danewcash54899'),
                'email_verified_at' => now(),
                'employee_id' => 'ADMIN001',
                'position' => 'System Administrator',
                'department' => 'IT',
                'status' => 'active',
            ]
        );

        // Assign super_admin role
        $superAdminRole = Role::where('name', 'super_admin')->first();
        if ($superAdminRole) {
            $superAdminUser->roles()->sync([$superAdminRole->id]);
        }

        // Create a test manager user
        $managerUser = User::firstOrCreate(
            ['email' => 'manager@carrepairs.com'],
            [
                'name' => 'Workshop Manager',
                'password' => Hash::make('password'),
                'email_verified_at' => now(),
                'employee_id' => 'MGR001',
                'position' => 'Workshop Manager',
                'department' => 'Management',
                'status' => 'active',
            ]
        );

        $managerRole = Role::where('name', 'manager')->first();
        if ($managerRole) {
            $managerUser->roles()->sync([$managerRole->id]);
        }

        // Create a test technician user
        $technicianUser = User::firstOrCreate(
            ['email' => 'technician@carrepairs.com'],
            [
                'name' => 'Lead Technician',
                'password' => Hash::make('password'),
                'email_verified_at' => now(),
                'employee_id' => 'TECH001',
                'position' => 'Lead Technician',
                'department' => 'Workshop',
                'status' => 'active',
            ]
        );

        $technicianRole = Role::where('name', 'technician')->first();
        if ($technicianRole) {
            $technicianUser->roles()->sync([$technicianRole->id]);
        }

        // Create a test service advisor user
        $advisorUser = User::firstOrCreate(
            ['email' => 'advisor@carrepairs.com'],
            [
                'name' => 'Service Advisor',
                'password' => Hash::make('password'),
                'email_verified_at' => now(),
                'employee_id' => 'ADV001',
                'position' => 'Service Advisor',
                'department' => 'Customer Service',
                'status' => 'active',
            ]
        );

        // Create a test technician user
        $technicianUser = User::firstOrCreate(
            ['email' => 'technician@carrepairs.com'],
            [
                'name' => 'Lead Technician',
                'password' => Hash::make('password'),
                'email_verified_at' => now(),
                'employee_id' => 'TECH001',
                'position' => 'Lead Technician',
                'department' => 'Workshop',
                'status' => 'active',
            ]
        );

        $technicianRole = Role::where('name', 'technician')->first();
        if ($technicianRole) {
            $technicianUser->roles()->sync([$technicianRole->id]);
        }

        // Create a test service advisor user
        $advisorUser = User::firstOrCreate(
            ['email' => 'advisor@carrepairs.com'],
            [
                'name' => 'Service Advisor',
                'password' => Hash::make('password'),
                'email_verified_at' => now(),
                'employee_id' => 'ADV001',
                'position' => 'Service Advisor',
                'department' => 'Customer Service',
                'status' => 'active',
            ]
        );

        $advisorRole = Role::where('name', 'service_advisor')->first();
        if ($advisorRole) {
            $advisorUser->roles()->sync([$advisorRole->id]);
        }

        $this->command->info('Roles, permissions, and users created successfully!');
        $this->command->info('Login credentials:');
        $this->command->info('Super Admin - Email: admin@admin.com, Password: danewcash54899');
        $this->command->info('Manager - Email: manager@carrepairs.com, Password: password');
        $this->command->info('Technician - Email: technician@carrepairs.com, Password: password');
        $this->command->info('Service Advisor - Email: advisor@carrepairs.com, Password: password');
    }
}
