<?php
session_start();
require_once 'functions.php';
// Also load main/admin DB connection for audit logging
require_once 'main_db_connect.php';

// Check if user is logged in
if (!isset($_SESSION['username'])) {
    header("Location: ../index.php");
    exit();
}

if (isset($_GET['id'])) {
    $documentId = (int)$_GET['id'];
    // Get file information from pmed_documents table (use pmed DB connection)
    $dbConn = isset($conn2) ? $conn2 : $conn; // prefer pmed DB connection
    $stmt = $dbConn->prepare("SELECT pmed_file_name, pmed_file_path, pmed_file_type FROM pmed_documents WHERE pmed_document_id = ?");
    $stmt->bind_param("i", $documentId);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $file = $result->fetch_assoc();
        $filePath = $file['pmed_file_path'];
        $fileName = $file['pmed_file_name'];
        $fileType = $file['pmed_file_type'];
        
        // Normalize path
        $normalized = str_replace('\\', '/', $filePath);
        
        // Check if it's an absolute server path that contains /uploads/
        // e.g., /home/ppdconline/pmed.lagunappdco.online/uploads/file.jpg
        // Convert to web URL for better compatibility
        if (preg_match('#^/home/[^/]+/pmed\.lagunappdco\.online(/uploads/.+)$#', $normalized, $matches)) {
            // Extract the /uploads/... portion and convert to web URL
            $uploadsPath = $matches[1];
            $normalized = 'https://pmed.lagunappdco.online' . $uploadsPath;
            // For downloads, redirect to the web URL
            header('Location: ' . $normalized);
            exit();
        }
        
        // Check if file exists (try both original and normalized paths)
        $resolvedPath = null;
        if (file_exists($filePath)) {
            $resolvedPath = $filePath;
        } else if ($normalized !== $filePath && file_exists($normalized)) {
            $resolvedPath = $normalized;
        }
        
        if ($resolvedPath) {
            // Set headers for download
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
            header('Content-Length: ' . filesize($resolvedPath));
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            // Clear output buffer
            ob_clean();
            flush();
            // Audit log: downloaded a file from Gender and development
            if (function_exists('logAction')) {
                $userId = $_SESSION['user_id'] ?? 0;
                $username = $_SESSION['username'] ?? 'Guest';
                // Use admin DB connection ($conn) to write audit log
                logAction(isset($conn) ? $conn : null, $userId, $username, "downloaded a file from Gender and Development (pmed)", $documentId, $fileName);
            }
            // Read and output file
            readfile($resolvedPath);
            exit();
        } else {
            echo "File not found on server.";
        }
    } else {
        echo "Document not found in database.";
    }
    $stmt->close();
} else {
    echo "No document ID provided.";
}
?>
