<?php
/**
 * Secure Document Download Handler
 * Serves signed PDF documents
 */

session_start();
ob_start();
require_once 'config.php';
require_once 'auth.php';
require_once 'billing.php';

$auth = getAuth();
$auth->requireAuth(); // Must be logged in

$currentUser = $auth->getCurrentUser();
$db = getDatabaseConnection();
// Enforce active subscription for downloading signed documents
requireSubscription($db, $currentUser['id']);
$documentId = isset($_GET['doc']) ? sanitizeInput($_GET['doc']) : '';

if (empty($documentId)) {
    error_log("download: missing document id from user " . ($currentUser['id'] ?? 'unknown'));
    die('ID de documento no proporcionado');
} 
 
// Verify document exists
$stmt = $db->prepare("SELECT nombre_de_archivo, nombre_del_firmante, id_de_usuario FROM firmas WHERE id_de_documento = ?");
$stmt->bind_param('s', $documentId);
$stmt->execute();
$result = $stmt->get_result();

if ($row = $result->fetch_assoc()) { 

    if ($row['id_de_usuario'] != $currentUser['id']) {
        error_log("download: permission denied for user {$currentUser['id']} on document {$documentId}");
        die('No tiene permiso para descargar este documento');
    }

    $filename = $row['nombre_de_archivo'];
    $signerName = $row['nombre_del_firmante'];
    $filepath = __DIR__ . '/signed_documents/' . $filename;
    
    if (file_exists($filepath)) {
        // Set headers for download
        $logStmt = $db->prepare("
            INSERT INTO actividad_del_usuario (id_de_usuario, accion_de_usuario, descripcion, direccion_ip, user_agent)
            VALUES (?, 'documento_descargado', ?, ?, ?)
        ");

        $description = "Descargó documento: $documentId";
        $ip = $_SERVER['REMOTE_ADDR']; 
        $userAgent = $_SERVER['HTTP_USER_AGENT'];
        $logStmt->bind_param('isss', $currentUser['id'], $description, $ip, $userAgent);
        $logStmt->execute();
        $logStmt->close();

        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $signerName . '_signed_' . date('Ymd') . '.pdf"');
        header('Content-Length: ' . filesize($filepath));
        header('Cache-Control: private, max-age=0, must-revalidate');
        header('Pragma: public');
        
        // Clear output buffer
        ob_clean();
        flush();
        
        // Read and output file
        readfile($filepath);
        // Ensure output buffering is flushed and closed
        if (ob_get_level()) { ob_end_flush(); }
        exit;
    } else {
        error_log("download: file not found: {$filepath} (document {$documentId})");
        die('Archivo no encontrado');
    }
} else {
    error_log("download: document record not found: {$documentId} (user {$currentUser['id']})");
    die('Documento no existe');
}

$stmt->close();
$db->close();
?>
