<?php

namespace App\Controllers;

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

use App\Core\Database;
use App\Core\Controller;
use App\Services\WorkflowDecisionService;

class AdminDecisionController extends Controller
{
    private function startSession()
    {
        if (session_status() !== PHP_SESSION_ACTIVE) {
            session_start();
        }
    }

    private function requireChair()
    {
        $this->startSession();

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

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

        if (!in_array($role, [
            'conference_chair',
            'track_chair',
            'admin',
            'superadmin'
        ])) {
            die("Access denied.");
        }
    }

    /*
    --------------------------------------------------
    Decision Board
    --------------------------------------------------
    */

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

        $db = Database::getInstance();

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

        $stmt = $db->prepare("
            SELECT
                s.id,
                COALESCE(s.title, s.title_en, s.title_ar) AS title,
                s.status,
                s.stage,

                COUNT(DISTINCT rv.id) AS reviews_count,
                ROUND(AVG(rv.score),2) AS avg_score

            FROM submissions s
            LEFT JOIN reviews rv
                ON rv.submission_id = s.id

            WHERE s.conference_id = ?

            GROUP BY s.id
            ORDER BY s.id DESC
        ");

        $stmt->execute([$conferenceId]);

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

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

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

    /*
    --------------------------------------------------
    Apply Decision
    --------------------------------------------------
    */

    public function apply()
    {
        $this->requireChair();

        $submissionId = (int)($_POST['submission_id'] ?? 0);
        $decision     = $_POST['decision'] ?? '';

        if (!$submissionId || !$decision) {
            die("Invalid input");
        }

        WorkflowDecisionService::applyDecision(
            $submissionId,
            $decision,
            $_SESSION['user_id']
        );

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