<?php
declare(strict_types=1);

namespace App\Controllers;

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

final class AuthorRevisionController extends Controller
{
    public function index(): void
    {
        require_login();
        $db = Database::getInstance();

        $submissionId = (int)($_GET['submission_id'] ?? 0);
        $uid = (int)auth_id();

        $st = $db->prepare("SELECT * FROM submissions WHERE id=:id AND author_id=:uid LIMIT 1");
        $st->execute([':id'=>$submissionId, ':uid'=>$uid]);
        $sub = $st->fetch();
        if (!$sub) { http_response_code(404); exit('Not found'); }

        $openUntil = $sub['revision_open_until'] ?? null;
        $isOpen = $openUntil ? (strtotime((string)$openUntil) >= time()) : false;

        $fs = $db->prepare("SELECT * FROM submission_files WHERE submission_id=:sid AND is_active=1 ORDER BY uploaded_at DESC, id DESC");
        $fs->execute([':sid'=>$submissionId]);
        $files = $fs->fetchAll();

        $this->view('author/revision/index', ['sub'=>$sub, 'files'=>$files, 'is_open'=>$isOpen]);
    }

    public function submit(): void
    {
        require_login();
        if (!$this->isPost()) redirect('author/dashboard');
        csrf_check();

        $db = Database::getInstance();
        $uid = (int)auth_id();
        $submissionId = (int)($_POST['submission_id'] ?? 0);

        $st = $db->prepare("SELECT * FROM submissions WHERE id=:id AND author_id=:uid LIMIT 1");
        $st->execute([':id'=>$submissionId, ':uid'=>$uid]);
        $sub = $st->fetch();
        if (!$sub) { http_response_code(403); exit('Forbidden'); }

        $openUntil = $sub['revision_open_until'] ?? null;
        if (!$openUntil || strtotime((string)$openUntil) < time()) {
            flash('danger', trans('revision_window') . ': closed');
            redirect('author/submission/revision?submission_id='.$submissionId);
        }

        // Revised version (required)
        if (empty($_FILES['revised_file']['tmp_name'])) {
            flash('danger', trans('required_fields'));
            redirect('author/submission/revision?submission_id='.$submissionId);
        }

        $destDir = __DIR__ . '/../../storage/uploads/revisions';
        if (!is_dir($destDir)) @mkdir($destDir, 0775, true);

        $saveOne = function(string $field, string $cat) use ($submissionId, $uid, $db, $destDir): void {
            if (empty($_FILES[$field]['tmp_name'])) return;

            $origName = basename((string)$_FILES[$field]['name']);
            $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
            if (!in_array($ext, ['pdf','doc','docx','zip'], true)) {
                throw new \RuntimeException("File must be pdf/doc/docx/zip");
            }

            $new = 'rev_' . $submissionId . '_' . time() . '_' . bin2hex(random_bytes(3)) . '.' . $ext;
            $dest = $destDir . '/' . $new;
            if (!move_uploaded_file((string)$_FILES[$field]['tmp_name'], $dest)) {
                throw new \RuntimeException("Upload failed");
            }
            $path = 'uploads/revisions/' . $new;

            $ins = $db->prepare("INSERT INTO submission_files (submission_id, file_category, file_path, original_name, uploaded_by, uploaded_at)
                                 VALUES (:sid,:cat,:fp,:on,:by,NOW())");
            $ins->execute([':sid'=>$submissionId, ':cat'=>$cat, ':fp'=>$path, ':on'=>$origName, ':by'=>$uid]);
        };

        try {
            $saveOne('revised_file', 'revised_version');
            $saveOne('response_letter', 'response_letter');
        } catch (\Throwable $e) {
            flash('danger', $e->getMessage());
            redirect('author/submission/revision?submission_id='.$submissionId);
        }

        // Move status forward (still under review, but revision delivered)
        $db->prepare("UPDATE submissions SET status='under_review' WHERE id=:id")->execute([':id'=>$submissionId]);

        flash('success', trans('save'));
        redirect('author/submission/revision?submission_id='.$submissionId);
    }
}
