<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['user_id'])) {
    http_response_code(403);
    echo "Login required.";
    exit;
}

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

if ($id <= 0) {
    http_response_code(404);
    echo "Invalid file ID.";
    exit;
}

/* GET FILE PATH FROM DATABASE */
$stmt = $conn->prepare("SELECT file_path FROM products WHERE id=? LIMIT 1");
$stmt->bind_param("i",$id);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
$stmt->close();

if (!$row || empty($row['file_path'])) {
    http_response_code(404);
    echo "No file attached.";
    exit;
}

/* Build file path */
$file_path = __DIR__ . '/../' . $row['file_path'];

if (!file_exists($file_path)) {
    http_response_code(404);
    echo "File not found.";
    exit;
}

/* Get mime type */
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file_path) ?: 'application/octet-stream';

$filename = basename($file_path);

/* Show PDF & images inline */
if ($mime === 'application/pdf' || strpos($mime,'image/') === 0) {
    header("Content-Type: $mime");
    header("Content-Disposition: inline; filename=\"$filename\"");
} else {
    header("Content-Type: $mime");
    header("Content-Disposition: attachment; filename=\"$filename\"");
}

header("Content-Length: " . filesize($file_path));
header("X-Content-Type-Options: nosniff");

/* Output file */
readfile($file_path);
exit;