<?php
/**
 * Download Backup File
 * Handles secure backup file downloads
 */

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

// Check authentication - redirect to login if not logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: ' . BASE_URL . '/login.php');
    exit;
}

// Check admin role - support both new and legacy session variables
$user_role = $user_role ?? $_SESSION['role'] ?? '';
if (!isset($_SESSION['user_id']) || ($user_role !== 'admin')) {
    http_response_code(403);
    die('❌ অ্যাক্সেস denied। আপনার এই পেজ দেখার অনুমতি নেই।<br><br>
    <a href="' . BASE_URL . '/login.php" class="btn btn-primary">লগইন পেজে যান</a>');
}

// Get backup ID
$backup_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if (!$backup_id) {
    http_response_code(400);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => '❌ ব্যাকআপ আইডি প্রয়োজন'
    ]);
    exit;
}

try {
    // Get backup details from database
    $stmt = $pdo->prepare("
        SELECT * FROM backup_history 
        WHERE id = ? AND is_deleted = FALSE
    ");
    $stmt->execute([$backup_id]);
    $backup = $stmt->fetch();
    
    if (!$backup) {
        http_response_code(404);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => '❌ ব্যাকআপ খুঁজে পাওয়া যায়নি'
        ]);
        exit;
    }
    
    // Check if file exists
    if (!file_exists($backup['file_path'])) {
        http_response_code(404);
        header('Content-Type: application/json');
        echo json_encode([
            'success' => false,
            'message' => '❌ ব্যাকআপ ফাইলটি ডিস্কে পাওয়া যায়নি'
        ]);
        exit;
    }
    
    // Log the download action
    $log_stmt = $pdo->prepare("
        INSERT INTO audit_log (user_id, user_role, action, table_name, record_id, ip_address, user_agent, created_at)
        VALUES (?, ?, 'DOWNLOAD', 'backup_history', ?, ?, ?, NOW())
    ");
    $log_stmt->execute([
        $_SESSION['user_id'],
        $user_role,
        $backup_id,
        $_SERVER['REMOTE_ADDR'] ?? 'unknown',
        $_SERVER['HTTP_USER_AGENT'] ?? 'unknown'
    ]);
    
    // Get file info
    $file_path = $backup['file_path'];
    $file_name = $backup['file_name'];
    $file_size = filesize($file_path);
    
    // Determine MIME type
    $file_extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
    $mime_types = [
        'zip' => 'application/zip',
        'sql' => 'text/plain',
        'gz' => 'application/gzip',
        'tar' => 'application/x-tar'
    ];
    $mime_type = $mime_types[$file_extension] ?? 'application/octet-stream';
    
    // Set headers for download
    header('Content-Type: ' . $mime_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;
    
} catch (Exception $e) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => '❌ ডাউনলোড ত্রুটি: ' . $e->getMessage()
    ]);
    exit;
}
