<?php
/**
 * Descarga segura de documentos asociados a una oportunidad.
 *
 * Evita exponer rutas relativas de storage/uploads y recupera desde FACTO
 * el PDF tributario cuando todavía no existe en el almacenamiento local.
 */
require_once __DIR__ . '/../../core/config.php';
require_once __DIR__ . '/../../core/session.php';
require_once __DIR__ . '/../../core/database.php';
require_once __DIR__ . '/../../core/permissions.php';
require_once __DIR__ . '/../../services/facto/FactoDocumentsSyncService.php';

require_login();
if (!user_can('module.crm') && !user_can('module.customers')) {
    http_response_code(403);
    die('No tienes permisos para ver este documento.');
}

$documentId = (int)($_GET['id'] ?? 0);
$kind = strtolower(trim((string)($_GET['kind'] ?? 'pdf')));
if ($documentId <= 0 || $kind !== 'pdf') {
    http_response_code(400);
    die('Solicitud inválida.');
}

$pdo = db();
$stmt = $pdo->prepare("
    SELECT d.*
    FROM crm_documents d
    LEFT JOIN crm_opportunities o
      ON o.id = d.opportunity_id
     AND o.deleted_at IS NULL
    WHERE d.id = ?
      AND (d.opportunity_id IS NULL OR o.id IS NOT NULL)
    LIMIT 1
");
$stmt->execute(array($documentId));
$document = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$document) {
    http_response_code(404);
    die('Documento no encontrado.');
}

$facto = null;
if (!empty($document['facto_document_id'])) {
    $factoStmt = $pdo->prepare("
        SELECT id, environment, document_id, document_number, pdf_file_path
        FROM facto_documents
        WHERE BINARY document_id = BINARY ?
        ORDER BY (environment = 'production') DESC, id DESC
        LIMIT 1
    ");
    $factoStmt->execute(array((string)$document['facto_document_id']));
    $facto = $factoStmt->fetch(PDO::FETCH_ASSOC) ?: null;
}

$root = realpath(dirname(__DIR__, 2));
$allowedRoots = array_filter(array(
    $root ? realpath($root . '/storage/billing') : false,
    $root ? realpath($root . '/uploads/crm_documents') : false,
));

$resolve = static function ($relative) use ($root, $allowedRoots) {
    if (!$relative || !$root) {
        return false;
    }

    $absolute = realpath($root . '/' . ltrim((string)$relative, '/\\'));
    if (!$absolute || !is_file($absolute)) {
        return false;
    }

    foreach ($allowedRoots as $allowedRoot) {
        $allowedRoot = rtrim($allowedRoot, '/\\');
        if ($absolute === $allowedRoot || strpos($absolute, $allowedRoot . DIRECTORY_SEPARATOR) === 0) {
            return $absolute;
        }
    }

    return false;
};

$relative = $facto['pdf_file_path'] ?? ($document['file_path'] ?? null);
$absolute = $resolve($relative);

if (!$absolute && $facto && !empty($facto['document_id'])) {
    try {
        (new FactoDocumentsSyncService($facto['environment'] ?? 'production'))
            ->refreshDocument($facto['document_id'], true);
        $factoStmt->execute(array((string)$document['facto_document_id']));
        $facto = $factoStmt->fetch(PDO::FETCH_ASSOC) ?: $facto;
        $absolute = $resolve($facto['pdf_file_path'] ?? null);
    } catch (Throwable $e) {
        error_log('CRM FACTO file recovery failed: ' . $e->getMessage());
    }
}

// Algunos registros históricos conservan además una copia manual válida.
if (!$absolute) {
    $absolute = $resolve($document['file_path'] ?? null);
}

if (!$absolute) {
    http_response_code(404);
    die('El PDF no está disponible. Sincroniza el documento con FACTO e inténtalo nuevamente.');
}

$baseName = trim((string)($document['document_number'] ?? ''));
if ($baseName === '') {
    $baseName = trim((string)($facto['document_number'] ?? ''));
}
if ($baseName === '') {
    $baseName = 'documento_' . $documentId;
}

$downloadName = preg_replace('/[^A-Za-z0-9_.-]/', '_', $baseName) . '.pdf';
header('Content-Type: application/pdf');
header('Content-Length: ' . filesize($absolute));
header('Content-Disposition: inline; filename="' . $downloadName . '"');
header('Cache-Control: private, no-store, max-age=0');
header('X-Content-Type-Options: nosniff');
readfile($absolute);
