<?php

namespace App\Services;

use App\Core\Database;

class ReviewCompletionService
{
    public static function checkCompletion(
        int $submissionId,
        int $conferenceId,
        int $userId
    ): void
    {
        $db =
            Database::getInstance();

        /*
        Get minimum reviewers
        */

        $stmt =
            $db->prepare("
                SELECT min_reviewers
                FROM conference_review_settings
                WHERE conference_id = ?
                LIMIT 1
            ");

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

        $minReviewers =
            (int)$stmt->fetchColumn();

        if (!$minReviewers) {

            $minReviewers = 2;

        }

        /*
        Count completed reviews
        */

        $stmt =
            $db->prepare("
                SELECT COUNT(*)
                FROM reviews
                WHERE submission_id = ?
                AND submitted_at IS NOT NULL
            ");

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

        $completed =
            (int)$stmt->fetchColumn();

        error_log(
            "REVIEW COUNT: submission="
            . $submissionId
            . " completed="
            . $completed
            . " required="
            . $minReviewers
        );

        /*
        If requirement met → move to decision
        */

        if ($completed >= $minReviewers) {

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

            /*
            Log history
            */

            $db->prepare("
                INSERT INTO submission_status_history
                (
                    submission_id,
                    new_status,
                    changed_by,
                    created_at
                )
                VALUES
                (?, 'decision', ?, NOW())
            ")
            ->execute([
                $submissionId,
                $userId
            ]);

            error_log(
                "AUTO TRANSITION: submission="
                . $submissionId
                . " → decision"
            );

        }

    }
}
