<?php

class AdminReviewAssignmentController
{
    public function assign()
    {
        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {

            header('Location: /easychair/admin/submissions');
            exit;
        }

        require_once BASE_PATH . '/app/core/Database.php';

        $db =
            \App\Core\Database::getInstance();

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

        $reviewerId =
            (int)($_POST['reviewer_id'] ?? 0);

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

            $_SESSION['error'] =
                'Invalid assignment';

            header('Location: /easychair/admin/submissions');
            exit;
        }

        try {
/*
-----------------------------------------
LOAD CURRENT ROUND
-----------------------------------------
*/

$stmtRound = $db->prepare("
    SELECT current_round_no
    FROM submissions
    WHERE id = ?
    LIMIT 1
");

$stmtRound->execute([
    $submissionId
]);

$currentRoundNo =
    (int)(
        $stmtRound->fetchColumn()
        ?: 1
    );
            $stmt =
                $db->prepare("
                    INSERT INTO review_assignments
                    (
                        submission_id,
                        conference_id,
                        reviewer_id,
                        round_no,
			assigned_by,
                        status,
                        assigned_at
                    )
                    SELECT
                        s.id,
                        s.conference_id,
                        ?,
                        ?,
			?,
                        'assigned',
                        NOW()
                    FROM submissions s
                    WHERE s.id = ?
                ");

            $stmt->execute([
                $reviewerId,
                $_SESSION['user_id'] ?? null,
		$currentRoundNo,
                $submissionId
            ]);

\App\Services\SubmissionWorkflowService
    ::onReviewerAssigned(
        $submissionId,
        $_SESSION['user_id'] ?? null
    );

            $_SESSION['success'] =
                'Reviewer assigned successfully';


        } catch (\Throwable $e) {

            error_log(
                'REVIEW ASSIGN ERROR: '
                . $e->getMessage()
            );

            $_SESSION['error'] =
                $e->getMessage();
        }

        header('Location: /easychair/admin/submissions');
        exit;
    }
}
