<?php
/**
 * download-anonymized.php - Download Anonymized File in Original Format
 */

require_once '../config.php';
requireLogin();

$fileId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($fileId <= 0) {
    die('Invalid file ID');
}

$userId = $_SESSION['user_id'];
$pdo = getDBConnection();

try {
    $stmt = $pdo->prepare("
        SELECT * FROM file_risk_analyses 
        WHERE id = ? AND user_id = ?
    ");
    $stmt->execute([$fileId, $userId]);
    $file = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$file) {
        die('File not found');
    }
    
    // Check if anonymized file exists
    $anonymizedPath = $file['anonymized_filepath'];
    
    if (!$anonymizedPath || !file_exists($anonymizedPath)) {
        // Try to find anonymized file in the same directory
        $uploadDir = dirname($file['original_filepath']);
        $originalName = basename($file['original_filepath']);
        $possiblePath = $uploadDir . '/anonymized_' . $originalName;
        
        if (file_exists($possiblePath)) {
            $anonymizedPath = $possiblePath;
        } else {
            die('Anonymized file not found. Please re-upload and anonymize again.');
        }
    }
    
    // Update download count
    $stmt = $pdo->prepare("
        UPDATE file_risk_analyses 
        SET download_count = download_count + 1,
            downloaded_at = datetime('now')
        WHERE id = ?
    ");
    $stmt->execute([$fileId]);
    
    // Get file info
    $fileInfo = pathinfo($anonymizedPath);
    $extension = strtolower($fileInfo['extension'] ?? 'txt');
    
    // Set appropriate content type
    $contentTypes = [
        'pdf' => 'application/pdf',
        'docx' => 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
        'xlsx' => 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'csv' => 'text/csv',
        'txt' => 'text/plain',
        'doc' => 'application/msword',
        'xls' => 'application/vnd.ms-excel'
    ];
    
    $contentType = $contentTypes[$extension] ?? 'application/octet-stream';
    
    // Prepare download filename
    $originalFilename = pathinfo($file['original_filename'], PATHINFO_FILENAME);
    $safeFilename = preg_replace('/[^a-zA-Z0-9_-]/', '_', $originalFilename);
    $downloadFilename = $safeFilename . '_anonymized.' . $extension;
    
    // Set headers
    header('Content-Type: ' . $contentType);
    header('Content-Disposition: attachment; filename="' . $downloadFilename . '"');
    header('Content-Length: ' . filesize($anonymizedPath));
    header('Cache-Control: private, no-cache, must-revalidate');
    header('Pragma: no-cache');
    
    // Output file
    readfile($anonymizedPath);
    exit;
    
} catch (Exception $e) {
    error_log("Download error: " . $e->getMessage());
    die('Error downloading file: ' . $e->getMessage());
}
?>