<?php
namespace App\Controllers;

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

use App\Core\Database;

class AdminWorkflowBoardController
{
    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(), ['super_admin','org_admin','admin','organizer','conference_chair','track_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 ($this->role() !== 'super_admin' && (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() !== '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->conference();

        $stmt = $this->db()->prepare("
            SELECT *
            FROM conference_workflow_steps
            WHERE conference_id=?
              AND org_id=?
            ORDER BY step_group, sort_order, id
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $steps = $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $groups = [];
        foreach ($steps as $s) {
            $groups[$s['step_group']][] = $s;
        }

        $stats = [
            'total' => count($steps),
            'done' => count(array_filter($steps, fn($x) => (int)$x['is_done'] === 1)),
            'enabled' => count(array_filter($steps, fn($x) => (int)$x['is_enabled'] === 1)),
        ];

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

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

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

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

        $stmt = $this->db()->prepare("
            UPDATE conference_workflow_steps
            SET is_done = IF(is_done=1,0,1),
                done_by = IF(is_done=0, ?, NULL),
                done_at = IF(is_done=0, NOW(), NULL)
            WHERE id=?
              AND conference_id=?
              AND org_id=?
        ");
        $stmt->execute([(int)$_SESSION['user_id'], $id, (int)$conference['id'], (int)$conference['org_id']]);

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

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

        $stmt = $this->db()->prepare("
            UPDATE conference_workflow_steps
            SET is_enabled = IF(is_enabled=1,0,1)
            WHERE id=?
              AND conference_id=?
              AND org_id=?
        ");
        $stmt->execute([(int)($_GET['id'] ?? 0), (int)$conference['id'], (int)$conference['org_id']]);

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