<?php

namespace App\Services;

use App\Core\Database;

class WorkflowService
{
    public const MAP = [
        'submitted' => ['under_review'],
        'under_review' => ['revision_required','accepted','rejected'],
        'revision_required' => ['resubmitted'],
        'resubmitted' => ['under_review'],
        'accepted' => ['camera_ready'],
        'camera_ready' => ['scheduled'],
        'scheduled' => ['published'],
    ];

    public static function can(string $from, string $to): bool
    {
        return in_array($to, self::MAP[$from] ?? [], true);
    }

    public static function move(int $submissionId, string $to, int $userId, string $notes=''): bool
    {
        $db = Database::getInstance();

        $q = $db->prepare("SELECT workflow_stage FROM submissions WHERE id=? LIMIT 1");
        $q->execute([$submissionId]);
        $from = (string)($q->fetchColumn() ?: 'submitted');

        if (!self::can($from, $to)) {
            return false;
        }

        $db->prepare("
            UPDATE submissions
            SET workflow_stage=?, workflow_updated_at=NOW()
            WHERE id=?
        ")->execute([$to, $submissionId]);

        $db->prepare("
            INSERT INTO submission_workflow_history
            (submission_id, from_stage, to_stage, changed_by, notes)
            VALUES (?,?,?,?,?)
        ")->execute([$submissionId, $from, $to, $userId ?: null, $notes]);

        return true;
    }
}
