<?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 ConferenceSelectController
{
    protected function db()
    {
        return Database::getInstance();
    }

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

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

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

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

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

        $db = $this->db();

/* 🔥 SUPERADMIN AUTO-BYPASS
   ONLY WHEN NOT MANUAL ACCESS
*/

$manualAccess =
    isset($_GET['manual']);

if (
    (ec_is_superadmin())
    && !$manualAccess
) {

    $stmt = $db->query("
        SELECT id, org_id
        FROM conferences
        ORDER BY id ASC
        LIMIT 1
    ");

    $conf = $stmt->fetch(\PDO::FETCH_ASSOC);

    if ($conf) {

        $_SESSION['conference_id']
            = (int)$conf['id'];

        $_SESSION['org_id']
            = (int)$conf['org_id'];
    }

    $_SESSION['conference_role']
        = 'superadmin';

    header("Location: /easychair/admin/dashboard");
    exit;
}

        /* NORMAL USERS */
        //if (function_exists('ec_scope_role') && ec_scope_role() !== 'superadmin') {

/* NORMAL USERS ONLY */
if (
    !$manualAccess
    &&
    function_exists('ec_scope_role')
    &&
    ec_scope_role() !== 'superadmin'
) {
            $landing = function_exists('ec_scope_landing_url')
                ? ec_scope_landing_url()
                : '/easychair/admin/dashboard';

            header("Location: " . $landing);
            exit;
        }

        /* SUPERADMIN (MANUAL VIEW IF NEEDED) */
        $role = $this->role();
        $userId = (int)$_SESSION['user_id'];

        $stmt = $db->query("
            SELECT c.*, o.name AS org_name
            FROM conferences c
            LEFT JOIN organizations o ON o.id = c.org_id
            ORDER BY c.id DESC
        ");

        $conferences = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        ob_start();
        require BASE_PATH . '/app/views/conference/select.php';
        $content = ob_get_clean();

        require BASE_PATH . '/app/views/layouts/header.php';
        echo $content;
        require BASE_PATH . '/app/views/layouts/footer.php';
    }

    public function select()
    {
        $this->requireLogin();

        $db = $this->db();

        $conferenceId = (int)($_POST['conference_id'] ?? $_GET['conference_id'] ?? 0);

        if ($conferenceId <= 0) {
            exit("Conference is required.");
        }

        $stmt = $db->prepare("
            SELECT *
            FROM conferences
            WHERE id = ?
            LIMIT 1
        ");
        $stmt->execute([$conferenceId]);
        $conference = $stmt->fetch(\PDO::FETCH_ASSOC);

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

        /* 🔥 SUPERADMIN DIRECT ACCESS */
        if (ec_is_superadmin()) {

            $_SESSION['conference_id'] = $conferenceId;
            $_SESSION['org_id'] = (int)$conference['org_id'];
            $_SESSION['conference_role'] = 'superadmin';

            header("Location: /easychair/admin/dashboard");
            exit;
        }

        /* NORMAL USERS VALIDATION */
        $stmt = $db->prepare("
            SELECT uc.*, r.code AS role_code
            FROM user_conferences uc
            LEFT JOIN roles r ON r.id = uc.role_id
            WHERE uc.user_id = ?
              AND uc.conference_id = ?
            LIMIT 1
        ");
        $stmt->execute([(int)$_SESSION['user_id'], $conferenceId]);
        $membership = $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$membership) {
            http_response_code(403);
            exit("You are not assigned to this conference.");
        }

        $_SESSION['conference_role_id'] = (int)($membership['role_id'] ?? 0);
        $_SESSION['conference_role'] = (string)($membership['role_code'] ?? '');

        $_SESSION['conference_id'] = $conferenceId;
        $_SESSION['org_id'] = (int)$conference['org_id'];

        if (!isset($_SESSION['conference_list']) || !is_array($_SESSION['conference_list'])) {
            $_SESSION['conference_list'] = [];
        }

        if (!in_array($conferenceId, $_SESSION['conference_list'], true)) {
            $_SESSION['conference_list'][] = $conferenceId;
        }

        /* REDIRECT BASED ON ROLE */
        $effectiveRole = $_SESSION['conference_role'];

        if (in_array($effectiveRole, ['org_admin','admin','organizer','conference_chair','track_chair'], true)) {
            $redirect = '/easychair/admin/dashboard';
        } elseif ($effectiveRole === 'reviewer') {
            $redirect = '/easychair/reviewer/dashboard';
        } else {
            $redirect = '/easychair/author/dashboard';
        }

        header("Location: " . $redirect);
        exit;
    }
}
