<?php
session_start();

require_once __DIR__ . '/../includes/user_activity_log.php';

require '../vendor/autoload.php'; // Asegúrate de ajustar la ruta si es necesario
require __DIR__ . '/api/_node.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

header('Content-Type: application/json; charset=UTF-8');
header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
header('Pragma: no-cache');
header('Expires: 0');

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $cotizacionIdPost = isset($_POST['cotizacionId']) ? (int)$_POST['cotizacionId'] : 0;
    $to = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $subject = htmlspecialchars($_POST['subject'], ENT_QUOTES, 'UTF-8');
    $message = nl2br(htmlspecialchars($_POST['message'], ENT_QUOTES, 'UTF-8')); // Convert new lines to <br>
    $pdfFilePath = filter_var($_POST['pdfFilePath'], FILTER_SANITIZE_STRING);

    // === Resend blocker: no permitir reenvío a la misma dirección para la misma cotización en el próximo minuto ===
    // Intentaremos extraer el id de cotización desde el nombre del PDF (p.ej. cotizacion_123.pdf).
    $locksDir = __DIR__ . '/.email_locks';
    if (!is_dir($locksDir)) {
        @mkdir($locksDir, 0755, true);
    }

    // Helper: extraer id desde el nombre del archivo PDF
    function extractCotizacionIdFromPdf($pdfPath)
    {
        $base = basename($pdfPath);
        // patrones comunes: cotizacion_123.pdf o cotizacion-123.pdf
        if (preg_match('/cotizacion[_-]?(\d+)\.pdf/i', $base, $m)) {
            return $m[1];
        }
        // fallback: buscar cualquier número en el nombre
        if (preg_match('/(\d+)/', $base, $m)) {
            return $m[1];
        }
        return null;
    }

    $cotizacionId = $cotizacionIdPost > 0 ? (string)$cotizacionIdPost : extractCotizacionIdFromPdf($pdfFilePath);
    $identifier = $cotizacionId ? "cotizacion:" . $cotizacionId : 'pdf:' . md5($pdfFilePath);
    $lockKey = sha1($identifier . '|' . strtolower($to));
    $lockFile = $locksDir . '/' . $lockKey . '.json';
    $now = time();
    $BLOCK_SECONDS = 60; // no permitir reenvío en este intervalo

    if (file_exists($lockFile)) {
        $data = @json_decode(@file_get_contents($lockFile), true);
        $sentAt = isset($data['time']) ? intval($data['time']) : @filemtime($lockFile);
        if (($now - $sentAt) < $BLOCK_SECONDS) {
            // Bloqueado: ya se envió recientemente
            echo json_encode(['success' => false, 'error' => 'blocked_recently', 'retry_after_seconds' => $BLOCK_SECONDS - ($now - $sentAt)]);
            exit;
        }
    }

    // Realizar el envío
    $result = sendEmail($to, $subject, $message, $pdfFilePath);

    if ($result === true) {
        $estadoUpdated = false;
        $estadoNombre = null;

        // Marcar como enviada (estado = 3) vía Node si hay token de sesión
        $token = $_SESSION['node_token'] ?? '';
        if ($cotizacionId && is_string($token) && trim($token) !== '') {
            $base = cpn_node_api_base();
            $url = $base . '/api/cotizaciones/' . urlencode((string)$cotizacionId) . '/marcar-enviada';
            $r = cpn_node_request('POST', $url, $token, null);
            if (isset($r['ok']) && $r['ok'] === true) {
                $estadoUpdated = true;
                $estadoNombre = 'Enviada';
            }
        }

        // Registrar el envío en el lock file
        $payload = ['email' => $to, 'pdf' => $pdfFilePath, 'time' => $now, 'cotizacionId' => $cotizacionId];
        @file_put_contents($lockFile, json_encode($payload), LOCK_EX);

        if ($cotizacionId) {
            cpn_activity_log_event(
                'Cotizaciones',
                'cotizaciones.email_send',
                'Envió la cotización #' . (int)$cotizacionId . ' a ' . (string)$to,
                'cotizacion',
                (int)$cotizacionId
            );
        }
        echo json_encode(['success' => true, 'estadoUpdated' => $estadoUpdated, 'estadoNombre' => $estadoNombre]);
    } else {
        echo json_encode(['success' => false, 'error' => $result]);
    }
}

function sendEmail($to, $subject, $body, $attachment = null)
{
    $mail = new PHPMailer(true);

    try {
        // Configuración del servidor
        $mail->isSMTP();
        $mail->Host       = 'mail.compranet.com.co'; // Configura tu servidor SMTP
        $mail->SMTPAuth   = true;
        $mail->Username   = 'cotizaciones@compranet.com.co'; // Tu dirección de correo SMTP
        $mail->Password   = 'Proyecto2025*'; // Tu contraseña SMTP
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // habilita ssl
        $mail->Port       = 465;                        // puerto SSL
        // Opciones SMTP
        $mail->SMTPOptions = array(
            'ssl' => array(
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            )
        );

        // Remitente y destinatario
        $mail->setFrom('cotizaciones@compranet.com.co', 'Compranet Cotizaciones');
        $mail->addAddress($to);

        // Añadir copia oculta (BCC)
        $mail->addBCC('cotizaciones@compranet.com.co');

        // Contenido del correo
        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $body;
        $mail->CharSet = 'UTF-8'; // Set the charset to UTF-8

        // Adjuntar archivo si existe
        if ($attachment) {
            $mail->addAttachment($attachment);
        }

        $mail->send();
        return true;
    } catch (Exception $e) {
        return "Message could not be sent. Mailer Error: {$mail->ErrorInfo}";
    }
}
