<?php
/**
 * Secure File Download Handler
 * Digital Marketplace
 */

require_once __DIR__ . '/config/database.php';

require_login();

$user_id = get_current_user_id();
$item_id = (int)($_GET['item'] ?? 0);

if (!$item_id) {
    set_flash_message('Invalid download request.', 'error');
    header('Location: ' . BASE_URL . '/account/downloads.php');
    exit;
}

// Get order item with verification
$stmt = $pdo->prepare("SELECT oi.*, o.user_id, o.payment_status, p.file_path, p.download_url, p.name as product_name
                      FROM order_items oi 
                      JOIN orders o ON oi.order_id = o.id 
                      JOIN products p ON oi.product_id = p.id 
                      WHERE oi.id = ? AND o.user_id = ? AND o.payment_status = 'completed'");
$stmt->execute([$item_id, $user_id]);
$item = $stmt->fetch();

if (!$item) {
    set_flash_message('Download not authorized.', 'error');
    header('Location: ' . BASE_URL . '/account/downloads.php');
    exit;
}

// Check download limit
if ($item['download_count'] >= $item['download_limit']) {
    set_flash_message('Download limit reached for this product.', 'error');
    header('Location: ' . BASE_URL . '/account/downloads.php');
    exit;
}

// Determine file path
$file_path = null;

if (!empty($item['file_path'])) {
    $file_path = __DIR__ . '/uploads/files/' . $item['file_path'];
} elseif (!empty($item['download_url'])) {
    // External URL - redirect
    increment_download_count($item_id);
    header('Location: ' . $item['download_url']);
    exit;
}

if (!$file_path || !file_exists($file_path)) {
    set_flash_message('File not found. Please contact support.', 'error');
    header('Location: ' . BASE_URL . '/account/downloads.php');
    exit;
}

// Increment download count
increment_download_count($item_id);

// Log download
log_activity('file_download', "Downloaded: {$item['product_name']}", $user_id);

// Get file info
$file_name = basename($file_path);
$file_size = filesize($file_path);
$file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

// Set appropriate content type
$content_types = [
    'zip' => 'application/zip',
    'pdf' => 'application/pdf',
    'doc' => 'application/msword',
    'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
    'xls' => 'application/vnd.ms-excel',
    'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'jpg' => 'image/jpeg',
    'jpeg' => 'image/jpeg',
    'png' => 'image/png',
    'gif' => 'image/gif',
    'mp3' => 'audio/mpeg',
    'mp4' => 'video/mp4',
];

$content_type = $content_types[$file_extension] ?? 'application/octet-stream';

// Clear output buffer
ob_clean();

// Set headers
header('Content-Type: ' . $content_type);
header('Content-Disposition: attachment; filename="' . $file_name . '"');
header('Content-Length: ' . $file_size);
header('Cache-Control: no-cache, must-revalidate');
header('Expires: 0');

// Output file
readfile($file_path);
exit;
