<?php
declare(strict_types=1);
require_once __DIR__ . '/db/config.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = $_POST['name'] ?? 'Anónimo';
    $message = $_POST['message'] ?? '';
    $whatsappNumber = "5359177041";

    if (!empty($message)) {
        try {
            $stmt = db()->prepare("INSERT INTO listener_requests (name, message) VALUES (?, ?)");
            $stmt->execute([$name, $message]);
            
            // Redirect to WhatsApp
            $whatsappText = urlencode("Hola! Soy $name. Mi petición es: $message");
            $redirectUrl = "https://wa.me/$whatsappNumber?text=$whatsappText";
            
            header("Location: $redirectUrl");
            exit;
        } catch (Exception $e) {
            error_log("Error saving request: " . $e->getMessage());
            header("Location: index.php?error=1");
            exit;
        }
    }
}

header("Location: index.php");
exit;
