<?php

namespace App\Controllers;

use App\Core\Database;

class ChairDecisionController
{
    private function requireAccess()
    {
        if (!isset($_SESSION['user_id'])) {

            header("Location: /easychair/login");
            exit;

        }

        $allowed = [

            'conference_chair',
            'org_admin',
            'super_admin'

        ];

        if (!in_array(
            $_SESSION['role_code'] ?? '',
            $allowed
        )) {

            http_response_code(403);

            die("Access denied.");

        }
    }

    public function index()
    {
        $this->requirePermission(
    'reviewer.assign',
    'view'
);

        $db =
            Database::getInstance();

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

        /*
        Submissions ready for decision
        */

        $stmt =
            $db->prepare("
                SELECT
                    s.id,
                    s.title,
                    s.stage,
                    s.status,

                    COUNT(r.id)
                        AS review_count,

                    ROUND(
                        AVG(r.overall_score),
                        2
                    ) AS avg_score

                FROM submissions s

                LEFT JOIN reviews r
                    ON r.submission_id = s.id

                WHERE s.conference_id = ?
                AND s.stage = 'decision'

                GROUP BY s.id

                ORDER BY s.id DESC
            ");

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

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

        error_log(
            "CHAIR DECISIONS: "
            . count($submissions)
        );

        require
            BASE_PATH .
            '/app/views/chair/decisions/index.php';
    }

    public function applyDecision()
    {
       $this->requirePermission(
    'reviewer.assign',
    'view'
);

        $db =
            Database::getInstance();

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

        $decision =
            trim($_POST['decision'] ?? '');

        if (!$submissionId || !$decision) {

            die("Invalid decision.");

        }

        /*
        Map decision → workflow
        */

        $status = 'under_review';
        $stage  = 'production';

        switch ($decision) {

            case 'accept':

                $status = 'accepted';
                $stage  = 'production';

                break;

            case 'minor_revision':
            case 'major_revision':

                $status = 'revision_required';
/*
-----------------------------------------
AUTO INCREMENT REVIEW ROUND
-----------------------------------------
*/

$db->prepare("
    UPDATE submissions
    SET current_round_no =
        current_round_no + 1
    WHERE id = ?
")->execute([
    $submissionId
]);
   //             $stage  = 'revision';

                break;

            case 'reject':

                $status = 'rejected';
                $stage  = 'decision';

                break;

        }

        /*
        Update submission
        */

        $db->prepare("
            UPDATE submissions
            SET
                status = ?,
                stage  = ?,
                decision = ?,
                updated_by = ?,
                updated_at = NOW()
            WHERE id = ?
        ")
        ->execute([

            $status,
            $stage,
            $decision,
            $_SESSION['user_id'],
            $submissionId

        ]);

        /*
        Log history
        */

        $db->prepare("
            INSERT INTO submission_status_history
            (
                submission_id,
                new_status,
                changed_by,
                created_at
            )
            VALUES
            (?, ?, ?, NOW())
        ")
        ->execute([

            $submissionId,
            $status,
            $_SESSION['user_id']

        ]);

        error_log(
            "CHAIR DECISION: submission="
            . $submissionId
            . " decision="
            . $decision
        );

        header(
            "Location: /easychair/chair/decisions"
        );

        exit;
    }
}
