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

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('HTTP/1.1 401 Unauthorized');
    echo "You must be logged in to download files.";
    exit();
}

$user_id = $_SESSION['user_id'];

// Check if file ID is provided
if (!isset($_GET['file_id']) || empty($_GET['file_id'])) {
    header('HTTP/1.1 400 Bad Request');
    echo "File ID is required.";
    exit();
}

$file_id = intval($_GET['file_id']);

// Fetch file information
$file_sql = "SELECT f.file_id, f.file_name, f.file_path, f.file_type, f.file_size, f.uploaded_by, f.is_deleted 
            FROM file_manager f 
            WHERE f.file_id = ?";

$file_stmt = $conn->prepare($file_sql);
$file_stmt->bind_param("i", $file_id);
$file_stmt->execute();
$file_result = $file_stmt->get_result();

if ($file_result->num_rows === 0) {
    header('HTTP/1.1 404 Not Found');
    echo "File not found.";
    exit();
}

$file = $file_result->fetch_assoc();
$file_stmt->close();

// Check if file is deleted
if ($file['is_deleted']) {
    header('HTTP/1.1 404 Not Found');
    echo "This file has been deleted.";
    exit();
}

// Check if user has access to the file
$access_sql = "SELECT 1 FROM file_manager f 
              LEFT JOIN file_shares fs ON (f.file_id = fs.file_id)
              WHERE f.file_id = ? AND 
              (f.uploaded_by = ? OR 
               fs.shared_with = ? OR 
               f.is_public = 1)";

$access_stmt = $conn->prepare($access_sql);
$access_stmt->bind_param("iii", $file_id, $user_id, $user_id);
$access_stmt->execute();
$access_result = $access_stmt->get_result();

// Allow access if the user is an admin (role_id = 1)
$is_admin = false;
$role_sql = "SELECT role_id FROM users WHERE user_id = ?";
$role_stmt = $conn->prepare($role_sql);
$role_stmt->bind_param("i", $user_id);
$role_stmt->execute();
$role_result = $role_stmt->get_result();

if ($role_result->num_rows > 0) {
    $role = $role_result->fetch_assoc();
    if ($role['role_id'] == 1) {
        $is_admin = true;
    }
}
$role_stmt->close();

if ($access_result->num_rows === 0 && !$is_admin) {
    header('HTTP/1.1 403 Forbidden');
    echo "You don't have permission to download this file.";
    exit();
}

$access_stmt->close();

// Check if file exists on the server
if (!file_exists($file['file_path'])) {
    header('HTTP/1.1 404 Not Found');
    echo "File not found on server.";
    exit();
}

// Log the download
$log_sql = "INSERT INTO file_access_logs (file_id, user_id, access_type, ip_address) 
           VALUES (?, ?, 'download', ?)";
$log_stmt = $conn->prepare($log_sql);
$ip_address = $_SERVER['REMOTE_ADDR'];
$log_stmt->bind_param("iis", $file_id, $user_id, $ip_address);
$log_stmt->execute();
$log_stmt->close();

// Set headers for file download
header('Content-Description: File Transfer');
header('Content-Type: ' . $file['file_type']);
header('Content-Disposition: attachment; filename="' . basename($file['file_name']) . '"');
header('Content-Length: ' . $file['file_size']);
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');

// Close database connection before sending the file
$conn->close();

// Read and output file
readfile($file['file_path']);
exit();
?>