<?php
session_start();

// Cek Login
if (!isset($_SESSION['user_id'])) {
    header("HTTP/1.1 401 Unauthorized");
    exit('Unauthorized');
}

$sessionId = isset($_GET['session_id']) ? preg_replace('/[^a-zA-Z0-9_-]/', '', $_GET['session_id']) : '';
$fileName = isset($_GET['file']) ? trim($_GET['file']) : '';

if (empty($sessionId) || empty($fileName)) {
    exit("Data tidak valid.");
}

// Prevent directory traversal
$fileName = str_replace(['..\\', '../', '..'], '', $fileName);
$fileName = ltrim($fileName, '/\\');

$projectDir = '../../autokoding/projects/' . $sessionId . '/';
$fullPath = realpath($projectDir . $fileName);

// Pastikan file tersebut benar-benar ada di dalam folder project
$realProjectDir = realpath($projectDir);

if ($fullPath === false || !file_exists($fullPath) || strpos($fullPath, $realProjectDir) !== 0) {
    exit("File tidak ditemukan atau akses ditolak.");
}

// Lakukan Force Download
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename="'.basename($fullPath).'"');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($fullPath));
readfile($fullPath);
exit;
