<?php
session_start();
include 'layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit;
}

try {
    $doc_id = $_GET['id'] ?? null;
    if (!$doc_id) {
        throw new Exception('Document ID is required');
    }

    $sql = "SELECT file_path, original_name FROM client_documents WHERE id = ?";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param('i', $doc_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $doc = $result->fetch_assoc();

    if (!$doc || !file_exists($doc['file_path'])) {
        throw new Exception('Document not found');
    }

    $extension = pathinfo($doc['file_path'], PATHINFO_EXTENSION);
    
    switch(strtolower($extension)) {
        case 'pdf':
            header('Content-Type: application/pdf');
            break;
        case 'jpg':
        case 'jpeg':
            header('Content-Type: image/jpeg');
            break;
        case 'png':
            header('Content-Type: image/png');
            break;
        case 'doc':
        case 'docx':
            header('Content-Type: application/msword');
            break;
        default:
            throw new Exception('Unsupported file type');
    }

    header('Content-Disposition: inline; filename="' . $doc['original_name'] . '"');
    readfile($doc['file_path']);

} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

$conn->close();
?>