<?php
session_start();
include('con.php');

if (!isset($_SESSION['username'])) {
    die("Unauthorized access.");
}

$username = $_SESSION['username'];
$id = mysqli_real_escape_string($ahk_conn, $_GET['id']);

// Securely fetch the link
$res = mysqli_query($ahk_conn, "SELECT link, number, type FROM dl_history WHERE id='$id' AND custno='$username'");
$data = mysqli_fetch_assoc($res);

if ($data) {
    $filePath = $data['link'];
    
    // Check if the file exists on the server
    if (file_exists($filePath)) {
        // Clear buffer to prevent PDF corruption
        ob_clean();
        flush();

        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="'.$data['type'].'_'.$data['number'].'.pdf"');
        header('Content-Length: ' . filesize($filePath));
        
        readfile($filePath);
        exit;
    } else {
        die("Error: The PDF file has been moved or deleted from the server.");
    }
} else {
    die("Record not found.");
}
?>