<?php
session_start();
// Load admin-scoped helpers and database connections
require_once 'functions.php'; // provides $conn (main) and $conn2 (pmed_db) and helper functions

// Always use pmed_documents table for file paths
if (isset($_GET['id'])) {
    $documentId = intval($_GET['id']);

    // Query the pmed_documents table using the pmed DB connection ($conn2 when available)
    $db = isset($conn2) ? $conn2 : $conn;
    $stmt = $db->prepare("SELECT pmed_file_path, pmed_file_name, pmed_file_type FROM pmed_documents WHERE pmed_document_id = ?");
    if (!$stmt) {
        error_log('view.php prepare failed: ' . ($db->error ?? 'unknown'));
        echo "Error preparing query.";
        exit;
    }
    $stmt->bind_param('i', $documentId);
    $stmt->execute();
    $stmt->store_result();

    if ($stmt->num_rows === 0) {
        echo "Document not found.";
        $stmt->close();
        exit;
    }

    $stmt->bind_result($filePath, $fileName, $fileType);
    $stmt->fetch();
    $stmt->close();

    if (!$filePath) {
        echo "File path not specified.";
        exit;
    }

    // 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
    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;
        header('Location: ' . $normalized);
        exit;
    }

    // If the path looks like a URL (http(s)://), redirect to it
    if (preg_match('#^https?://#i', $normalized)) {
        header('Location: ' . $normalized);
        exit;
    }

    // If it's a relative path starting with /uploads, build absolute URL
    if (strpos($normalized, '/uploads/') === 0) {
        $normalized = 'https://pmed.lagunappdco.online' . $normalized;
        header('Location: ' . $normalized);
        exit;
    }

    // Check if it's an absolute server path (starts with /home/) that exists
    // Try to serve it directly if the file exists
    if (preg_match('#^/home/#', $normalized) && file_exists($normalized)) {
        $resolvedPath = $normalized;
        goto serve_file;
    }

    // Otherwise, attempt to serve local file with best-effort resolution
    $tries = [];
    // If looks absolute (Windows drive or starting slash, but not already handled /home/ paths)
    if (preg_match('#^[A-Za-z]:/#', $normalized) || (strpos($normalized, '/') === 0 && !preg_match('#^/home/#', $normalized))) {
        $tries[] = $normalized;
    } else {
        // Try relative to project root
        $projectRoot = realpath(__DIR__);
        if ($projectRoot) $tries[] = $projectRoot . '/' . ltrim($normalized, '/');
        // Try relative to uploads directory
        if ($projectRoot) $tries[] = $projectRoot . '/uploads/' . ltrim($normalized, '/');
        // Try as given
        $tries[] = $normalized;
    }

    $resolvedPath = null;
    foreach ($tries as $candidate) {
        if (file_exists($candidate)) {
            $resolvedPath = $candidate;
            break;
        }
    }

    foreach ($tries as $t) error_log('view.php tried path: ' . $t);

    if ($resolvedPath) {
        serve_file:
        // Determine mime type
        $mime = @mime_content_type($resolvedPath) ?: 'application/octet-stream';
        $inlineTypes = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif', 'image/svg+xml', 'text/plain', 'text/html'];

        if (in_array($mime, $inlineTypes)) {
            header('Content-Type: ' . $mime);
            header('Content-Disposition: inline; filename="' . basename($fileName) . '"');
        } else {
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . basename($fileName) . '"');
        }
        header('Content-Length: ' . filesize($resolvedPath));
        readfile($resolvedPath);
        exit;
    } else {
        error_log('view.php: File not found. Tried: ' . implode(', ', $tries));
        echo "File not found.";
        exit;
    }

} else {
    echo "No document ID provided.";
}

if (isset($conn)) $conn->close();
?>

