<?php
namespace App\Controllers;

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

use App\Core\Database;

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

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

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

        $role = $_SESSION['role'] ?? $_SESSION['user_role'] ?? '';

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

    public function index()
    {

        // Pack512: non-superadmin bypasses selector safely.
        if (function_exists('ec_scope_role') && ec_scope_role() !== 'super_admin') {
            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->requireAccess();

        $db = Database::getInstance();

        $role = $_SESSION['role'] ?? '';
        $orgId = (int)($_SESSION['org_id'] ?? 0);

        if ($role === 'super_admin') {
            $stmt = $db->query("
                SELECT 
                    c.*,
                    o.name AS org_name,
                    p.conference_id AS org_current_conference_id,
                    COUNT(DISTINCT s.id) AS submissions_count,
                    COUNT(DISTINCT uc.user_id) AS members_count
                FROM conferences c
                LEFT JOIN organizations o ON o.id = c.org_id
                LEFT JOIN org_conference_policy p ON p.org_id = c.org_id
                LEFT JOIN submissions s ON s.conference_id = c.id
                LEFT JOIN user_conferences uc ON uc.conference_id = c.id
                GROUP BY c.id
                ORDER BY c.org_id ASC, c.id DESC
            ");
            $conferences = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        } else {
            $stmt = $db->prepare("
                SELECT 
                    c.*,
                    o.name AS org_name,
                    p.conference_id AS org_current_conference_id,
                    COUNT(DISTINCT s.id) AS submissions_count,
                    COUNT(DISTINCT uc.user_id) AS members_count
                FROM conferences c
                LEFT JOIN organizations o ON o.id = c.org_id
                LEFT JOIN org_conference_policy p ON p.org_id = c.org_id
                LEFT JOIN submissions s ON s.conference_id = c.id
                LEFT JOIN user_conferences uc ON uc.conference_id = c.id
                WHERE c.org_id = ?
                GROUP BY c.id
                ORDER BY c.id DESC
            ");
            $stmt->execute([$orgId]);
            $conferences = $stmt->fetchAll(\PDO::FETCH_ASSOC);
        }

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

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

    public function changeStatus()
    {
        $this->requireAccess();

        $db = Database::getInstance();

        $id = (int)($_POST['id'] ?? $_GET['id'] ?? $_SESSION['conference_id'] ?? 0);
        $status = trim((string)($_POST['status'] ?? $_GET['status'] ?? ''));

        $allowed = ['draft','open','reviewing','decision','published','archived'];

        if ($id <= 0 || !in_array($status, $allowed, true)) {
            http_response_code(400);
            exit("Invalid conference/status.");
        }

        if (($_SESSION['role'] ?? '') !== 'super_admin') {
            $stmt = $db->prepare("
                SELECT id
                FROM conferences
                WHERE id = ?
                  AND org_id = ?
                LIMIT 1
            ");
            $stmt->execute([$id, (int)($_SESSION['org_id'] ?? 0)]);

            if (!$stmt->fetchColumn()) {
                http_response_code(403);
                exit("Invalid organization conference access.");
            }
        }

        $stmt = $db->prepare("
            UPDATE conferences
            SET status = ?,
                updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$status, $id]);

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

    public function setCurrent()
    {
        $this->requireAccess();

        $db = Database::getInstance();

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

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

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

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

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

        $stmt = $db->prepare("
            INSERT INTO org_conference_policy (org_id, conference_id, policy_note, created_by)
            VALUES (?, ?, 'Current organization conference set from conference manager', ?)
            ON DUPLICATE KEY UPDATE
                conference_id = VALUES(conference_id),
                policy_note = VALUES(policy_note),
                updated_at = NOW()
        ");
        $stmt->execute([(int)$conf['org_id'], $id, (int)$_SESSION['user_id']]);

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