<?php

require_once '../../core/config.php';
require_once '../../core/session.php';
require_once '../../core/permissions.php'; // 1. Motor de permisos
require_once '../../core/database.php';
require_once '../../core/notifications.php';

require_login();
require_permission('module.crm'); // 2. Bloqueo de seguridad
csrf_require_valid_request();

$pdo = db();

$opportunityId = isset($_POST['opportunity_id']) ? (int) $_POST['opportunity_id'] : 0;
$customerId = isset($_POST['customer_id']) ? (int) $_POST['customer_id'] : null;

// Validar Oportunidad y extraer el nombre del cliente correctamente
$stmt = $pdo->prepare("
    SELECT *
    FROM crm_opportunities
    WHERE id = ?
      AND deleted_at IS NULL
    LIMIT 1
");

$stmt->execute(array($opportunityId));
$opportunity = $stmt->fetch();

if (!$opportunity) {
    die('Oportunidad no encontrada.');
}

// La relación cliente-oportunidad proviene de la base, no de un campo oculto.
$customerId = !empty($opportunity['customer_id']) ? (int)$opportunity['customer_id'] : null;

// Extraemos el customerName real de la oportunidad para evitar el error de variable indefinida
$customerName = $opportunity['customer_name'];

$documentType = isset($_POST['document_type']) ? $_POST['document_type'] : 'otro';
$documentName = isset($_POST['document_name']) ? trim($_POST['document_name']) : '';
$documentNumber = isset($_POST['document_number']) ? trim($_POST['document_number']) : '';
$documentDate = isset($_POST['document_date']) && $_POST['document_date'] !== '' ? $_POST['document_date'] : null;
$netAmount = isset($_POST['net_amount']) ? (float) $_POST['net_amount'] : 0;
$totalAmount = isset($_POST['total_amount']) ? (float) $_POST['total_amount'] : 0;
$factoDocumentId = isset($_POST['facto_document_id']) ? trim($_POST['facto_document_id']) : '';
$notes = isset($_POST['notes']) ? trim($_POST['notes']) : '';

if ($documentName === '') {
    die('Nombre de documento requerido.');
}

$filePath = null;

if (isset($_FILES['document_file']) && $_FILES['document_file']['error'] === UPLOAD_ERR_OK) {
    $uploadDir = __DIR__ . '/../../uploads/crm_documents/';

    if (!is_dir($uploadDir)) {
        if (!mkdir($uploadDir, 0750, true) && !is_dir($uploadDir)) {
            die('No se pudo preparar el directorio de documentos.');
        }
    }

    $temporaryPath = (string)$_FILES['document_file']['tmp_name'];
    $fileSize = (int)$_FILES['document_file']['size'];
    $extension = strtolower(pathinfo($_FILES['document_file']['name'], PATHINFO_EXTENSION));

    if ($fileSize <= 0 || $fileSize > 10 * 1024 * 1024) {
        die('El PDF debe pesar entre 1 byte y 10 MB.');
    }
    if (!is_uploaded_file($temporaryPath)) {
        die('La carga del documento no es válida.');
    }

    if (!class_exists('finfo')) {
        die('La validación segura de archivos no está disponible en el servidor.');
    }
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    $mimeType = (string)$finfo->file($temporaryPath);
    $signature = file_get_contents($temporaryPath, false, null, 0, 5);
    if ($extension !== 'pdf' || !in_array($mimeType, array('application/pdf', 'application/x-pdf'), true) || $signature !== '%PDF-') {
        die('Solo se permiten archivos PDF.');
    }

    $safeName = 'crm_doc_' . date('Ymd_His') . '_' . mt_rand(1000, 9999) . '.pdf';
    $destination = $uploadDir . $safeName;

    if (!move_uploaded_file($_FILES['document_file']['tmp_name'], $destination)) {
        die('No se pudo subir el PDF.');
    }
    @chmod($destination, 0640);

    $filePath = '/uploads/crm_documents/' . $safeName;
}

// Insertar el Documento
$stmt = $pdo->prepare("
    INSERT INTO crm_documents
    (
        opportunity_id,
        customer_id,
        document_type,
        document_name,
        document_number,
        document_date,
        net_amount,
        total_amount,
        file_path,
        facto_document_id,
        notes
    )
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
");

$stmt->execute(array(
    $opportunityId,
    $customerId,
    $documentType,
    $documentName,
    $documentNumber,
    $documentDate,
    $netAmount,
    $totalAmount,
    $filePath,
    $factoDocumentId,
    $notes
));
$documentId = (int)$pdo->lastInsertId();

// Construir una única entrada limpia para el Timeline (crm_activities)
$sessionUser = current_user();
$currentUser = !empty($sessionUser['name']) ? $sessionUser['name'] : (!empty($sessionUser['email']) ? $sessionUser['email'] : 'Sistema');

$description = $documentType . ': ' . $documentName;

if ($documentNumber !== '') {
    $description .= "\nNúmero: " . $documentNumber;
}
if ($netAmount > 0) {
    $description .= "\nNeto: " . $netAmount;
}
if ($notes !== '') {
    $description .= "\nNotas: " . $notes;
}

$stmtAct = $pdo->prepare("
    INSERT INTO crm_activities
    (
        opportunity_id,
        customer_id,
        customer_name,
        activity_type,
        title,
        description,
        owner_name,
        activity_date
    )
    VALUES (?, ?, ?, 'documento', 'Documento adjuntado', ?, ?, NOW())
");

$stmtAct->execute(array(
    $opportunityId,
    $customerId,
    $customerName,
    $description,
    $currentUser
));


if (in_array($documentType, array('factura', 'nota_credito', 'nota_debito'), true)) {
    $documentLabel = array(
        'factura' => 'Factura',
        'nota_credito' => 'Nota de crédito',
        'nota_debito' => 'Nota de débito',
    )[$documentType] ?? 'Documento tributario';

    notify_crm_owner_or_admin_event(
        'document.tax_associated',
        !empty($opportunity['owner_user_id']) ? (int)$opportunity['owner_user_id'] : null,
        $documentLabel . ' asociada: ' . ($documentNumber !== '' ? $documentNumber : $documentName),
        'Cliente: ' . $customerName . "\nDocumento: " . $documentName . ($documentNumber !== '' ? "\nNúmero: " . $documentNumber : '') . ($totalAmount > 0 ? "\nTotal: $" . number_format($totalAmount, 0, ',', '.') : ''),
        '/modules/crm/opportunity.php?id=' . $opportunityId,
        'document',
        $documentId,
        array('dedupe_key' => 'document.tax_associated:' . $documentId)
    );
}

// ==========================================
// 🔥 NUEVO: Manejo de respuesta AJAX
// ==========================================
if (isset($_POST['ajax']) && $_POST['ajax'] == '1') {
    header('Content-Type: application/json');
    echo json_encode([
        'success' => true,
        'file_path' => $filePath ? '/modules/crm/document_file.php?id=' . $documentId . '&kind=pdf' : null
    ]);
    exit;
}

// Comportamiento normal (Fallback)
header('Location: /modules/crm/opportunity.php?id=' . $opportunityId);
exit;
