<?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 AdminSubmissionFilesController extends Controller
{
    public function index(): void
    {
        require_permission('admin.access');
        $db = Database::getInstance();

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

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

        $fs = $db->prepare("SELECT sf.*, u.email AS uploader_email
                            FROM submission_files sf
                            LEFT JOIN users u ON u.id=sf.uploaded_by
                            WHERE sf.submission_id=:sid 
                            ORDER BY sf.uploaded_at DESC, sf.id DESC");
        $fs->execute([':sid'=>$submissionId]);
        $files = $fs->fetchAll();

        $this->view('admin/submissions/files', ['sub'=>$sub, 'files'=>$files]);
    }

    public function upload(): void
    {
        require_permission('admin.access');
        if (!$this->isPost()) redirect('admin/submissions');
        csrf_check();

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

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

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

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

        $new = 'prod_' . $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('admin/submissions/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'=>(int)auth_id()]);

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