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

function hasPermission($permission) {
    global $conn;
    
    if (!isset($_SESSION['user_id'])) {
        return false;
    }
    
    if (isset($_SESSION['role_name']) && $_SESSION['role_name'] === 'Super Admin') {
        return true;
    }
    
    try {
        $sql = "SELECT COUNT(*) as has_permission 
                FROM users u 
                JOIN role_permissions rp ON u.role_id = rp.role_id 
                JOIN permissions p ON rp.permission_id = p.permission_id 
                WHERE u.user_id = ? AND p.name = ? AND u.status = 'ACTIVE'";
        
        $stmt = $conn->prepare($sql);
        $stmt->bind_param("is", $_SESSION['user_id'], $permission);
        $stmt->execute();
        $result = $stmt->get_result()->fetch_assoc();
        $stmt->close();
        
        return $result['has_permission'] > 0;
    } catch (Exception $e) {
        error_log("Permission check error: " . $e->getMessage());
        return false;
    }
}

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    http_response_code(401);
    die('Unauthorized access');
}

// Check permission
if (!hasPermission('documents_view')) {
    http_response_code(403);
    die('Insufficient permissions');
}

$document_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if (!$document_id) {
    http_response_code(400);
    die('Invalid document ID');
}

// Fetch document details
$sql = "SELECT d.*, dc.category_name 
        FROM documents d
        LEFT JOIN document_categories dc ON d.category_id = dc.category_id
        WHERE d.document_id = ?";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $document_id);
$stmt->execute();
$document = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$document) {
    http_response_code(404);
    die('Document not found');
}

// Check file exists
$file_path = $document['file_path'];
if (!file_exists($file_path)) {
    http_response_code(404);
    die('File not found on server');
}

// Log download activity
try {
    $log_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, new_values, ip_address, user_agent, session_id) 
                VALUES (?, 'DOWNLOAD', 'DOCUMENT', ?, 'DOCUMENT', ?, ?, ?, ?)";
    
    $log_stmt = $conn->prepare($log_sql);
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $user_agent = substr($_SERVER['HTTP_USER_AGENT'] ?? '', 0, 500);
    $session_id = session_id();
    $download_data = json_encode([
        'document_name' => $document['document_name'],
        'file_name' => $document['file_name'],
        'download_time' => date('Y-m-d H:i:s')
    ]);
    
    $log_stmt->bind_param("iissss", $_SESSION['user_id'], $document_id, $download_data, $ip_address, $user_agent, $session_id);
    $log_stmt->execute();
    $log_stmt->close();
} catch (Exception $e) {
    error_log("Download log error: " . $e->getMessage());
}

$conn->close();

// Set appropriate headers for file download
$mime_type = $document['mime_type'] ?? 'application/octet-stream';
$file_name = $document['file_name'];

header('Content-Type: ' . $mime_type);
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Content-Length: ' . filesize($file_path));
header('Cache-Control: private');
header('Pragma: private');
header('Expires: 0');

// Clear any output buffers
if (ob_get_length()) {
    ob_end_clean();
}

// Read and output the file
readfile($file_path);
exit();
?>