<?php
namespace App\Controllers;

use App\Core\Database;

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

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

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

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

        $role = ec_scope_role();

        if (!in_array($role, ['super_admin','org_admin','admin','conference_chair','organizer','track_chair','section_editor'], true)) {
            http_response_code(403);
            exit('Access denied.');
        }
    }

    public function index()
    {
        $this->requireAdmin();

        if (function_exists('ec_scope_auto_select_conference') && ec_scope_role() !== 'super_admin') {
            ec_scope_auto_select_conference(false);
        }

        $session = $_SESSION;

        $conference = null;
        if (!empty($_SESSION['conference_id'])) {
            $stmt = $this->db()->prepare("SELECT * FROM conferences WHERE id=? LIMIT 1");
            $stmt->execute([(int)$_SESSION['conference_id']]);
            $conference = $stmt->fetch(\PDO::FETCH_ASSOC) ?: null;
        }

        $user = null;
        if (!empty($_SESSION['user_id'])) {
            $stmt = $this->db()->prepare("SELECT * FROM users WHERE id=? LIMIT 1");
            $stmt->execute([(int)$_SESSION['user_id']]);
            $user = $stmt->fetch(\PDO::FETCH_ASSOC) ?: null;
        }

        $available = function_exists('ec_scope_available_conferences') ? ec_scope_available_conferences() : [];
        $landing = function_exists('ec_access_landing_for_role') ? ec_access_landing_for_role() : '';

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

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