<?php
session_start();
// Include functions which pulls in the main DB connection and provides logAction()
require_once __DIR__ . '/../functions.php';
require_once __DIR__ . '/../gad_db_connect.php';

// Check if user is logged in
if (!isset($_SESSION['username'])) {
    header("Location: ../index.php");
    exit();
}

if (isset($_GET['id'])) {
    $documentId = (int)$_GET['id'];
    // Get file information from gad_documents table
    $stmt = $conn->prepare("SELECT gad_file_name, gad_file_path, gad_file_type FROM gad_documents WHERE gad_document_id = ?");
    $stmt->bind_param("i", $documentId);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows > 0) {
        $file = $result->fetch_assoc();
        $filePath = $file['gad_file_path'];
        $fileName = $file['gad_file_name'];
        $fileType = $file['gad_file_type'];
        // Check if file exists
        if (file_exists($filePath)) {
            // Set headers for download
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename="' . $fileName . '"');
            header('Content-Length: ' . filesize($filePath));
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            // Clear output buffer
            ob_clean();
            flush();
            // Audit log: downloaded a file from Gender and development
            if (function_exists('logAction')) {
                $userId = $_SESSION['user_id'] ?? 0;
                $username = $_SESSION['username'] ?? 'Guest';
                logAction(isset($conn) ? $conn : null, $userId, $username, "downloaded a file from Gender and Development (GAD)", $documentId, $fileName);
            }
            // Read and output file
            readfile($filePath);
            exit();
        } else {
            echo "File not found on server.";
        }
    } else {
        echo "Document not found in database.";
    }
    $stmt->close();
} else {
    echo "No document ID provided.";
}
?>
