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

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

    if (!empty($message)) {
        try {
            $stmt = db()->prepare("INSERT INTO listener_requests (name, phone, message) VALUES (?, ?, ?)");
            $stmt->execute([$name, $phone, $message]);
            
            // Redirect to Station WhatsApp
            $whatsappText = urlencode("Hola! Soy $name. Mi mensaje es: $message" . ($phone ? " (Mi WhatsApp: $phone)" : ""));
            $redirectUrl = "https://wa.me/$stationWhatsapp?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;