<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Controller;
use App\Core\Database;

final class AdminProductionWorkflowController extends Controller
{
    public function setStep(): void
    {
        require_permission('admin.access');
        if (!$this->isPost()) redirect('admin/submissions');
        csrf_check();

        $db = Database::getInstance();
        $submissionId = (int)($_POST['submission_id'] ?? 0);
        $step = trim((string)($_POST['step'] ?? ''));
        $revisionUntil = trim((string)($_POST['revision_open_until'] ?? ''));

        if ($submissionId <= 0 || $step === '') {
            flash('danger', trans('required_fields'));
            redirect('admin/submissions/view?id='.$submissionId);
        }

        // Map to statuses
        $status = $step;
        if ($step === 'copyediting') $status = 'copyediting';
        if ($step === 'galley') $status = 'galley';
        if ($step === 'published') $status = 'published';
        if ($step === 'minor_revision' || $step === 'major_revision') $status = 'revision';

        $params = [':st'=>$status, ':id'=>$submissionId];

        $sql = "UPDATE submissions SET status=:st";
        if ($status === 'revision') {
            // open revision window if provided (datetime-local)
            if ($revisionUntil !== '') {
                $dt = date('Y-m-d H:i:s', strtotime($revisionUntil));
                $sql .= ", revision_open_until=:ru";
                $params[':ru'] = $dt;
            }
        }
        $sql .= " WHERE id=:id";

        $db->prepare($sql)->execute($params);

        flash('success', trans('save'));
        redirect('admin/submissions/view?id='.$submissionId);
    }
}
