<?php
namespace App\Controllers;

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

use App\Core\Database;

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

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

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

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

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

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

    private function conferenceId(): int
    {
        return (int)($_SESSION['conference_id'] ?? $_SESSION['current_conference_id'] ?? 0);
    }

    private function orgId(): int
    {
        return (int)($_SESSION['org_id'] ?? 0);
    }

    private function assertConference(): array
    {
        $cid = $this->conferenceId();

        if ($cid <= 0) {
            header("Location: /easychair/select-conference");
            exit;
        }

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

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

        if ($this->role() !== 'super_admin') {
            if ((int)$conf['org_id'] !== $this->orgId()) {
                http_response_code(403);
                exit("Invalid conference access.");
            }

            $stmt = $this->db()->prepare("
                SELECT id
                FROM user_conferences
                WHERE user_id = ?
                  AND conference_id = ?
                LIMIT 1
            ");
            $stmt->execute([(int)$_SESSION['user_id'], $cid]);

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

        return $conf;
    }

    private function ensureWorkflow(int $conferenceId, int $orgId): void
    {
        $db = $this->db();

        $stmt = $db->prepare("
            INSERT INTO workflow_settings (conference_id, org_id, review_rounds, allow_revision, auto_decision)
            SELECT ?, ?, 1, 1, 0
            WHERE NOT EXISTS (
                SELECT 1 FROM workflow_settings WHERE conference_id = ?
            )
        ");
        $stmt->execute([$conferenceId, $orgId, $conferenceId]);

        $stages = [
            'submission',
            'screening',
            'review',
            'revision',
            'decision',
            'galley',
            'production',
            'issue',
            'published'
        ];

        foreach ($stages as $stage) {
            $stmt = $db->prepare("
                INSERT INTO conference_workflow (conference_id, stage, is_enabled, org_id)
                SELECT ?, ?, 1, ?
                WHERE NOT EXISTS (
                    SELECT 1
                    FROM conference_workflow
                    WHERE conference_id = ?
                      AND stage = ?
                )
            ");
            $stmt->execute([$conferenceId, $stage, $orgId, $conferenceId, $stage]);
        }
    }

    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->requireAdmin();

        $conference = $this->assertConference();

        $conferenceId = (int)$conference['id'];
        $orgId = (int)$conference['org_id'];

        $this->ensureWorkflow($conferenceId, $orgId);

        $stmt = $this->db()->prepare("
            SELECT *
            FROM workflow_settings
            WHERE conference_id = ?
              AND org_id = ?
            LIMIT 1
        ");
        $stmt->execute([$conferenceId, $orgId]);
        $settings = $stmt->fetch(\PDO::FETCH_ASSOC);

        $stmt = $this->db()->prepare("
            SELECT *
            FROM conference_workflow
            WHERE conference_id = ?
              AND org_id = ?
            ORDER BY FIELD(stage,'submission','screening','review','revision','decision','galley','production','issue','published'), id
        ");
        $stmt->execute([$conferenceId, $orgId]);
        $workflowStages = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

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

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

        $conference = $this->assertConference();
        $conferenceId = (int)$conference['id'];
        $orgId = (int)$conference['org_id'];

        $type = $_GET['type'] ?? 'stage';
        $id = (int)($_GET['id'] ?? 0);

        if ($type === 'stage' && $id > 0) {
            $stmt = $this->db()->prepare("
                UPDATE conference_workflow
                SET is_enabled = IF(is_enabled=1,0,1)
                WHERE id = ?
                  AND conference_id = ?
                  AND org_id = ?
            ");
            $stmt->execute([$id, $conferenceId, $orgId]);
        }

        if ($type === 'revision') {
            $stmt = $this->db()->prepare("
                UPDATE workflow_settings
                SET allow_revision = IF(allow_revision=1,0,1)
                WHERE conference_id = ?
                  AND org_id = ?
            ");
            $stmt->execute([$conferenceId, $orgId]);
        }

        if ($type === 'auto_decision') {
            $stmt = $this->db()->prepare("
                UPDATE workflow_settings
                SET auto_decision = IF(auto_decision=1,0,1)
                WHERE conference_id = ?
                  AND org_id = ?
            ");
            $stmt->execute([$conferenceId, $orgId]);
        }

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

    public function change()
    {
        return $this->toggle();
    }
}
