<?php

require_once BASE_PATH . '/app/controllers/admin/AdminBaseController.php';
require_once BASE_PATH . '/app/models/Permission.php';

class AdminPermissionController extends AdminBaseController
{
    private Permission $permissionModel;

    public function __construct()
    {
        parent::__construct();
        $this->requireAdmin();
        $this->permissionModel = new Permission();
    }

    public function index(): void
    {
        $matrix = $this->permissionModel->getMatrix();
        $matrixRows = Permission::matrixDefinition();
        require BASE_PATH . '/app/views/admin/permissions/index.php';
    }

    public function update(): void
    {
        $this->requirePost();
        $this->validateCsrf();

        $submittedPermissions = $_POST['permissions'] ?? [];
        $submittedPermissions = is_array($submittedPermissions)
            ? $submittedPermissions
            : [];

        try {
            $this->mutateAndLog(
                fn () => $this->permissionModel->saveMatrix($submittedPermissions),
                'admin.role_permissions.update',
                'role_permission',
                null,
                ['roles' => ['customer', 'owner']],
                true
            );
            $this->flashSuccess('Đã cập nhật quyền menu và quyền truy cập cho Customer/Owner.');
        } catch (Throwable $error) {
            $this->flashError($error->getMessage());
        }

        $this->redirect('admin/permissions');
    }
}
