<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);

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

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

$username = $_SESSION['phone'];

/* ================= VALIDATE FILE PARAM ================= */
if (!isset($_GET['file']) || empty($_GET['file'])) {
    die("File not specified.");
}

$file = $_GET['file'];

/* Prevent directory traversal */
$file = str_replace(['../', './'], '', $file);

/* ================= CHECK IN DATABASE ================= */
$stmt = $ahk_conn->prepare("
    SELECT link FROM history 
    WHERE custno = ? AND link = ? AND type='rc'
    LIMIT 1
");
$stmt->bind_param("ss", $username, $file);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("Access denied.");
}

$row = $result->fetch_assoc();
$filepath = $row['link'];

/* ================= CHECK FILE EXISTS ================= */
if (!file_exists($filepath)) {
    die("File not found.");
}

/* ================= FORCE DOWNLOAD ================= */
header('Content-Description: File Transfer');
header('Content-Type: application/pdf');
header('Content-Disposition: inline; filename="' . basename($filepath) . '"');
header('Content-Length: ' . filesize($filepath));
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Expires: 0');

readfile($filepath);
exit;
?>