<?php
/**
 * Roofing Nation LLC - Centralized Lead Submission Endpoint
 * Versión Corregida: Multi-Email & SSL Support
 */

// Desactivar visualización de errores pero mantener log
ini_set('display_errors', 0);
header('Content-Type: application/json; charset=utf-8');

// Cargar configuración
require_once __DIR__ . '/config.php';

// CORS handling
$origin = $_SERVER['HTTP_ORIGIN'] ?? '';
if (in_array($origin, ALLOWED_ORIGINS)) {
    header("Access-Control-Allow-Origin: $origin");
} else {
    header("Access-Control-Allow-Origin: https://roofing-nation.com");
}
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type, Accept");

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$input = file_get_contents('php://input');
$data = json_decode($input, true);

if (json_last_error() !== JSON_ERROR_NONE) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => 'Invalid JSON data']);
    exit;
}

// Funciones de validación y limpieza
function sanitize($value, $maxLength = 500) {
    if (!is_string($value)) return '';
    $value = trim($value);
    $value = strip_tags($value);
    $value = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
    return mb_substr($value, 0, $maxLength);
}

function validateEmail($email) {
    return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

function validatePhone($phone) {
    $phone = preg_replace('/[^0-9+\-\(\)\s]/', '', $phone);
    return strlen($phone) >= 10 && strlen($phone) <= 20;
}

// Extraer campos
$name = sanitize($data['name'] ?? '', 100);
$email = sanitize($data['email'] ?? '', 255);
$phone = sanitize($data['phone'] ?? '', 20);
$address = sanitize($data['address'] ?? '', 500);
$service = sanitize($data['service'] ?? '', 100);
$reason = sanitize($data['reason'] ?? '', 100);
$subject = sanitize($data['subject'] ?? '', 200);
$message = sanitize($data['message'] ?? '', 2000);
$origin_form = sanitize($data['origin'] ?? 'unknown', 255);

// Errores básicos
$errors = [];
if (strlen($name) < 2) $errors[] = 'Name is too short';
if (!validateEmail($email)) $errors[] = 'Invalid email';
if (!validatePhone($phone)) $errors[] = 'Invalid phone number';

if (!empty($errors)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'error' => implode(', ', $errors)]);
    exit;
}

// 1. CONEXIÓN A BASE DE DATOS
try {
    $pdo = new PDO(
        "mysql:host=" . DB_HOST . ";dbname=" . DB_NAME . ";charset=utf8mb4",
        DB_USER,
        DB_PASS,
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );

    $stmt = $pdo->prepare("INSERT INTO leads (name, email, phone, address, service, reason, subject, message, origin, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'new')");
    $stmt->execute([$name, $email, $phone, $address, $service, $reason, $subject, $message, $origin_form]);
    $leadId = $pdo->lastInsertId();
} catch (PDOException $e) {
    error_log("DB Error: " . $e->getMessage());
    // Continuamos aunque la DB falle para intentar enviar el correo
}

// 2. CONFIGURACIÓN DE ENVÍO DE CORREOS
require_once __DIR__ . '/vendor/PHPMailer/src/Exception.php';
require_once __DIR__ . '/vendor/PHPMailer/src/PHPMailer.php';
require_once __DIR__ . '/vendor/PHPMailer/src/SMTP.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

function sendEmail($to_list, $toName, $subject, $htmlBody) {
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host       = SMTP_HOST;
        $mail->SMTPAuth   = true;
        $mail->Username   = SMTP_USER;
        $mail->Password   = SMTP_PASS;
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_SMTPS; // SSL para puerto 465
        $mail->Port       = SMTP_PORT;
        $mail->CharSet    = 'UTF-8';

        $mail->setFrom(SMTP_FROM, SMTP_FROM_NAME);
        
        // Manejar múltiples correos separados por coma
        $addresses = explode(',', $to_list);
        foreach ($addresses as $addr) {
            $clean_addr = trim($addr);
            if (!empty($clean_addr)) {
                $mail->addAddress($clean_addr);
            }
        }

        $mail->isHTML(true);
        $mail->Subject = $subject;
        $mail->Body    = $htmlBody;

        return $mail->send();
    } catch (Exception $e) {
        error_log("Email error: " . $mail->ErrorInfo);
        return false;
    }
}

// 3. ENVIAR NOTIFICACIÓN AL EQUIPO
$timestamp = date('Y-m-d H:i:s');
$teamSubject = "🚨 NEW LEAD: " . $name . " [" . ($service ?: $reason) . "]";

$teamHtml = "
<div style='background-color: #00154d; color: #ffffff; padding: 20px; text-align: center;'>
    <div style='font-size: 20px; font-weight: bold; text-transform: uppercase;'>New Lead Received</div>
</div>
<div style='padding: 20px; border: 1px solid #eeeeee; line-height: 1.6;'>
    <h3 style='color: #00154d; border-bottom: 2px solid #d71635; padding-bottom: 5px;'>Customer Information</h3>
    <table style='width: 100%; border-collapse: collapse;'>
        <tr>
            <td style='padding: 8px 0; border-bottom: 1px solid #f4f4f4;'><strong>Name:</strong></td>
            <td style='padding: 8px 0; border-bottom: 1px solid #f4f4f4;'>" . $name . "</td>
        </tr>
        <tr>
            <td style='padding: 8px 0; border-bottom: 1px solid #f4f4f4;'><strong>Phone:</strong></td>
            <td style='padding: 8px 0; border-bottom: 1px solid #f4f4f4;'><a href='tel:" . $phone . "' style='color: #d71635; font-weight: bold;'>" . $phone . "</a></td>
        </tr>
        <tr>
            <td style='padding: 8px 0; border-bottom: 1px solid #f4f4f4;'><strong>Email:</strong></td>
            <td style='padding: 8px 0; border-bottom: 1px solid #f4f4f4;'><a href='mailto:" . $email . "'>" . $email . "</a></td>
        </tr>
        <tr>
            <td style='padding: 8px 0; border-bottom: 1px solid #f4f4f4;'><strong>Address:</strong></td>
            <td style='padding: 8px 0; border-bottom: 1px solid #f4f4f4;'>" . ($address ?: 'Not provided') . "</td>
        </tr>
    </table>

    <h3 style='color: #00154d; border-bottom: 2px solid #d71635; padding-bottom: 5px; margin-top: 20px;'>Request Details</h3>
    <p><strong>Service/Reason:</strong> " . ($service ?: $reason ?: 'General Inquiry') . "</p>
    " . ($message ? "<p style='background-color: #f9f9f9; padding: 10px; border-left: 3px solid #00154d;'><strong>Message:</strong><br>" . $message . "</p>" : "") . "
    
    <div style='margin-top: 20px; font-size: 12px; color: #777;'>
        <p><strong>Origin Form:</strong> " . $origin_form . "<br>
        <strong>Timestamp:</strong> " . $timestamp . "</p>
    </div>
</div>";

sendEmail(TEAM_EMAIL, 'Roofing Nation Team', $teamSubject, $teamHtml);


// 4. ENVIAR CONFIRMACIÓN AL CLIENTE (Versión exacta de tu editor)
$clientSubject = "We received your request - Roofing Nation";

$userHtml = "
<div style='background-color: #00154d; color: #ffffff; padding: 30px 20px; text-align: center;'>
    <img src='https://roofing-nation.com/roofing-nation-roofing-contractor.png' alt='Roofing Nation Logo' style='height: 60px; margin-bottom: 15px;' />
    <div style='font-size: 26px; font-weight: bold; text-transform: uppercase; letter-spacing: 1px;'>Roofing Nation LLC</div>
</div>
<div style='padding: 30px; line-height: 1.6;'>
    <h2 style='color: #00154d; margin-top: 0;'>Thank you for your request</h2>
    <p style='font-size: 16px;'>Hello <strong>" . $name . "</strong>,</p>
    <p style='font-size: 16px;'>We have received your request for a roofing quote regarding <span style='color: #d71635; font-weight: bold;'> " . ($service ?: $reason ?: 'our services') . " </span>.</p>
    <p style='font-size: 16px;'>Shortly, one of our specialists will reach out to greet you and coordinate the details. Our goal is to provide you with the <span style='color: #d71635; font-weight: bold;'>best possible price and service</span>.</p>
    <hr style='border: 0; border-top: 1px solid #eeeeee; margin: 25px 0;' />
    <h3 style='color: #00154d;'>Who are we?</h3>
    <p style='font-size: 15px;'>Roofing Nation LLC (<strong>#CCC1333780</strong>), specialists in residential and commercial roofing. We are here to help you protect what matters most.</p>
    <p style='margin: 25px 0;'><a href='https://roofing-nation.com/roofing-services' style='background-color: #d71635; color: #ffffff; padding: 12px 25px; text-decoration: none; border-radius: 5px; font-weight: bold; display: inline-block;'> Learn more about our services </a></p>
    <h3 style='color: #00154d;'>Direct contact:</h3>
    <p style='font-size: 15px; background-color: #f9f9f9; padding: 15px; border-left: 4px solid #d71635;'><strong>License:</strong> #CCC1333780<br /><strong>Phone:</strong> <a href='tel:3052491011' style='color: #333; text-decoration: none;'>(305) 249-1011</a></p>
    <p style='font-size: 16px; margin-top: 30px;'>Thank you very much for your trust. We will contact you soon.</p>
    <p style='font-size: 16px;'><strong>The Roofing Nation Team</strong></p>
</div>
<div style='background-color: #f4f4f4; padding: 20px; font-size: 12px; color: #777777; text-align: center;'>&copy; " . date('Y') . " Roofing Nation LLC &ndash; All rights reserved<br />Miami, Florida. Professional Roofing Services.</div>";

sendEmail($email, $name, $clientSubject, $userHtml);



// RESPUESTA FINAL
echo json_encode([
    'success' => true,
    'message' => 'Thank you! We will contact you shortly.'
]);