<?php

namespace App\Services;

use App\Core\Database;

class StageTransitionService
{
    /*
    -----------------------------------------
    Check if stage is active
    -----------------------------------------
    */

    public static function canEnterStage(
        int $conferenceId,
        string $stage
    ): bool
    {
        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT is_active
            FROM submission_stage_rules
            WHERE conference_id = ?
            AND stage_key = ?
            LIMIT 1
        ");

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

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

        if (!$active) {

            error_log(
                "STAGE BLOCKED (inactive): " . $stage
            );

            return false;
        }

        return true;
    }

    /*
    -----------------------------------------
    Check review completion requirement
    -----------------------------------------
    */

    public static function isReviewCompleteRequired(
        int $conferenceId,
        string $stage,
        int $submissionId
    ): bool
    {
        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT require_review_complete
            FROM submission_stage_rules
            WHERE conference_id = ?
            AND stage_key = ?
            LIMIT 1
        ");

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

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

        if (!$required) {
            return true;
        }

        /*
        Count completed reviews
        */

        $stmt = $db->prepare("
            SELECT COUNT(*)
            FROM review_assignments
            WHERE submission_id = ?
            AND status = 'completed'
        ");

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

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

        if ($count === 0) {

            error_log(
                "BLOCKED: no completed reviews for submission "
                . $submissionId
            );

            return false;
        }

        return true;
    }

    /*
    -----------------------------------------
    Master validator
    -----------------------------------------
    */

    public static function validateTransition(
        int $conferenceId,
        string $targetStage,
        int $submissionId
    ): bool
    {
        if (!self::canEnterStage(
            $conferenceId,
            $targetStage
        )) {
            return false;
        }

        if (!self::isReviewCompleteRequired(
            $conferenceId,
            $targetStage,
            $submissionId
        )) {
            return false;
        }

        return true;
    }
}
