<?php
include('config.php');
date_default_timezone_set('UTC');

// ⬇️ Define path (pastikan autoload.php sesuai struktur project)
define('GX_PATH', realpath(__DIR__ . '/'));
define('GX_LIB', GX_PATH . '/lib/');

require 'autoload.php';
require 'countrycodes.php';

new Db();

// Bot Telegram
$botToken = "7269003627:AAFNgRQEGH7phGarDvwB4Iyl1VByVln7wjo";
$chatId   = "-1001399120213";

// Pastikan parameter ada
if (isset($_GET['network'], $_GET['subid'], $_GET['payout'])) {
    $network = Typo::cleanX($_GET['network']);
    $subid   = Typo::cleanX($_GET['subid']);
    $payout  = isset($_GET['payout']) && is_numeric($_GET['payout']) ? (float)$_GET['payout'] : 0.00;
    $os      = isset($_GET['os']) ? Typo::cleanX($_GET['os']) : "";
    $countryCode = isset($_GET['country']) ? Typo::cleanX($_GET['country']) : "";
    $country = array_search($countryCode, $countrycodes) ?: $countryCode;
    $offer_name = isset($_GET['offer_name']) ? Typo::cleanX($_GET['offer_name']) : "Unknown";

    // Simpan ke database
    Db::insert([
        'table' => 'conversions',
        'key' => [
            'date'       => date('Y-m-d H:i:s'),
            'subid'      => $subid,
            'country'    => $country,
            'payout'     => $payout,
            'os'         => $os,
            'network'    => $network,
            'offer_name' => $offer_name
        ]
    ]);

    // Format pesan Telegram (tanpa \r\n)
    $data = "💢 <b>LEAD BARU</b> 💲\n";
    $data .= "Network: $network\n";
    $data .= "Subid: $subid\n";
    $data .= "Payout: $payout\n";
    $data .= "Country: $country\n";
    $data .= "OS: $os\n";
    $data .= "Offer: $offer_name\n";
    $data .= "\n💋 <b>Asololle..</b> 💃💃💃";

    // Kirim ke Telegram pakai CURL
    $url = "https://api.telegram.org/bot{$botToken}/sendMessage";
    $params = [
        'chat_id' => $chatId,
        'text' => $data,
        'parse_mode' => 'html'
    ];

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    $res = curl_exec($ch);
    $err = curl_error($ch);
    curl_close($ch);

    if ($err) {
        file_put_contents('telegram_error_log.txt', "Curl error: $err\n", FILE_APPEND);
    }

    // Debug output
    echo "OK";
} else {
    echo "Missing required parameters (network, subid, payout)";
}
