<?php
namespace Modules\Users\Controllers;

use Core\Controller;
use Core\Auth;
use Modules\Users\Models\RoleModel;

class RoleController extends Controller {
    private RoleModel $roleModel;

    public function __construct() {
        parent::__construct();
        $this->roleModel = new RoleModel();
    }

    public function index() {
        $this->requirePermission('users', 'view');
        $roles = $this->roleModel->getAllForOrg(Auth::orgId());
        $this->render('users/roles/index', ['roles' => $roles]);
    }

    public function create() {
        $this->requirePermission('users', 'edit');
        $this->render('users/roles/form', ['role' => null, 'rolePermissions' => []]);
    }

    public function store() {
        $this->requirePermission('users', 'edit');
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token.');
            $this->redirect('/users/roles/create');
        }

        $name = trim($this->getPost('name', ''));
        if (empty($name)) {
            $this->setFlash('error', 'Role name is required.');
            $this->redirect('/users/roles/create');
        }

        $data = [
            'org_id' => Auth::orgId(),
            'name' => $name,
            'description' => sanitize($this->getPost('description', '')),
            'is_system' => 0,
        ];
        $permissions = $_POST['permissions'] ?? [];

        $roleId = $this->roleModel->createRole($data, $permissions);
        logAudit('role_created', 'users', 'role', $roleId);
        $this->setFlash('success', 'Role created successfully.');
        $this->redirect('/users/roles');
    }

    public function edit($id) {
        $this->requirePermission('users', 'edit');
        $role = $this->roleModel->getRoleWithPermissions((int)$id);
        if (!$role || ((int)$role['org_id'] !== (int)Auth::orgId() && !$role['is_system'])) {
            $this->setFlash('error', 'Role not found.');
            $this->redirect('/users/roles');
        }
        $this->render('users/roles/form', ['role' => $role, 'rolePermissions' => $role['permissions']]);
    }

    public function update($id) {
        $this->requirePermission('users', 'edit');
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token.');
            $this->redirect('/users/roles/' . $id . '/edit');
        }

        $role = $this->roleModel->find((int)$id);
        if (!$role || (int)$role['org_id'] !== (int)Auth::orgId() || $role['is_system']) {
            $this->setFlash('error', 'This role cannot be modified.');
            $this->redirect('/users/roles');
        }

        $data = [
            'name' => trim($this->getPost('name', $role['name'])),
            'description' => sanitize($this->getPost('description', '')),
        ];
        $permissions = $_POST['permissions'] ?? [];

        $this->roleModel->updateRole((int)$id, $data, $permissions);
        logAudit('role_updated', 'users', 'role', (int)$id);
        $this->setFlash('success', 'Role updated successfully.');
        $this->redirect('/users/roles');
    }

    public function delete($id) {
        $this->requirePermission('users', 'edit');
        if (!$this->validateCsrf()) {
            $this->setFlash('error', 'Invalid security token.');
            $this->redirect('/users/roles');
        }

        $role = $this->roleModel->find((int)$id);
        if (!$role || (int)$role['org_id'] !== (int)Auth::orgId() || $role['is_system']) {
            $this->setFlash('error', 'This role cannot be deleted.');
            $this->redirect('/users/roles');
        }

        $this->roleModel->deleteRole((int)$id);
        logAudit('role_deleted', 'users', 'role', (int)$id);
        $this->setFlash('success', 'Role deleted successfully.');
        $this->redirect('/users/roles');
    }
}
