<?php
require_once dirname(__DIR__, 2) . '/config.php';

// --- CORS Headers Start ---
header('Access-Control-Allow-Headers: Authorization, Content-Type');
if (!defined('ALLOWED_ORIGINS') || empty(ALLOWED_ORIGINS)) {
    header('Access-Control-Allow-Origin: *');
} else {
    $allowedOrigins = is_array(ALLOWED_ORIGINS) ? ALLOWED_ORIGINS : [ALLOWED_ORIGINS];
    if (isset($_SERVER['HTTP_ORIGIN']) && in_array($_SERVER['HTTP_ORIGIN'], $allowedOrigins)) {
        header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
        header('Access-Control-Allow-Credentials: true');
    }
}
header('Access-Control-Allow-Methods: GET, OPTIONS');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit();
}

// --- CORS Headers End ---
try {
    $db = new Database();
    $user = Session::Validate($db); // Strictly validates $headers['Authorization']
    
    $id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
    $type = isset($_GET['type']) ? trim($_GET['type']) : '';
    
    if ($id <= 0 || empty($type)) {
        throw new Exception("Missing parameters", 400);
    }
    
    // Fetch file path from database securely using ID
    $stmt = $db->link->prepare("SELECT photo_path, pdf_file_path FROM ekyc_webhook_logs WHERE id = ? LIMIT 1");
    $stmt->execute([$id]);
    $log = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$log) {
        throw new Exception("Record not found.", 404);
    }
    
    $file = ($type === 'photo') ? $log['photo_path'] : $log['pdf_file_path'];
    
    if (empty($file)) {
        throw new Exception("File path not found in record.", 404);
    }
    
    // if (strpos($file, '..') !== false || !preg_match('/^[0-9]{4}\/[0-9]{2}\/[a-zA-Z0-9_\-\.]+\.(jpg|pdf)$/i', $file)) {
    if (strpos($file, '..') !== false || !preg_match('/^[0-9]{4}\/[0-9]{2}\/([0-9]{2}\/)?[a-zA-Z0-9_\-\.]+\.(jpg|pdf)$/i', $file)) {    
        throw new Exception("Invalid file path.", 400);
    }
  
    // --- Dynamic Single Path Resolution Start ---
    $baseDir = rtrim($db->getStoragePath(), '/') . '/ekycData/uploads/';
    $absolutePath = realpath($baseDir . $file);
    
    // Secure validation to prevent directory traversal
    if (!$absolutePath || !file_exists($absolutePath) || strpos($absolutePath, realpath($baseDir)) !== 0) {
        throw new Exception("File not found on server.", 404);
    }
    
    if ($type === 'photo' && preg_match('/\.jpg$/i', $file)) {
        header('Content-Type: image/jpeg');
    } elseif ($type === 'pdf' && preg_match('/\.pdf$/i', $file)) {
        header('Content-Type: application/pdf');
        header('Content-Disposition: inline; filename="' . basename($file) . '"');
    } else {
        throw new Exception("Unsupported file type.", 400);
    }
    
    readfile($absolutePath);
    exit();

} catch (Exception $e) {
    http_response_code($e->getCode() ?: 401);
    echo "Error: " . $e->getMessage();
}