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

/* ===============================
   ✅ ADMIN AUTH CHECK
   =============================== */
if (!isset($_SESSION['user_id']) || strtolower($_SESSION['role']) !== 'admin') {
    http_response_code(403);
    exit("Access denied (Admin only)");
}

/* ===============================
   ✅ VALIDATE ID
   =============================== */
$id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($id <= 0) {
    http_response_code(400);
    exit("Invalid ID");
}

/* ===============================
   ✅ FETCH FILE PATH
   =============================== */
$stmt = $conn->prepare("SELECT file_path FROM products WHERE id=? LIMIT 1");

if (!$stmt) {
    exit("DB Error: " . $conn->error);
}

$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);
    exit("No file found in DB");
}

/* ===============================
   ✅ CLEAN PATH
   =============================== */
$file_relative = trim($row['file_path']);

// remove starting slash if exists
$file_relative = ltrim($file_relative, '/');

// build full path
$file_path = __DIR__ . '/../' . $file_relative;

/* ===============================
   ✅ CHECK FILE EXISTS
   =============================== */
if (!file_exists($file_path)) {
    http_response_code(404);

    // 🔥 DEBUG (temporary)
    echo "File not found<br>";
    echo "DB Path: " . htmlspecialchars($file_relative) . "<br>";
    echo "Server Path: " . htmlspecialchars($file_path);
    exit;
}

/* ===============================
   ✅ MIME TYPE
   =============================== */
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mime = $finfo->file($file_path);

if (!$mime) {
    $mime = "application/octet-stream";
}

$filename = basename($file_path);

/* ===============================
   ✅ OUTPUT HEADERS
   =============================== */
header("Content-Type: " . $mime);

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

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

/* ===============================
   ✅ OUTPUT FILE
   =============================== */
readfile($file_path);
exit;