<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'PHPMailer/Exception.php';
require 'PHPMailer/PHPMailer.php';
require 'PHPMailer/SMTP.php';

header('Content-Type: application/json');
error_reporting(E_ALL);
ini_set('display_errors', 1);

// Verificar que la solicitud es POST
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Método no permitido']);
    exit;
}

// Recoger datos
$data = [
    'nombre' => trim($_POST['consult-name'] ?? ''),
    'whatsapp' => trim($_POST['consult-phone'] ?? ''),
    'email' => trim($_POST['consult-email'] ?? ''),
    'motivo' => trim($_POST['motivo'] ?? ''),
    'mensaje' => trim($_POST['mensaje'] ?? '')
];

// Validar datos
foreach ($data as $key => $val) {
    if (empty($val)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => "El campo $key es obligatorio."]);
        exit;
    }
}
if (!filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Email inválido.']);
    exit;
}

// Construir mensaje
$message = "Nombre: {$data['nombre']}\n";
$message .= "WhatsApp: {$data['whatsapp']}\n";
$message .= "Email: {$data['email']}\n";
$message .= "Motivo: {$data['motivo']}\n";
$message .= "Mensaje:\n{$data['mensaje']}";

$mail = new PHPMailer(true);

try {
    $mail->isSMTP();
    $mail->Host = 'mail.scaminvestigationsaeronautics.com';
    $mail->SMTPAuth = true;
    $mail->Username = 'info@scaminvestigationsaeronautics.com';
    $mail->Password = 'info2025#';
    $mail->SMTPSecure = 'ssl';
    $mail->Port = 465;

    $mail->setFrom('info@scaminvestigationsaeronautics.com', 'Sitio Web');
    $mail->addAddress('info@scaminvestigationsaeronautics.com');
    $mail->addReplyTo($data['email'], $data['nombre']);
    $mail->Subject = 'Nueva Consulta: ' . $data['motivo'];
    $mail->Body = $message;

    $mail->send();
    echo json_encode(['success' => true]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $mail->ErrorInfo]);
}
?>
