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

if (!isset($_SESSION['phone'])) {
    header("Location: login.php");
    exit;
}

if (!isset($_GET['file']) || empty($_GET['file'])) {
    die("Invalid file request.");
}

$username = $_SESSION['phone'];

/* ===== GET FILE PATH ===== */
$file = urldecode($_GET['file']);

/* ===== SECURITY CHECKS ===== */

// Remove null bytes
$file = str_replace("\0", "", $file);

// Prevent directory traversal
if (strpos($file, '..') !== false) {
    die("Access denied.");
}

// Allow only pdf files
if (pathinfo($file, PATHINFO_EXTENSION) !== 'pdf') {
    die("Invalid file type.");
}

// Absolute path
$fullPath = realpath($file);

// Ensure file exists
if (!$fullPath || !file_exists($fullPath)) {
    die("File not found.");
}

/* ===== CHECK OWNERSHIP FROM HISTORY TABLE ===== */
$stmt = $ahk_conn->prepare("SELECT id FROM v1history WHERE link=? AND custno=? LIMIT 1");
$stmt->bind_param("ss", $file, $username);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    die("You are not authorized to access this file.");
}

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

readfile($fullPath);
exit;
?>
