<?php
header('Content-Type: application/json');
require_once 'config.php';
require_once 'core/autoload.php';
require_once 'core/app/model/EventoData.php';

function sanitize_input($data) {
    return htmlspecialchars(strip_tags(trim($data)), ENT_QUOTES, 'UTF-8');
}

function enviarCorreoConAdjunto($to, $subject, $message, $from) {
    $smtpHost = SMTP_HOST;
    $smtpPort = SMTP_PORT;
    $smtpUser = SMTP_USERNAME;
    $smtpPass = SMTP_PASSWORD;
    $smtpSecure = SMTP_SECURE;
    $smtpFromName = SMTP_FROM_NAME;

    $composerAutoload = __DIR__ . '/vendor/autoload.php';
    if (file_exists($composerAutoload)) {
        require_once $composerAutoload;
    }

    if (class_exists('PHPMailer\PHPMailer\PHPMailer')) {
        try {
            $mail = new PHPMailer\PHPMailer\PHPMailer(true);
            $mail->isSMTP();
            $mail->Host = $smtpHost;
            $mail->Port = $smtpPort;
            $mail->SMTPAuth = true;
            $mail->Username = $smtpUser;
            $mail->Password = $smtpPass;
            $mail->CharSet = 'UTF-8';

            if (!empty($smtpSecure) && strtolower($smtpSecure) !== 'none') {
                if (strtolower($smtpSecure) === 'ssl') {
                    $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS;
                } else {
                    $mail->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS;
                }
            }

            $mail->setFrom($smtpUser, $smtpFromName);
            $mail->addAddress($to);
            $mail->addReplyTo($smtpUser, $smtpFromName);
            $mail->Subject = $subject;
            $mail->Body = $message;
            $mail->isHTML(false);
            $mail->Timeout = 15;

            return $mail->send();
        } catch (Exception $e) {
            error_log('PHPMailer Error: ' . $e->getMessage());
        }
    }

    // Fallback a mail()
    $headers = "From: {$smtpFromName} <{$smtpUser}>\r\n";
    $headers .= "Reply-To: {$smtpUser}\r\n";
    $headers .= "X-Mailer: PHP/" . phpversion() . "\r\n";
    $headers .= "Content-Type: text/plain; charset=UTF-8\r\n";

    return @mail($to, $subject, $message, $headers);
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'message' => 'Metodo no permitido']);
    exit;
}

$datos = [
    'nombre' => sanitize_input($_POST['nombre'] ?? ''),
    'celular' => sanitize_input($_POST['celular'] ?? ''),
    'empresa' => sanitize_input($_POST['empresa'] ?? ''),
    'correo' => sanitize_input($_POST['correo'] ?? ''),
    'asistencia' => sanitize_input($_POST['asistencia'] ?? 'si'),
    'id_evento' => isset($_POST['id_evento']) ? intval($_POST['id_evento']) : null,
    'fecha_evento' => sanitize_input($_POST['fecha_evento'] ?? ''),
    'sugerencias' => sanitize_input($_POST['sugerencias'] ?? 'Registro de evento virtual'),
];

if (empty($datos['nombre']) || empty($datos['celular']) || empty($datos['empresa']) || empty($datos['correo'])) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Faltan datos requeridos']);
    exit;
}

if (!filter_var($datos['correo'], FILTER_VALIDATE_EMAIL)) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Correo invalido']);
    exit;
}

try {
    $conexion = new mysqli(DB_SERVER, DB_SERVER_USERNAME, DB_SERVER_PASSWORD, DB_DATABASE);
    if ($conexion->connect_error) throw new Exception('Error de conexion');
    $conexion->set_charset("utf8mb4");

    $sql = "INSERT INTO forms (nombre, celular, empresa, correo, asistencia, id_evento, fecha_evento, sugerencias, fecha_creacion) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, NOW())";
    $stmt = $conexion->prepare($sql);
    if (!$stmt) throw new Exception('Error prepare: ' . $conexion->error);

    $stmt->bind_param(
        'sssssiss',
        $datos['nombre'],
        $datos['celular'],
        $datos['empresa'],
        $datos['correo'],
        $datos['asistencia'],
        $datos['id_evento'],
        $datos['fecha_evento'],
        $datos['sugerencias']
    );

    if (!$stmt->execute()) throw new Exception('Error execute: ' . $stmt->error);
    $insert_id = $stmt->insert_id;
    $stmt->close();
    $conexion->close();

    // Enviar correo de confirmacion
    $email_enviado = false;
    if ($datos['id_evento']) {
        $evento = EventoData::getById($datos['id_evento']);
        if ($evento) {
            $fechaTxt = strftime('%d de %B de %Y', strtotime($evento->fecha_evento));
            $horaInicio = substr($evento->hora_inicio, 0, 5);
            $horaFin = substr($evento->hora_fin, 0, 5);
            
            $subject = 'Confirmacion: ' . $evento->nombre_evento;
            $msg = "Hola " . $datos['nombre'] . ",\n\n";
            $msg .= "Tu registro fue confirmado.\n\n";
            $msg .= "Evento: " . $evento->nombre_evento . "\n";
            $msg .= "Fecha: " . $fechaTxt . " " . $horaInicio . " - " . $horaFin . "\n";
            if ($evento->lugar) $msg .= "Lugar: " . $evento->lugar . "\n";
            if ($evento->enlace_meet) $msg .= "Enlace: " . $evento->enlace_meet . "\n";
            $msg .= "\nGracias por tu participacion.\nEquipo TYKUN";
            
            $email_enviado = enviarCorreoConAdjunto(
                $datos['correo'],
                $subject,
                $msg,
                'info@consultora-tykun.com'
            );
        }
    }

    echo json_encode([
        'success' => true, 
        'message' => 'Formulario enviado correctamente', 
        'insert_id' => $insert_id,
        'email_enviado' => $email_enviado
    ]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error: ' . $e->getMessage()]);
}
