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

// User instructed: always use pmed_documents table for file paths (paths point to pmed.lagunappdco.online/uploads/...)
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);

    // If the path looks like a URL (http(s)://) or contains the pmed domain, redirect to it so cPanel serves the file
    if (preg_match('#^https?://#i', $normalized) || stripos($normalized, 'pmed.lagunappdco.online') !== false || stripos($normalized, 'pmed.lagunappdco.online/uploads') !== false || stripos($normalized, '/uploads/') !== false) {
        // If it's a relative path starting with /uploads, build absolute URL
        if (strpos($normalized, '/uploads/') === 0) {
            // Prepend domain
            $normalized = 'https://pmed.lagunappdco.online' . $normalized;
        }

        // Redirect to the remote/pmed URL so the web server (cpanel) handles content-type and caching
        header('Location: ' . $normalized);
        exit;
    }

    // Otherwise, attempt to serve local file with best-effort resolution
    $tries = [];
    // If looks absolute (Windows drive or starting slash)
    if (preg_match('#^[A-Za-z]:/#', $normalized) || strpos($normalized, '/') === 0) {
        $tries[] = $normalized;
    } else {
        // Try relative to project root (one level up from users/)
        $projectRoot = realpath(__DIR__ . '/..');
        if ($projectRoot) $tries[] = $projectRoot . '/' . ltrim($normalized, '/');
        // Try relative to current users directory
        $tries[] = __DIR__ . '/' . 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) {
        // 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.";
}

$conn->close();
?>