<?php
namespace App\Controllers;

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

use App\Core\Database;

class AdminWorkflowRulesController
{
    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 requireAccess(): 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'], 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->requireAccess();
        $conference = $this->conference();

        $stmt = $this->db()->prepare("
            SELECT *
            FROM conference_submission_stage_rules
            WHERE conference_id=?
              AND org_id=?
            ORDER BY FIELD(stage_key,
                'submitted','screening','reviewing','rebuttal','revision_required','revision_submitted',
                'accepted','rejected','camera_ready','production','galley','assigned_to_issue','published'
            ), stage_key
        ");
        $stmt->execute([(int)$conference['id'], (int)$conference['org_id']]);
        $rules = $stmt->fetchAll(\PDO::FETCH_ASSOC);

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

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

    public function save()
    {
$this->requireAccess();
        $conference = $this->conference();

        $rules = $_POST['rules'] ?? [];

        foreach ($rules as $id => $r) {
            $id = (int)$id;

            $stmt = $this->db()->prepare("
                UPDATE conference_submission_stage_rules
                SET allow_author_update=?,
                    allow_author_file_upload=?,
                    allow_rebuttal=?,
                    allow_camera_ready=?,
                    visible_to_author=?,
                    visible_reviews_to_author=?,
                    updated_at=NOW()
                WHERE id=?
                  AND conference_id=?
                  AND org_id=?
            ");
            $stmt->execute([
                !empty($r['allow_author_update']) ? 1 : 0,
                !empty($r['allow_author_file_upload']) ? 1 : 0,
                !empty($r['allow_rebuttal']) ? 1 : 0,
                !empty($r['allow_camera_ready']) ? 1 : 0,
                !empty($r['visible_to_author']) ? 1 : 0,
                !empty($r['visible_reviews_to_author']) ? 1 : 0,
                $id,
                (int)$conference['id'],
                (int)$conference['org_id']
            ]);
        }

        header("Location: /easychair/admin/workflow-rules?saved=1");
        exit;
    }
}
