<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

requireLogin();
$currentUser = getCurrentUser();

$file = $_GET['file'] ?? '';
// Prevent directory traversal
$file = basename($file);
$filepath = __DIR__ . '/uploads/kyc_documents/' . $file;

if (empty($file) || !file_exists($filepath)) {
    header("HTTP/1.1 404 Not Found");
    exit("File not found.");
}

// Security Check:
// Administrators can view all documents.
// Normal users can only view their own uploaded documents.
$has_access = false;
if ($currentUser['role'] === 'admin') {
    $has_access = true;
} else {
    try {
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM kyc_records WHERE user_id = ? AND (doc1_file LIKE ? OR doc2_file LIKE ?)");
        $stmt->execute([$currentUser['id'], '%' . $file, '%' . $file]);
        if ($stmt->fetchColumn() > 0) {
            $has_access = true;
        }
    } catch (PDOException $e) {
        // Access remains false
    }
}

if (!$has_access) {
    header("HTTP/1.1 403 Forbidden");
    exit("Access denied.");
}

// Serve the file securely with correct MIME type
$mime = mime_content_type($filepath);
header("Content-Type: " . $mime);
header("Content-Length: " . filesize($filepath));
header("Content-Disposition: inline; filename=\"" . $file . "\"");
readfile($filepath);
exit();
