<?php
declare(strict_types=1);

namespace App\Modules\Users\Controllers;

use App\Core\Controller;
use App\Core\Request;
use App\Core\Response;
use App\Core\App;
use App\Core\Registries\PermissionRegistry;
use App\Modules\Users\Models\Employee;
use App\Modules\Roles\Models\Role;

class UserPermissionController extends Controller
{
    public function edit(Request $request, string $id): Response
    {
        $employee = Employee::find((int) $id);
        if (!$employee) {
            return $this->redirect('/users')->withError('الموظف غير موجود');
        }

        $allPermissions = PermissionRegistry::getAllGrouped();
        $allRoles = Role::allActive();
        $employeeRoles = $employee->getRolesWithNames();
        $currentRoleIds = array_column($employeeRoles, 'id');

        $roleExpirations = [];
        foreach ($employeeRoles as $er) {
            $roleExpirations[(int) $er['id']] = $er['expires_at'] ?? '';
        }

        $db = App::getInstance()->db();
        $rolePermMap = [];
        foreach ($employeeRoles as $er) {
            $perms = $db->select(
                "SELECT permission_key FROM role_permissions WHERE role_id = ?",
                [(int) $er['id']]
            );
            foreach ($perms as $p) {
                $rolePermMap[$p['permission_key']][] = $er['name_ar'];
            }
        }

        $directPerms = $employee->getDirectPermissions();
        $directMap = [];
        foreach ($directPerms as $dp) {
            $directMap[$dp['permission_key']] = (int) $dp['is_denied'] === 1 ? 'deny' : 'grant';
        }

        return $this->view('Users.Views.permissions', [
            'employee'        => $employee,
            'allPermissions'  => $allPermissions,
            'allRoles'        => $allRoles,
            'currentRoleIds'  => $currentRoleIds,
            'roleExpirations' => $roleExpirations,
            'rolePermMap'     => $rolePermMap,
            'directMap'       => $directMap,
        ]);
    }

    public function update(Request $request, string $id): Response
    {
        $employee = Employee::find((int) $id);
        if (!$employee) {
            return $this->redirect('/users')->withError('الموظف غير موجود');
        }

        $db = App::getInstance()->db();
        $currentEmp = App::getInstance()->currentEmployee();
        $grantedBy = $currentEmp ? (int) $currentEmp->id : 0;

        $db->delete('employee_roles', '`employee_id` = ?', [$employee->id]);
        $roleIds = $request->post('roles', []);
        $roleExpires = $request->post('role_expires', []);
        if (is_array($roleIds)) {
            foreach ($roleIds as $roleId) {
                $expiresAt = $roleExpires[$roleId] ?? null;
                $db->insert('employee_roles', [
                    'employee_id' => (int) $employee->id,
                    'role_id'     => (int) $roleId,
                    'assigned_at' => date('Y-m-d H:i:s'),
                    'assigned_by' => $grantedBy,
                    'expires_at'  => ($expiresAt && $expiresAt !== '') ? $expiresAt : null,
                    'is_active'   => 1,
                ]);
            }
        }

        $permStates = $request->post('perm_state', []);
        $grants = [];
        $denials = [];
        if (is_array($permStates)) {
            foreach ($permStates as $key => $state) {
                if ($state === 'grant') {
                    $grants[] = $key;
                } elseif ($state === 'deny') {
                    $denials[] = $key;
                }
            }
        }

        $employee->syncDirectPermissions($grants, $denials, $grantedBy);

        return $this->redirect("/users/{$id}/permissions")->withSuccess('تم تحديث الصلاحيات بنجاح');
    }
}
