<?php
/**
 * Secure File Download System
 * Validates user purchase and prevents direct file access.
 */

require_once 'includes/config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_once 'includes/auth.php';

// 1. Security Check: Must be logged in
if (!function_exists('is_logged_in') || !is_logged_in()) {
    redirect(SITE_URL . '/login.php');
    exit;
}

$product_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$user_id = $_SESSION['user_id'];

if ($product_id <= 0) {
    set_flash_message('error', 'Invalid product requested.');
    redirect(SITE_URL . '/account.php');
    exit;
}

// 2. Validate Purchase (Check if user has an 'approved' order)
try {
    $stmt_order = $pdo->prepare("SELECT id FROM orders WHERE user_id = :uid AND product_id = :pid AND status = 'approved' LIMIT 1");
    $stmt_order->execute([':uid' => $user_id, ':pid' => $product_id]);
    
    if (!$stmt_order->fetch()) {
        set_flash_message('error', 'You do not have permission to download this file. Please purchase it first.');
        redirect(SITE_URL . '/product.php?slug=' . get_product_slug($pdo, $product_id));
        exit;
    }
} catch (PDOException $e) {
    set_flash_message('error', 'Database error during validation.');
    redirect(SITE_URL . '/account.php');
    exit;
}

// 3. Fetch Product & File Info
try {
    $stmt_prod = $pdo->prepare("SELECT title, file_path FROM products WHERE id = :id LIMIT 1");
    $stmt_prod->execute([':id' => $product_id]);
    $product = $stmt_prod->fetch();

    if (!$product || empty($product['file_path'])) {
        set_flash_message('error', 'File information is missing from the database.');
        redirect(SITE_URL . '/account.php');
        exit;
    }
} catch (PDOException $e) {
    set_flash_message('error', 'System error while fetching file.');
    redirect(SITE_URL . '/account.php');
    exit;
}

// 4. Locate the File on Server
$file_name = basename($product['file_path']);
$absolute_path = PRODUCT_FILES_PATH . DS . $file_name;

// 5. Force Secure Download if file exists
if (file_exists($absolute_path)) {
    // Clean file name for download (Remove special characters to prevent errors)
    $clean_filename = preg_replace('/[^a-zA-Z0-9-_\.]/', '_', $product['title']) . '.zip';
    
    // Set headers to force download
    header('Content-Description: File Transfer');
    header('Content-Type: application/zip'); // Assumes all source codes are in .zip format
    header('Content-Disposition: attachment; filename="' . $clean_filename . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($absolute_path));
    
    // Clean output buffer to prevent corrupted zip files
    ob_clean();
    flush();
    
    // Read and output the file safely
    readfile($absolute_path);
    exit;
} else {
    // File doesn't exist on the server (Admin might have deleted it)
    set_flash_message('error', 'The requested file is missing from the server. Please contact support.');
    redirect(SITE_URL . '/account.php');
    exit;
}

// Helper Function
function get_product_slug($pdo, $id) {
    $stmt = $pdo->prepare("SELECT slug FROM products WHERE id = :id LIMIT 1");
    $stmt->execute([':id' => $id]);
    return $stmt->fetchColumn() ?: '';
}
?>