<?php

class RoleController extends Controller
{
    public function index(): void
    {
        Auth::requirePermission('roles', 'view');
        $roleModel = new Role();
        $this->view('admin.roles.index', [
            'pageTitle' => 'Roles & Permissions',
            'roles'     => $roleModel->allWithUserCount(),
        ]);
    }

    public function permissions(): void
    {
        Auth::requirePermission('roles', 'view');
        $roleId = (int) $this->input('role_id');
        $roleModel = new Role();
        $role = $roleModel->find($roleId);
        if (!$role) {
            $this->redirect('admin/settings?tab=roles');
            return;
        }
        $this->view('admin.roles.permissions', [
            'pageTitle' => 'Permissions: ' . $role['role_name'],
            'role'      => $role,
            'matrix'    => $roleModel->permissionMatrix($roleId),
            'csrf'      => $this->csrfField(),
        ]);
    }

    public function savePermissions(): void
    {
        Auth::requirePermission('roles', 'edit');
        $this->verifyCsrf();

        $roleId = (int) $this->input('role_id');
        $roleModel = new Role();
        $role = $roleModel->find($roleId);
        if (!$role) {
            $this->redirect('admin/settings?tab=roles');
            return;
        }
        // System roles (OWNER) permissions are locked to always-full-access
        if ((bool) $role['is_system']) {
            $this->redirect('admin/settings?tab=roles');
            return;
        }

        $perms = $this->input('perm', []); // perm[permission_id][view|add|edit|delete] = 1
        $db = Database::getConnection();

        $stmt = $db->prepare(
            "INSERT INTO role_permissions (role_id, permission_id, can_view, can_add, can_edit, can_delete)
             VALUES (:role_id, :permission_id, :can_view, :can_add, :can_edit, :can_delete)
             ON DUPLICATE KEY UPDATE can_view = VALUES(can_view), can_add = VALUES(can_add),
                can_edit = VALUES(can_edit), can_delete = VALUES(can_delete)"
        );

        $allPerms = $db->query("SELECT id FROM permissions")->fetchAll();
        foreach ($allPerms as $p) {
            $pid = $p['id'];
            $set = $perms[$pid] ?? [];
            $stmt->execute([
                'role_id'       => $roleId,
                'permission_id' => $pid,
                'can_view'      => isset($set['view']) ? 1 : 0,
                'can_add'       => isset($set['add']) ? 1 : 0,
                'can_edit'      => isset($set['edit']) ? 1 : 0,
                'can_delete'    => isset($set['delete']) ? 1 : 0,
            ]);
        }

        AuditLogger::log(Auth::id(), 'ROLE_PERMISSIONS_UPDATE', 'roles', "Updated permissions for role #{$roleId}");
        $this->redirect('admin/settings?tab=roles');
    }
}
