<?php
// public/upload.php
session_start();
if (empty($_SESSION['lab_id'])) { header('Location: index.php'); exit; }
$config = require __DIR__ . '/../config.php';
require_once __DIR__ . '/../src/Signer.php';

$signer = new Signer($config);

$labId = (int)$_SESSION['lab_id'];

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: dashboard.php');
    exit;
}

// processar pfx (se enviado)
$pfxPath = null;
$pfxPassword = null;
if (!empty($_FILES['pfx']['tmp_name'])) {
    $uploadsDir = __DIR__ . '/../storage/uploads';
    if (!is_dir($uploadsDir)) mkdir($uploadsDir, 0755, true);
    $dest = $uploadsDir . '/pfx_upload_' . time() . '_' . basename($_FILES['pfx']['name']);
    if (move_uploaded_file($_FILES['pfx']['tmp_name'], $dest)) {
        $pfxPath = $dest;
        $pfxPassword = $_POST['pfx_password'] ?? null;
    }
}

// nome do laboratório (para rodapé)
$labName = trim($_POST['lab_name'] ?? '');

// validar arquivos
if (empty($_FILES['pdfs'])) {
    $_SESSION['error'] = 'Nenhum arquivo enviado';
    header('Location: dashboard.php');
    exit;
}

$files = $_FILES['pdfs'];
for ($i = 0; $i < count($files['name']); $i++) {
    $tmp = $files['tmp_name'][$i];
    $origName = $files['name'][$i];
    if (!$tmp) continue;
    $uploadsDir = __DIR__ . '/../storage/uploads';
    if (!is_dir($uploadsDir)) mkdir($uploadsDir, 0755, true);
    $stored = $uploadsDir . '/' . time() . '_' . preg_replace('/[^a-zA-Z0-9._-]/', '_', $origName);
    move_uploaded_file($tmp, $stored);

    try {
        $res = $signer->signPdfWithFooter($stored, $pfxPath, $pfxPassword, $labName, $labId);
        // opcional: você pode mostrar link para o arquivo assinado
    } catch (Exception $e) {
        // registrar erro
        file_put_contents(sys_get_temp_dir() . '/assinador_errors.txt', date('c') . " - Erro: " . $e->getMessage() . PHP_EOL, FILE_APPEND);
    }
}

// se usou pfx upload temporário, por segurança removemos o arquivo
if ($pfxPath && file_exists($pfxPath)) {
    // opcional: apagar após uso — comente se preferir manter
    unlink($pfxPath);
}

header('Location: dashboard.php');
exit;

