<?php
require_once 'db.php';

$file = isset($_GET['file']) ? $_GET['file'] : '';
$file = ltrim($file, '/');

if (strpos($file, '..') !== false || empty($file)) {
    die('درخواست نامعتبر');
}

$baseDir = __DIR__ . '/repository/';
$fullPath = $baseDir . $file;

if (!file_exists($fullPath) || is_dir($fullPath)) {
    die('فایل یافت نشد');
}

// ثبت دانلود در دیتابیس
$stmt = $pdo->prepare("INSERT INTO files (file_path, download_count, last_download) 
                       VALUES (?, 1, NOW()) 
                       ON DUPLICATE KEY UPDATE 
                       download_count = download_count + 1, 
                       last_download = NOW()");
$stmt->execute([$file]);

// ارسال فایل برای دانلود
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="' . basename($fullPath) . '"');
header('Content-Length: ' . filesize($fullPath));
readfile($fullPath);
exit;
?>