<?php

namespace App\Services;

use App\Core\Database;
use App\Services\StageTransitionService;

class WorkflowDecisionService
{
    public static function applyDecision(
        int $submissionId,
        string $recommendation,
        int $userId
    ): void
    {
        $db = Database::getInstance();

        /*
        -----------------------------------------
        Load submission
        -----------------------------------------
        */

        $stmt = $db->prepare("
            SELECT
                id,
                conference_id,
                org_id,
                stage
            FROM submissions
            WHERE id = ?
            LIMIT 1
        ");

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

        $submission =
            $stmt->fetch(\PDO::FETCH_ASSOC);

        if (!$submission) {

            error_log(
                "DECISION ERROR: submission not found: "
                . $submissionId
            );

            return;
        }

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

        $currentStage =
            $submission['stage'];

        /*
        -----------------------------------------
        Map recommendation → logical stage
        -----------------------------------------
        */

        $targetStage = 'review';
        $status      = 'under_review';

        switch ($recommendation) {

            case 'accept':

                $targetStage = 'production';
                $status      = 'accepted';

                break;

            case 'minor_revision':
            case 'major_revision':

                $targetStage = 'revision';
                $status      = 'revision_required';

                break;

            case 'reject':

                $targetStage = 'decision';
                $status      = 'rejected';

                break;
        }

        /*
        -----------------------------------------
        Verify stage exists and is active
        -----------------------------------------
        */

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

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

        $stageExists =
            $stmt->fetchColumn();

        if (!$stageExists) {

            error_log(
                "DECISION WARNING: stage disabled: "
                . $targetStage
            );

            return;
        }

        /*
        -----------------------------------------
        PACK 572 — Transition Guard (NEW)
        -----------------------------------------
        */

if (!$stageExists) {

    error_log(
        "DECISION WARNING: stage disabled: "
        . $targetStage
    );

    return;
}

/*
-----------------------------------------
Guard transition (PACK 572)
-----------------------------------------
*/

if (
    !StageTransitionService::canEnterStage(
        $conferenceId,
        $targetStage
    )
) {

    error_log(
        "TRANSITION BLOCKED: inactive stage "
        . $targetStage
    );

    return;

}

if (
    !StageTransitionService::isReviewCompleteRequired(
        $conferenceId,
        $targetStage,
        $submissionId
    )
) {

    error_log(
        "TRANSITION BLOCKED: review incomplete for submission "
        . $submissionId
    );

    return;

}

        if (
            !StageTransitionService::validateTransition(
                $conferenceId,
                $targetStage,
                $submissionId
            )
        ) {

            error_log(
                "TRANSITION BLOCKED: submission="
                . $submissionId
                . " from="
                . $currentStage
                . " to="
                . $targetStage
            );

            return;

        }

        /*
        -----------------------------------------
        Update submission
        -----------------------------------------
        */

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

        $stmt->execute([

            $status,
            $targetStage,
            $userId,
            $submissionId

        ]);

        /*
        -----------------------------------------
        Log status history
        -----------------------------------------
        */

        $stmt = $db->prepare("
            INSERT INTO submission_status_history
            (
                submission_id,
                new_status,
                changed_by,
                created_at
            )
            VALUES
            (?, ?, ?, NOW())
        ");

        $stmt->execute([

            $submissionId,
            $status,
            $userId

        ]);

        error_log(
            "DECISION APPLIED: submission="
            . $submissionId
            . " status="
            . $status
            . " stage="
            . $targetStage
        );
    }
}
