<?php
require_once __DIR__ . '/auth.php';
require_login();
check_csrf();
require_once __DIR__ . '/config.php';

$loan_id = (int)($_POST['loan_id'] ?? 0);
if (!$loan_id) { http_response_code(400); exit('ID inválido'); }

if (!is_dir($UPLOAD_DIR)) { @mkdir($UPLOAD_DIR, 0775, true); }

if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
  exit('Falha no upload');
}

$size = $_FILES['file']['size'];
$type = mime_content_type($_FILES['file']['tmp_name']);
$name = $_FILES['file']['name'];

if ($size > $MAX_UPLOAD_BYTES) { exit('Arquivo muito grande'); }
if (!in_array($type, $ALLOWED_MIME, true)) { exit('Tipo de arquivo não permitido'); }

$ext = pathinfo($name, PATHINFO_EXTENSION) ?: 'bin';
$dest = $UPLOAD_DIR . '/' . $loan_id . '_' . bin2hex(random_bytes(8)) . '.' . $ext;

if (!move_uploaded_file($_FILES['file']['tmp_name'], $dest)) { exit('Erro ao salvar arquivo'); }

$st = $pdo->prepare('INSERT INTO loan_terms (loan_id, filename_original, filepath, uploaded_by) VALUES (?,?,?,?)');
$st->execute([$loan_id, $name, basename($dest), current_user()['id']]);

header('Location: ' . base_url('loan_view.php?id='.$loan_id));
