<?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

$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.');
}

// 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)) {
        mkdir($uploadDir, 0755, true);
    }

    $extension = strtolower(pathinfo($_FILES['document_file']['name'], PATHINFO_EXTENSION));

    if ($extension !== '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.');
    }

    $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 // Pasamos el path para que el botón "Ver" funcione de inmediato
    ]);
    exit;
}

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