<?php

namespace Database\Seeders;

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

class HRMPermissionsSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // Log the start of the seeder
        \Log::info('Starting HRMPermissionsSeeder');

        // Create HRM permissions
        $permissions = [
            // Employees
            'view_employees',
            'create_employee',
            'edit_employee',
            'delete_employee',
            'manage_employees',

            // Departments
            'view_departments',
            'create_department',
            'edit_department',
            'delete_department',
            'manage_departments',

            // Attendance
            'view_attendance',
            'create_attendance',
            'edit_attendance',
            'delete_attendance',
            'manage_attendance',

            // Leaves
            'view_leaves',
            'create_leave',
            'edit_leave',
            'delete_leave',
            'approve_leave',
            'reject_leave',
            'manage_leaves',

            // Leave Types
            'view_leave_types',
            'create_leave_type',
            'edit_leave_type',
            'delete_leave_type',
            'manage_leave_types',

            // Salaries
            'view_salaries',
            'create_salary',
            'edit_salary',
            'delete_salary',
            'manage_salaries',

            // Salary Components
            'view_salary_components',
            'create_salary_component',
            'edit_salary_component',
            'delete_salary_component',
            'manage_salary_components',

            // Payroll
            'view_payroll',
            'create_payroll',
            'edit_payroll',
            'delete_payroll',
            'manage_payroll',
            'approve_payroll',
            'mark_payroll_as_paid',
            'export_payroll',
            'view_payslips',

            // Bonuses
            'view_bonuses',
            'create_bonus',
            'edit_bonus',
            'delete_bonus',
            'approve_bonus',
            'reject_bonus',
            'mark_bonus_as_paid',
            'manage_bonuses',

            // Loans
            'view_loans',
            'create_loan',
            'edit_loan',
            'delete_loan',
            'approve_loan',
            'reject_loan',
            'activate_loan',
            'complete_loan',
            'cancel_loan',
            'manage_loans',

            // Loan Installments
            'view_loan_installments',
            'edit_loan_installment',
            'mark_loan_installment_as_paid',
            'mark_loan_installment_as_overdue',
            'cancel_loan_installment',
            'manage_loan_installments',
        ];

        // Create permissions if they don't exist
        foreach ($permissions as $permission) {
            // Check if permission already exists
            $existingPermission = Permission::where('slug', $permission)->first();

            if (!$existingPermission) {
                // Set all permissions to HRM group
                $group = 'hrm';

                // Check if HRM parent group exists
                $parentPermission = Permission::where('slug', 'manage_' . $group)->first();

                // Log parent permission check
                \Log::info('Checking for parent permission: manage_' . $group);

                // Create HRM parent group if it doesn't exist
                if (!$parentPermission) {
                    \Log::info('Creating parent permission for group: ' . $group);
                    $parentPermission = Permission::create([
                        'name' => 'إدارة الموارد البشرية',
                        'slug' => 'manage_' . $group,
                        'group' => $group,
                        'description' => 'إدارة كاملة لنظام الموارد البشرية',
                        'level' => 0,
                        'path' => null,
                        'type' => 'group',
                        'resource' => $group,
                        'order' => 0,
                        'is_active' => true,
                    ]);

                    // Update path after creation
                    $parentPermission->path = $parentPermission->id;
                    $parentPermission->save();
                }

                if ($parentPermission) {
                    \Log::info('Creating permission: ' . $permission);
                    $newPermission = Permission::create([
                        'parent_id' => $parentPermission->id,
                        'name' => ucfirst(str_replace('_', ' ', $permission)),
                        'slug' => $permission,
                        'group' => $group,
                        'description' => 'صلاحية ' . ucfirst(str_replace('_', ' ', $permission)),
                        'level' => 1,
                        'path' => null,
                        'type' => 'action',
                        'resource' => explode('_', $permission)[1] ?? $group,
                        'order' => 10,
                        'is_active' => true,
                    ]);

                    // Update path after creation
                    $newPermission->path = $parentPermission->path . '.' . $newPermission->id;
                    $newPermission->save();
                }
            }
        }

        // Assign permissions to admin role
        $adminRole = Role::where('slug', 'admin')->first();
        if ($adminRole) {
            $permissionIds = Permission::whereIn('slug', $permissions)->pluck('id')->toArray();
            \Log::info('Found ' . count($permissionIds) . ' permissions to assign to admin role');
            $adminRole->permissions()->syncWithoutDetaching($permissionIds);
        } else {
            \Log::error('Admin role not found');
        }

        // Assign view permissions to user role
        $userRole = Role::where('slug', 'user')->first();
        if ($userRole) {
            $viewPermissionIds = Permission::whereIn('slug', array_filter($permissions, function ($permission) {
                return strpos($permission, 'view_') === 0;
            }))->pluck('id')->toArray();
            $userRole->permissions()->syncWithoutDetaching($viewPermissionIds);
        }

        // Create HR role if it doesn't exist
        $hrRole = Role::where('slug', 'hr')->first();
        if (!$hrRole) {
            $hrRole = Role::create([
                'name' => 'مسؤول الموارد البشرية',
                'slug' => 'hr',
                'description' => 'مسؤول الموارد البشرية مع صلاحيات إدارة الموظفين والرواتب',
                'is_system_role' => true,
                'level' => 0,
                'path' => '6',
                'order' => 6,
                'is_active' => true,
                'is_default' => false,
            ]);
        }

        // Assign HR permissions to HR role
        if ($hrRole) {
            $permissionIds = Permission::whereIn('slug', $permissions)->pluck('id')->toArray();
            $hrRole->permissions()->syncWithoutDetaching($permissionIds);
        }

        $this->command->info('HRM permissions created and assigned successfully!');
    }
}
