<?php
declare(strict_types=1);

namespace App\Controllers;

require_once BASE_PATH . '/app/helpers/permissions.php';

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

final class AuthorSubmissionFilesController 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'); }

        $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/submission_files/index', ['sub'=>$sub, 'files'=>$files]);
    }

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

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

        $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'); }

        if (empty($_FILES['file']['tmp_name'])) {
            flash('danger', trans('required_fields'));
            redirect('author/submission/files?submission_id='.$submissionId);
        }

        $allowed = ['pdf','doc','docx','zip'];
        $origName = basename((string)$_FILES['file']['name']);
        $ext = strtolower(pathinfo($origName, PATHINFO_EXTENSION));
        if (!in_array($ext, $allowed, true)) {
            flash('danger', 'File must be pdf/doc/docx/zip');
            redirect('author/submission/files?submission_id='.$submissionId);
        }

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

        $new = 'sub_' . $submissionId . '_' . time() . '_' . bin2hex(random_bytes(3)) . '.' . $ext;
        $dest = $destDir . '/' . $new;

        if (!move_uploaded_file((string)$_FILES['file']['tmp_name'], $dest)) {
            flash('danger', 'Upload failed');
            redirect('author/submission/files?submission_id='.$submissionId);
        }

        $path = 'uploads/submissions/' . $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]);

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