<?php
session_start();
header('Content-Type: application/json');
require_once '../../config/config.php';

// Check if user is logged in
if (!isset($_SESSION['admin_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

// Check if ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    echo json_encode(['success' => false, 'message' => 'Document ID is required']);
    exit();
}

try {
    $documentId = (int)$_GET['id'];
    
    // Connect to database
    $pdo = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    // Get document details
    $stmt = $pdo->prepare("
        SELECT d.*, 
               CONCAT(a.first_name, ' ', a.last_name) as uploaded_by_name,
               a.email as uploaded_by_email
        FROM documents d
        LEFT JOIN admins a ON d.uploaded_by = a.id
        WHERE d.id = :id
    ");
    
    $stmt->execute(['id' => $documentId]);
    $document = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$document) {
        echo json_encode(['success' => false, 'message' => 'Document not found']);
        exit();
    }
    
    // Check if user has permission to view this document
    if ($document['is_public'] == 0 && $_SESSION['admin_id'] != $document['uploaded_by']) {
        // For now, allow all admins to view private documents
        // In a more secure implementation, you might want to check specific permissions
    }
    
    echo json_encode([
        'success' => true,
        'document' => $document
    ]);
    
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => 'Database error: ' . $e->getMessage()
    ]);
}
?>
