<?php
class RoleController {
    private $db;
    public function __construct() { $this->db = Database::getInstance(); }

    public function index() {
        $cid = Auth::user()['company_id'];
        $roles = $this->db->fetchAll("SELECT r.*, (SELECT COUNT(*) FROM users WHERE role_id=r.id AND deleted_at IS NULL) as user_count FROM roles r WHERE (r.company_id=? OR r.company_id IS NULL) AND r.deleted_at IS NULL ORDER BY r.name", [$cid]);
        require 'app/views/roles/index.php';
    }

    public function create() {
        $role = null; $cid = Auth::user()['company_id'];
        $permissions = $this->db->fetchAll("SELECT * FROM permissions ORDER BY module, name");
        $rolePermissions = [];
        require 'app/views/roles/form.php';
    }

    public function store() {
        CSRF::verify();
        $v = new Validator($_POST); $v->required('name');
        if ($v->fails()) { flash('error', implode('<br>', $v->errors())); redirect('?page=roles&action=create'); }
        $this->db->insert('roles', [
            'company_id' => Auth::user()['company_id'], 'name' => $_POST['name'],
            'description' => $_POST['description'] ?? null, 'is_system' => 0,
        ]);
        $roleId = $this->db->lastInsertId();
        if (!empty($_POST['permissions'])) {
            foreach ($_POST['permissions'] as $pid) { $this->db->insert('role_permissions', ['role_id' => $roleId, 'permission_id' => $pid]); }
        }
        flash('success', 'Role created.'); redirect('?page=roles');
    }

    public function edit($id) {
        $cid = Auth::user()['company_id'];
        $role = $this->db->fetch("SELECT * FROM roles WHERE id=? AND (company_id=? OR company_id IS NULL) AND deleted_at IS NULL", [$id, $cid]);
        if (!$role) { flash('error', 'Role not found.'); redirect('?page=roles'); }
        $permissions = $this->db->fetchAll("SELECT * FROM permissions ORDER BY module, name");
        $rolePermissions = $this->db->fetchAll("SELECT permission_id FROM role_permissions WHERE role_id=?", [$id]);
        $rolePermissions = array_column($rolePermissions, 'permission_id');
        require 'app/views/roles/form.php';
    }

    public function update($id) {
        CSRF::verify(); $cid = Auth::user()['company_id'];
        $role = $this->db->fetch("SELECT * FROM roles WHERE id=? AND company_id=?", [$id, $cid]);
        if (!$role || $role['is_system']) { flash('error', 'Cannot edit system roles.'); redirect('?page=roles'); }
        $this->db->update('roles', ['name' => $_POST['name'], 'description' => $_POST['description'] ?? null], 'id = ?', [$id]);
        $this->db->query("DELETE FROM role_permissions WHERE role_id = ?", [$id]);
        if (!empty($_POST['permissions'])) {
            foreach ($_POST['permissions'] as $pid) { $this->db->insert('role_permissions', ['role_id' => $id, 'permission_id' => $pid]); }
        }
        flash('success', 'Role updated.'); redirect('?page=roles');
    }

    public function delete($id) {
        CSRF::verify(); $cid = Auth::user()['company_id'];
        $role = $this->db->fetch("SELECT * FROM roles WHERE id=? AND company_id=?", [$id, $cid]);
        if (!$role || $role['is_system']) { flash('error', 'Cannot delete system roles.'); redirect('?page=roles'); }
        $this->db->query("UPDATE users SET role_id=NULL WHERE role_id=? AND company_id=?", [$id, $cid]);
        $this->db->query("DELETE FROM role_permissions WHERE role_id=?", [$id]);
        $this->db->softDelete('roles', 'id = ?', [$id]);
        flash('success', 'Role deleted.'); redirect('?page=roles');
    }
}
