<?php
namespace App\Services;

use App\Core\Database;

class WorkflowService
{
    public static function autoTransition(): void
    {
        $db = Database::getInstance();

        $today = date('Y-m-d H:i:s');

        $db->exec("
            UPDATE conferences
            SET status='open'
            WHERE submission_start <= '$today'
            AND submission_end >= '$today'
        ");

        $db->exec("
            UPDATE conferences
            SET status='reviewing'
            WHERE review_start <= '$today'
            AND review_end >= '$today'
        ");

        $db->exec("
            UPDATE conferences
            SET status='decision'
            WHERE decision_date <= '$today'
        ");
    }

    public static function canTransition(
        string $from,
        string $to,
        string $role
    ): bool
    {
        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT id
            FROM workflow_transitions
            WHERE from_status = ?
            AND to_status = ?
            AND allowed_role = ?
        ");

        $stmt->execute([
            $from,
            $to,
            $role
        ]);

        return $stmt->fetch() ? true : false;
    }


    public static function changeSubmissionStatus(
        int $submissionId,
        string $newStatus,
        int $userId,
        string $role
    ): void
    {
        $db = Database::getInstance();

        $stmt = $db->prepare("
            SELECT status
            FROM submissions
            WHERE id = ?
        ");

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

        $row = $stmt->fetch();

        if (!$row) {
            throw new \Exception("Submission not found");
        }

        $oldStatus = $row['status'];

        if (
            !self::canTransition(
                $oldStatus,
                $newStatus,
                $role
            )
        ) {
            throw new \Exception(
                "Transition not allowed"
            );
        }

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

        $stmt->execute([
            $newStatus,
            $userId,
            $submissionId
        ]);

        self::logStatusChange(
            $submissionId,
            $oldStatus,
            $newStatus,
            $userId
        );
    }


    private static function logStatusChange(
        int $submissionId,
        string $oldStatus,
        string $newStatus,
        int $userId
    ): void
    {
        $db = Database::getInstance();

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

        $stmt->execute([
            $submissionId,
            $oldStatus,
            $newStatus,
            $userId
        ]);

        $stmt = $db->prepare("
            INSERT INTO submission_activity_log
            (
                submission_id,
                actor_id,
                actor_role,
                event_key,
                event_title
            )
            VALUES
            (
                ?,
                ?,
                'system',
                'status.changed',
                CONCAT(
                    'Status changed from ',
                    ?,
                    ' to ',
                    ?
                )
            )
        ");

        $stmt->execute([
            $submissionId,
            $userId,
            $oldStatus,
            $newStatus
        ]);
    }

public static function transitionSubmissionStage(
    int $submissionId,
    int $userId
)
{
    $db =
        \App\Core\Database::getInstance();

    /*
    Load submission
    */

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

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

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

    if (!$submission) {

        throw new \Exception(
            "Submission not found."
        );

    }

    $currentStage =
        $submission['stage'];

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

    $orgId =
        (int)$submission['org_id'];

    /*
    Load enabled workflow stages
    */

    $stmt =
        $db->prepare("
            SELECT
                stage
            FROM conference_workflow
            WHERE conference_id = ?
            AND org_id = ?
            AND is_enabled = 1
            ORDER BY FIELD(
                stage,
                'submission',
                'screening',
                'review',
                'revision',
                'decision',
                'galley',
                'production',
                'issue',
                'published'
            )
        ");

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

    $stages =
        $stmt->fetchAll(
            \PDO::FETCH_COLUMN
        );

    if (!$stages) {

        throw new \Exception(
            "No workflow stages configured."
        );

    }

    /*
    Find next stage
    */

    $nextStage = null;

    foreach ($stages as $i => $stage) {

        if ($stage === $currentStage) {

            if (isset($stages[$i + 1])) {

                $nextStage =
                    $stages[$i + 1];

            }

            break;

        }

    }

    if (!$nextStage) {

        throw new \Exception(
            "No next stage available."
        );

    }

    /*
    Map stage → status
    */

    $statusMap = [

        'submission'
            => 'submitted',

        'screening'
            => 'screening',

        'review'
            => 'under_review',

        'revision'
            => 'revision_required',

        'decision'
            => 'accepted',

        'production'
            => 'production',

        'issue'
            => 'scheduled',

        'published'
            => 'published'

    ];

    $newStatus =
    $statusMap[$nextStage]
    ?? $submission['status'];

/*
ADD THIS BLOCK HERE
*/

if ($currentStage === 'review') {

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

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

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

    $requiredReviews = 2;

    if ($reviewCount < $requiredReviews) {

        throw new \Exception(
            "Cannot move to decision stage.
            Required reviews: "
            . $requiredReviews .
            "
            Submitted: "
            . $reviewCount
        );

    }

}


    /*
    Update submission
    */

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

    $stmt->execute([

        $nextStage,
        $newStatus,
        $userId,
        $submissionId

    ]);

    /*
    Log history
    */

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

    $stmt->execute([

        $submissionId,
        $submission['status'],
        $newStatus,
        $userId

    ]);

    error_log(
        "WORKFLOW TRANSITION: "
        . $submissionId
        . " "
        . $currentStage
        . " → "
        . $nextStage
    );

}

}
