<?php

namespace Database\Seeders;

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

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

        // HRM permissions to update
        $hrmPermissions = [
            // 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',

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

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

            // Payroll
            'view_payrolls',
            'create_payroll',
            'edit_payroll',
            'delete_payroll',
            'manage_payrolls',
            'generate_payroll',
            'approve_payroll',
        ];

        // Create HRM parent group if it doesn't exist
        $parentPermission = Permission::where('slug', 'manage_hrm')->first();

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

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

            Log::info('Created HRM parent permission with ID: ' . $parentPermission->id);
        }

        // Update existing permissions to HRM group
        $updatedCount = 0;
        foreach ($hrmPermissions as $permissionSlug) {
            $permission = Permission::where('slug', $permissionSlug)->first();

            if ($permission) {
                Log::info('Updating permission: ' . $permissionSlug . ' from group: ' . $permission->group . ' to group: hrm');

                $permission->group = 'hrm';
                $permission->parent_id = $parentPermission->id;
                $permission->path = $parentPermission->path . '.' . $permission->id;
                $permission->level = 1;
                $permission->save();

                $updatedCount++;
            } else {
                Log::info('Permission not found: ' . $permissionSlug . ', creating new one');

                // Create the permission if it doesn't exist
                $newPermission = Permission::create([
                    'parent_id' => $parentPermission->id,
                    'name' => ucfirst(str_replace('_', ' ', $permissionSlug)),
                    'slug' => $permissionSlug,
                    'group' => 'hrm',
                    'description' => 'صلاحية ' . ucfirst(str_replace('_', ' ', $permissionSlug)),
                    'level' => 1,
                    'path' => $parentPermission->path . '.' . ($parentPermission->id + 1), // Temporary path
                    'type' => 'action',
                    'resource' => explode('_', $permissionSlug)[1] ?? 'hrm',
                    'order' => 10,
                    'is_active' => true,
                ]);

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

        Log::info('Updated ' . $updatedCount . ' permissions to HRM group');

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

        Log::info('UpdateHRMPermissionsSeeder completed successfully');
    }
}
