<?php
error_reporting(0);
include('includes/dbconnection.php');

$id = mysqli_real_escape_string($con, $_GET["id"]);

$sql = "SELECT file_data, filename, File_Name, file_type, file_size FROM document WHERE id = '$id' LIMIT 1";
$result = mysqli_query($con, $sql);

if ($row = mysqli_fetch_assoc($result)) {
    // MIME map for extensions
    $mime_map = [
        'application/pdf' => 'pdf',
        'application/msword' => 'doc',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' => 'docx',
        'application/vnd.ms-excel' => 'xls',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' => 'xlsx',
        'image/jpeg' => 'jpg',
        'image/png' => 'png',
        'text/plain' => 'txt',
    ];




    $ext = isset($mime_map[$row['file_type']]) ? $mime_map[$row['file_type']] : 'bin';
    $filename = $row['File_Name'].'.' . $ext;
  

    // Send headers
    header('Content-Description: File Transfer');
    header('Content-Type: ' . $row['file_type']);
    header('Content-Disposition: inline; filename="' . $filename . '"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . $row['file_size']);
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Expires: 0');

    // Clear output buffers to avoid corrupting file
    while (ob_get_level()) {
        ob_end_clean();
    }

    // Output binary file data
    echo $row['file_data'];
    exit;
} else {
    http_response_code(404);
    echo "File not found.";
}

mysqli_close($con);
?>

