Files
ayr2026/enviar.php
T
2026-09-20 13:28:57 -03:00

171 lines
6.9 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<?php
/**
* Endpoint AJAX del formulario de contacto.
* Recibe POST y responde JSON.
*/
// ── Silenciar salida directa, solo JSON ────────────────────────────────
if (ob_get_length() > 0) { ob_clean(); }
header('Content-Type: application/json; charset=UTF-8');
// ── Errores a log, no a pantalla ───────────────────────────────────────
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL);
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/validar.php';
// ── Respuesta helper ───────────────────────────────────────────────────
function responder($status, $message, $code = 200, $extra = []) {
http_response_code($code);
echo json_encode(array_merge([
'status' => $status,
'message' => $message,
], $extra));
exit;
}
// ── Método ─────────────────────────────────────────────────────────────
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
responder('error', 'Método no permitido.', 405);
}
// ── Honeypot ───────────────────────────────────────────────────────────
if (!empty($_POST['website'])) {
// Fingimos éxito para no darle pistas al bot
responder('success', '¡Gracias! Te contactaremos a la brevedad.');
}
// ── Validación ─────────────────────────────────────────────────────────
$resultado = validar_contacto($_POST);
if (!$resultado['ok']) {
responder('error', implode(' ', $resultado['errores']), 400);
}
$d = $resultado['datos'];
// ── PHPMailer ──────────────────────────────────────────────────────────
require_once __DIR__ . '/lib/PHPMailer.php';
require_once __DIR__ . '/lib/SMTP.php';
require_once __DIR__ . '/lib/Exception.php';
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\SMTP;
// ── Mapas para mostrar etiquetas legibles ─────────────────────────────
$etiquetas = [
'servicio' => [
'branding' => 'Branding & Identidad',
'web' => 'Desarrollo Web a Medida',
'rrss' => 'Gestión de Redes Sociales',
'automatizaciones'=> 'Automatizaciones & Flujos',
'paid' => 'Paid Media & Campañas',
'ecosistema' => 'Ecosistema Digital Completo',
'otro' => 'Otro / Aún no definido',
],
'etapa' => [
'idea' => 'Solo tengo la idea',
'inicio' => 'Estoy empezando',
'marcha' => 'En marcha, necesito orden',
'redisenio' => 'Rediseñar / reposicionar',
'escalar' => 'Escalar lo existente',
],
'presupuesto' => [
'esencial' => 'Hasta $250.000 (Esencial)',
'impulso' => '$250.000 – $500.000 (Impulso)',
'premium' => '$500.000 – $800.000 (Premium)',
'elite' => 'Más de $800.000 (Élite)',
'proyecto' => 'Proyecto cerrado (one-off)',
'no-se' => 'A evaluar por el equipo',
],
'origen' => [
'instagram' => 'Instagram',
'linkedin' => 'LinkedIn',
'referido' => 'Referido',
'google' => 'Google',
'otro' => 'Otro',
],
];
$mail = new PHPMailer(true);
try {
// SMTP
$mail->isSMTP();
$mail->Host = SMTP_HOST;
$mail->SMTPAuth = true;
$mail->Username = SMTP_USER;
$mail->Password = SMTP_PASS;
$mail->SMTPSecure = SMTP_SECURE;
$mail->Port = SMTP_PORT;
$mail->CharSet = 'UTF-8';
$mail->SMTPDebug = 0;
// De / Para
$mail->setFrom(SMTP_FROM, SMTP_FROM_NAME);
$mail->addAddress(MAIL_TO, MAIL_TO_NAME);
$mail->addReplyTo($d['email'], $d['nombre']);
// Contenido
$mail->Subject = 'Nuevo contacto: ' . $d['nombre'] . ($d['empresa'] ? ' (' . $d['empresa'] . ')' : '');
$mail->isHTML(true);
$servicio_txt = $etiquetas['servicio'][$d['servicio']] ?? '—';
$etapa_txt = $etiquetas['etapa'][$d['etapa']] ?? '—';
$presupuesto_txt = $etiquetas['presupuesto'][$d['presupuesto']] ?? '—';
$origen_txt = $etiquetas['origen'][$d['origen']] ?? '—';
$rows = [
'Nombre' => $d['nombre'],
'Empresa / Marca' => $d['empresa'] ?: '—',
'Email' => $d['email'],
'Teléfono' => $d['telefono'] ?: '—',
'Servicio' => $servicio_txt,
'Etapa' => $etapa_txt,
'Presupuesto' => $presupuesto_txt,
'Cómo nos conoció'=> $origen_txt,
];
$html = '<div style="font-family:Arial,sans-serif;font-size:14px;color:#222;max-width:640px">';
$html .= '<h2 style="margin:0 0 16px;color:#111">Nueva consulta desde el sitio</h2>';
$html .= '<table cellpadding="8" cellspacing="0" style="border-collapse:collapse;width:100%">';
foreach ($rows as $label => $valor) {
$html .= '<tr>';
$html .= '<td style="background:#f5f2ec;border:1px solid #e5e0d5;font-weight:bold;width:180px">' . htmlspecialchars($label) . '</td>';
$html .= '<td style="border:1px solid #e5e0d5">' . htmlspecialchars($valor) . '</td>';
$html .= '</tr>';
}
$html .= '</table>';
$html .= '<h3 style="margin:24px 0 8px;color:#111">Mensaje</h3>';
$html .= '<div style="white-space:pre-wrap;background:#fafafa;border:1px solid #eee;padding:12px;border-radius:6px">'
. htmlspecialchars($d['mensaje']) . '</div>';
$html .= '</div>';
$mail->Body = $html;
$mail->AltBody = "Nueva consulta\n\n"
. "Nombre: {$d['nombre']}\n"
. "Empresa: {$d['empresa']}\n"
. "Email: {$d['email']}\n"
. "Teléfono: {$d['telefono']}\n"
. "Servicio: $servicio_txt\n"
. "Etapa: $etapa_txt\n"
. "Presupuesto: $presupuesto_txt\n"
. "Origen: $origen_txt\n\n"
. "Mensaje:\n{$d['mensaje']}\n";
$mail->send();
responder('success', '¡Gracias! Te contactaremos en menos de 48 horas hábiles.', 200, [
'redirect' => REDIRECT_URL,
'delay' => REDIRECT_MS,
]);
} catch (Exception $e) {
error_log('[contacto] Falló el envío: ' . $mail->ErrorInfo);
$msg = DEBUG_MODE
? 'Error SMTP: ' . $mail->ErrorInfo
: 'No pudimos enviar tu mensaje. Probá por WhatsApp o intentá más tarde.';
responder('error', $msg, 500);
}