<?php
namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/conference_scope.php';

use App\Core\Controller;
use App\Core\Database;
use App\Middleware\RoleGuard;

class AdminRoleMatrixController extends Controller
{
    public function index(): void
    {
        RoleGuard::allow(['super_admin','admin']);

        $db = Database::getInstance();
        $conference_id = $_GET['conference_id'] ?? null;

        if (!$conference_id) {
            echo "Conference not selected.";
            return;
        }

        $users = $db->query("SELECT id, first_name, last_name, email FROM users WHERE is_active=1")->fetchAll();

        $stmt = $db->prepare("SELECT * FROM conference_user_roles WHERE conference_id = ?");
        $stmt->execute([$conference_id]);
        $assignments = $stmt->fetchAll();

        ob_start();
        require BASE_PATH.'/app/views/admin/roles/matrix.php';
        $content = ob_get_clean();
        require BASE_PATH.'/app/views/layouts/admin_layout.php';
    }

    public function assign(): void
    {
        RoleGuard::allow(['super_admin','admin']);

        $db = Database::getInstance();

        $conference_id = $_POST['conference_id'];
        $user_id = $_POST['user_id'];
        $role_code = $_POST['role_code'];

        $stmt = $db->prepare("
            INSERT IGNORE INTO conference_user_roles
            (conference_id, user_id, role_code)
            VALUES (?,?,?)
        ");

        $stmt->execute([$conference_id, $user_id, $role_code]);

        header("Location: ".base_path("admin/roles?conference_id=".$conference_id));
        exit;
    }
}
