<?php
session_start();
require_once '../../config/config.php';

// Check if user is logged in
if (!isset($_SESSION['admin_id'])) {
    header('HTTP/1.1 403 Forbidden');
    exit('Unauthorized');
}

// Check if ID is provided
if (!isset($_GET['id']) || empty($_GET['id'])) {
    header('HTTP/1.1 400 Bad Request');
    exit('Document ID is required');
}

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 * FROM documents WHERE id = :id");
    $stmt->execute(['id' => $documentId]);
    $document = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$document) {
        header('HTTP/1.1 404 Not Found');
        exit('Document not found');
    }
    
    // Check if user has permission to download this document
    if ($document['is_public'] == 0 && $_SESSION['admin_id'] != $document['uploaded_by']) {
        // For now, allow all admins to download private documents
        // In a more secure implementation, you might want to check specific permissions
    }
    
    // Check if file exists
    if (!file_exists($document['file_path'])) {
        header('HTTP/1.1 404 Not Found');
        exit('File not found');
    }
    
    // Update download count
    $updateStmt = $pdo->prepare("UPDATE documents SET download_count = download_count + 1 WHERE id = :id");
    $updateStmt->execute(['id' => $documentId]);
    
    // Log download activity
    $logStmt = $pdo->prepare("
        INSERT INTO activity_logs (user_id, action, details, entity_type, entity_id)
        VALUES (:user_id, 'document_download', :details, 'document', :entity_id)
    ");
    
    $logStmt->execute([
        'user_id' => $_SESSION['admin_id'],
        'details' => "Downloaded document: " . $document['title'],
        'entity_id' => $documentId
    ]);
    
    // Set appropriate headers for file download
    header('Content-Type: ' . $document['file_type']);
    header('Content-Disposition: attachment; filename="' . $document['file_name'] . '"');
    header('Content-Length: ' . $document['file_size']);
    header('Cache-Control: no-cache, must-revalidate');
    header('Pragma: no-cache');
    
    // Output file
    readfile($document['file_path']);
    
} catch (Exception $e) {
    header('HTTP/1.1 500 Internal Server Error');
    exit('Database error: ' . $e->getMessage());
}
?>
