<?php
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', __DIR__ . '/../logs/php_errors.log');
error_reporting(E_ALL);

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

// 1. OBTENER DATOS
$data = $_POST;
if (empty($data)) {
    $raw = file_get_contents('php://input');
    if ($raw) {
        $maybe = json_decode($raw, true);
        if (is_array($maybe)) { $data = $maybe; }
    }
}

// --- BUSINESS CONFIG ---
require_once __DIR__ . '/db/business_config.php';

// ==================================================================
// 2. LÓGICA ANTI-SPAM (CORREGIDA Y MEJORADA)
// ==================================================================
$location_thank_you = 'thank-you.php';

// Verificación #1: Campos requeridos no pueden estar vacíos
// Un usuario real siempre llenará estos campos. Un bot de spam a menudo los deja vacíos.
$name_check  = trim($data['name'] ?? $data['full_name'] ?? '');
$email_check = trim($data['email'] ?? '');
$phone_check = trim($data['phone'] ?? '');

if (empty($name_check) || empty($email_check) || empty($phone_check)) {
    // Si alguno de los campos clave está vacío, es spam. Lo mandamos a la página de gracias sin hacer nada.
    header('Location: ' . $location_thank_you);
    exit;
}

// Verificación #2: Honeypot (esta ya la tenías y está bien)
if (!empty($data['user_nickname']) || !empty($data['website_url'])) {
    header('Location: ' . $location_thank_you);
    exit;
}

// Verificación #3: Contenido sospechoso (tu lógica original, ahora más efectiva)
$fields_to_check = [
    'Nombre'    => $name_check,
    'Email'     => $email_check,
    'Teléfono'  => $phone_check,
    'Servicio'  => $data['service'] ?? '',
    'Mensaje'   => $data['message'] ?? '',
];

$blocked_keywords = ['seo','sem','leads','marketing','crypto','investment','forex','offer','loan','pills','viagra','casino','betting'];
$blocked_tlds = ['.ru', '.cn', '.xyz', '.biz', '.top', '.site', '.online', '.club', '.cyou'];
$disposable_domains = ['mailinator.com', '10minutemail.com', 'temp-mail.org', 'guerrillamail.com'];
$url_pattern = '/(http|https|ftp|www\.|[a-z0-9-]+\.(com|net|org|ru|cn|biz))/i';
$language_pattern = '/[^\p{Latin}\p{N}\p{P}\p{Z}\s@.-]/u';

foreach ($fields_to_check as $fieldName => $fieldValue) {
    if (empty($fieldValue)) continue;

    // CORRECCIÓN: La regla de URL no se aplica al campo 'Email'.
    if ($fieldName !== 'Email') {
        if (preg_match($url_pattern, $fieldValue)) {
            header('Location: ' . $location_thank_you);
            exit;
        }
    }

    if (preg_match($language_pattern, $fieldValue)) {
        header('Location: ' . $location_thank_you);
        exit;
    }
    foreach ($blocked_keywords as $word) {
        if (stripos($fieldValue, $word) !== false) {
            header('Location: ' . $location_thank_you);
            exit;
        }
    }
}
// --- FIN DEL BLOQUE ANTI-SPAM ---

// 3. EXTRAER Y SANITIZAR DATOS
$fullName      = trim(filter_var($data['name'] ?? $data['full_name'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
$email         = trim(filter_var($data['email'] ?? '', FILTER_SANITIZE_EMAIL));
$originalPhone = trim(filter_var($data['phone'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
$service       = trim(filter_var($data['service'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS));
$message       = trim(filter_var($data['message'] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS));

if ($fullName === '') { $fullName = 'Cliente'; }
$nameParts = explode(' ', $fullName, 2);
$firstName = filter_var($nameParts[0] ?? 'Cliente', FILTER_SANITIZE_FULL_SPECIAL_CHARS);
$lastName  = filter_var($nameParts[1] ?? '', FILTER_SANITIZE_FULL_SPECIAL_CHARS);

$source = 'Pagina Web';
$status = 'Entrante';

// 4. GUARDAR EN BASE DE DATOS
try {
    if (file_exists(__DIR__ . '/db/db_connection.php')) {
        include __DIR__ . '/db/db_connection.php';
    } elseif (file_exists(__DIR__ . '/../db/db_connection.php')) {
        include __DIR__ . '/../db/db_connection.php';
    }

    if (isset($pdo) && $pdo instanceof PDO) {
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $stmt = $pdo->prepare("
            INSERT INTO leads (first_name, last_name, email, phone, source, status)
            VALUES (:first_name, :last_name, :email, :phone, :source, :status)
        ");
        $stmt->execute([
            ':first_name' => $firstName,
            ':last_name'  => $lastName,
            ':email'      => $email,
            ':phone'      => $originalPhone,
            ':source'     => $source,
            ':status'     => $status,
        ]);
    } else {
        error_log('[submit_lead.php] No PDO connection available.');
    }
} catch (Throwable $e) {
    error_log('[submit_lead.php] DB error: ' . $e->getMessage());
}

// 5. ENVIAR EMAIL DE NOTIFICACIÓN
try {
    $admin_email  = getenv('ADMIN_EMAIL') ?: 'orozdesign@gmail.com';
    $sender_email = getenv('SENDER_EMAIL') ?: 'no-reply@tunegociocrm.com';


// --- INICIA NUEVO CUERPO DEL EMAIL (HTML PROFESIONAL) ---
$logoUrl = LOGO_FILENAME;
$buttonUrl = 'https://crm.tunegociocrm.com/'; 
$businessName = BUSINESS_NAME;
$websiteUrl = WEBSITE_URL;

$email_body = <<<HTML
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Nuevo Prospecto Recibido</title>
    <style>
        body, table, td, div, p, a { 
            font-family: 'Barlow', Arial, sans-serif; 
        }
    </style>
</head>
<body style="margin: 0; padding: 0; background-color: #f4f7f6;">
    <table width="100%" border="0" cellspacing="0" cellpadding="0" style="background-color: #f4f7f6;">
        <tr>
            <td align="center">
                <table width="600" border="0" cellspacing="0" cellpadding="0" align="center" style="max-width: 600px;">
                    
                    <tr>
                        <td height="6" style="background-color: #9e1428;"></td>
                    </tr>
                    <tr>
                        <td style="background-color: #ffffff; padding: 25px 40px 40px 40px;">
                            
                            <h1 style="font-size: 30px; color: #07162d; margin-top: 0; margin-bottom: 5px; text-align: center; font-weight: 900; line-height: 1.2; text-transform: uppercase;">
                                ¡HAS RECIBIDO <br /><span style="color: #9e1428;">UN NUEVO PROSPECTO</span>!
                            </h1>
                            <p style="color: #555555; line-height: 1.6; text-align: center; font-size: 16px; margin-bottom: 25px;">
                                Aquí están los detalles del cliente potencial que ha llenado el formulario en tu sitio web. <b>Actúa Rápido.</b>
                            </p>
                            
                            <table width="100%" border="0" cellspacing="0" cellpadding="0" style="background-color: #f9f9f9; border: 1px solid #e0e0e0; border-radius: 8px; margin-top: 20px;">
                                <tr>
                                    <td style="padding: 20px;">
                                        
                                        <p style="margin: 8px 0; font-size: 16px;"><strong style="color: #07162d; font-weight: 700;">Nombre:</strong> <span style="color: #333;">{$fullName}</span></p>
                                        <p style="margin: 8px 0; font-size: 16px;"><strong style="color: #07162d; font-weight: 700;">Email:</strong> <span style="color: #333;">{$email}</span></p>
                                        <p style="margin: 8px 0; font-size: 16px;"><strong style="color: #07162d; font-weight: 700;">Teléfono:</strong> <span style="color: #333;">{$originalPhone}</span></p>
                                        
                                        <div style="border-bottom: 1px dashed #cccccc; margin: 15px 0;"></div>
                                        
                                        <p style="margin: 8px 0; font-size: 16px;"><strong style="color: #07162d; font-weight: 700;">Servicio de interés:</strong> <span style="color: #333;">{$service}</span></p>
                                        <p style="margin: 15px 0 0 0; font-size: 16px;"><strong style="color: #07162d; font-weight: 700;">Mensaje:</strong></p>
                                        <p style="margin: 5px 0 0 0; color: #333333; line-height: 1.6; padding: 10px; border: 1px solid #eeeeee; background-color: #ffffff; border-radius: 4px;">{$message}</p>

                                    </td>
                                </tr>
                            </table>

                            <table width="100%" border="0" cellspacing="0" cellpadding="0">
                                <tr>
                                    <td align="center" style="padding-top: 30px;">
                                        <a href="{$buttonUrl}" style="background-color: #9e1428; color: #ffffff; padding: 16px 32px; text-decoration: none; border-radius: 8px; font-weight: 700; display: inline-block; font-size: 18px; line-height: 1; letter-spacing: 0.5px;">
                                            Administra Tus Leads Con FlowCRM™
                                        </a>
                                    </td>
                                </tr>
                            </table>
                        </td>
                    </tr>
                    
                    <tr>
                        <td align="center" style="padding: 20px; font-size: 12px; color: #888888; text-align: center;">
                            <p style="margin: 0;">Este Correo Fue Enviado Desde Tu Sitio Web <b>{$businessName}</b></p>
                            <p style="margin: 5px 0 0 0;">
                                <a href="{$websiteUrl}" style="color: #888888; text-decoration: none; font-weight: 700;">Ver Sitio Web</a>
                                | <span style="font-weight: 700;">URL: {$websiteUrl}</span>
                            </p>
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>
HTML;

// --- TERMINA NUEVO CUERPO DEL EMAIL ---

   $headers = "From: {$sender_email}\r\n" .
               "Reply-To: {$sender_email}\r\n" .
               "MIME-Version: 1.0\r\n" . // Importante: indica que el contenido es HTML
               "Content-Type: text/html; charset=UTF-8\r\n" . // Importante: define el tipo de contenido
               "X-Mailer: PHP/" . phpversion();

 // @ suppress errors to avoid output. Check logs instead.
    @mail($admin_email, 'Nuevo Prospecto Del Sitio Web', $email_body, $headers);
} catch (Throwable $e) {
    error_log('[submit_lead.php] Mail error: ' . $e->getMessage());
}

// Build redirect to thank-you.php with query params
// Keep it simple: only pass safe fields like first name.
$query = http_build_query([
    'name'  => $firstName,
    'email' => $email,
]);

// Build redirect to thank-you.php with query params
$query = http_build_query([
    'name'  => $firstName ?? '',
    'email' => $email ?? '',
]);

$location = 'thank-you.php?' . $query;

// --- NUEVO: si la petición es AJAX/Fetch devolvemos JSON con redirect ---
// detecta si el cliente espera JSON (Accept header) o si es XHR
$acceptHeader = $_SERVER['HTTP_ACCEPT'] ?? '';
$xRequestedWith = $_SERVER['HTTP_X_REQUESTED_WITH'] ?? '';

$isAjax = (stripos($acceptHeader, 'application/json') !== false)
          || (strtolower($xRequestedWith) === 'xmlhttprequest');

// Si necesitas detectar peticiones que envían JSON en body (Content-Type: application/json) podríamos añadirlo.

if ($isAjax) {
    // Devolver JSON con la URL de redirección y estado
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode([
        'success'  => true,
        'redirect' => $location,
        // opcionales: puedes devolver más información si quieres
        //'saved' => true,
        //'message' => 'Lead guardado correctamente'
    ]);
    exit;
}

// Si no es AJAX, hacemos la redirección normal (POST tradicional)
header('Location: ' . $location, true, 302);
exit;