<?php
require __DIR__ . '/_auth.php';
require_admin();
$pdo = db();
if (!$pdo) {
    http_response_code(404);
    exit('Not found');
}
$id = (int) (isset($_GET['id']) ? $_GET['id'] : 0);
$stmt = $pdo->prepare('SELECT payment_proof_path FROM orders WHERE id = ? LIMIT 1');
$stmt->execute(array($id));
$order = $stmt->fetch();
if (!$order || empty($order['payment_proof_path'])) {
    http_response_code(404);
    exit('Payment proof not found');
}
$relative = str_replace(array('..', "\0"), '', (string) $order['payment_proof_path']);
$path = realpath(__DIR__ . '/../' . ltrim($relative, '/'));
$base = realpath(__DIR__ . '/../storage/payment_proofs');
if (!$path || !$base || strpos($path, $base) !== 0 || !is_file($path)) {
    http_response_code(404);
    exit('Payment proof not found');
}
$ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
$types = array(
    'jpg' => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'png' => 'image/png',
    'webp' => 'image/webp',
    'pdf' => 'application/pdf',
);
header('Content-Type: ' . (isset($types[$ext]) ? $types[$ext] : 'application/octet-stream'));
header('Content-Length: ' . filesize($path));
header('X-Content-Type-Options: nosniff');
readfile($path);
exit;
