<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/functions.php';
require_login();
$pdo = get_db();

$type = $_GET['type'] ?? '';
$id = (int)($_GET['id'] ?? 0);
if (!in_array($type, ['cv', 'doc'], true) || !$id) {
    http_response_code(400);
    die('Invalid request.');
}

$stmt = $pdo->prepare('SELECT * FROM applications WHERE id = ?');
$stmt->execute([$id]);
$app = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$app) { http_response_code(404); die('Not found.'); }

$pathCol = $type === 'cv' ? 'cv_path' : 'doc_path';
$nameCol = $type === 'cv' ? 'cv_original_name' : 'doc_original_name';

if (empty($app[$pathCol])) { http_response_code(404); die('No file on record.'); }

$filePath = UPLOAD_DIR . basename($app[$pathCol]);
if (!is_file($filePath)) { http_response_code(404); die('File missing from server.'); }

$downloadName = $app[$nameCol] ?: basename($filePath);
$ext = strtolower(pathinfo($filePath, PATHINFO_EXTENSION));
$mimes = ['pdf' => 'application/pdf', 'doc' => 'application/msword', 'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'];

header('Content-Type: ' . ($mimes[$ext] ?? 'application/octet-stream'));
header('Content-Disposition: attachment; filename="' . str_replace('"', '', $downloadName) . '"');
header('Content-Length: ' . filesize($filePath));
readfile($filePath);
exit;
