<?php
namespace App\Controllers;

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

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

use App\Core\Database;

class AdminPrivilegeMatrixController
{
    protected function db()
    {
        return Database::getInstance();
    }

    private function startSession(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    private function role(): string
    {
        return (string)($_SESSION['conference_role'] ?? $_SESSION['role'] ?? $_SESSION['user_role'] ?? '');
    }

    private function requireAdmin(): void
    {
        $this->startSession();

        if (empty($_SESSION['user_id'])) {
            header("Location: /easychair/login");
            exit;
        }

        if (empty($_SESSION['conference_id'])) {
            header("Location: /easychair/select-conference");
            exit;
        }

        if (!in_array($this->role(), ['superadmin','org_admin','admin','conference_chair'], true)) {
            http_response_code(403);
            exit("Access denied.");
        }
    }

    private function conference(): array
    {
        $stmt = $this->db()->prepare("SELECT * FROM conferences WHERE id=? LIMIT 1");
        $stmt->execute([(int)$_SESSION['conference_id']]);
        $c = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$c) {
            exit("Conference not found.");
        }

        if (!ec_is_superadmin() && (int)$c['org_id'] !== (int)($_SESSION['org_id'] ?? 0)) {
            http_response_code(403);
            exit("Invalid organization access.");
        }

        return $c;
    }

    public function index()
    {

        // Pack512: non-superadmin bypasses selector safely.
        if (function_exists('ec_scope_role') && ec_scope_role() !== 'superadmin') {
            if (function_exists('ec_scope_auto_select_conference')) {
                // ec_scope_auto_select_conference(true);
            }
            $landing = function_exists('ec_scope_landing_url') ? ec_scope_landing_url() : '/easychair/admin/dashboard';
            header("Location: " . $landing);
            exit;
        }

$this->requireAdmin();
        $conference = $this->conference();

        $roles = $this->db()->query("SELECT * FROM roles ORDER BY id")->fetchAll(\PDO::FETCH_ASSOC);

        $catalog = $this->db()->query("
            SELECT *
            FROM conference_privilege_catalog
            WHERE is_active=1
            ORDER BY module_key, sort_order, privilege_key
        ")->fetchAll(\PDO::FETCH_ASSOC);

        $stmt = $this->db()->prepare("
            SELECT role_id, privilege_key, allowed
            FROM conference_role_privileges
            WHERE conference_id=?
              AND org_id=?
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $rows = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $matrix = [];
        foreach ($rows as $r) {
            $matrix[(int)$r['role_id']][$r['privilege_key']] = (int)$r['allowed'];
        }

        ob_start();
        require BASE_PATH . '/app/views/admin/privilege_matrix/index.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/admin_layout.php';
    }

    public function save()
    {
$this->requireAdmin();
        $conference = $this->conference();

        $roleId = (int)($_POST['role_id'] ?? 0);
        $privileges = $_POST['privileges'] ?? [];

        if ($roleId <= 0) {
            exit("Role required.");
        }

        $catalog = $this->db()->query("SELECT privilege_key FROM conference_privilege_catalog WHERE is_active=1")
            ->fetchAll(\PDO::FETCH_COLUMN);

        foreach ($catalog as $key) {
            $allowed = isset($privileges[$key]) ? 1 : 0;

            $stmt = $this->db()->prepare("
                INSERT INTO conference_role_privileges
                (org_id, conference_id, role_id, privilege_key, allowed, created_by)
                VALUES (?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE
                    allowed=VALUES(allowed),
                    updated_at=NOW()
            ");
            $stmt->execute([
                (int)$conference['org_id'],
                (int)$conference['id'],
                $roleId,
                $key,
                $allowed,
                (int)$_SESSION['user_id']
            ]);
        }

        header("Location: /easychair/admin/privilege-matrix?role_id=" . $roleId . "&saved=1");
        exit;
    }
}
