<?php
include '../../../config.php';

function sendMessage($chat_id, $text, $parse_mode = 'HTML') {
    global $API_KC;
    $url = "https://api.telegram.org/bot" . $API_KC . "/sendMessage";
    $data = ['chat_id' => $chat_id, 'text' => $text, 'parse_mode' => $parse_mode];
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);
}

$user_id = $_GET['id'] ?? null;
$amount_toman = (int)($_GET['amount'] ?? 0);
$refid = $_GET['refid'] ?? null;

$base_page_style = '<!DOCTYPE html><html lang="fa" dir="rtl"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>{TITLE}</title><style>body{font-family: sans-serif; display: grid; place-items: center; min-height: 100vh; background: #f9f9f9;}.card{background: #fff; border-radius: 12px; box-shadow: 0 4px 12px rgba(0,0,0,0.05); padding: 30px; text-align: center;}h2{color: {COLOR}; margin-bottom: 15px;}p{font-size: 1.1em; margin-bottom: 25px;}a{display: inline-block; padding: 12px 25px; background: #007aff; color: white; text-decoration: none; border-radius: 8px; font-weight: bold;}</style></head><body><div class="card"><h2>{ICON} {TITLE}</h2><p>{MESSAGE}</p><a href="https://t.me/' . $bottag . '">بازگشت به ربات</a></div></body></html>';

if ($refid) {
    $data = array('amount' => $amount_toman, 'refId' => $refid);

    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => "https://api.payping.ir/v2/pay/verify",
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 30,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "POST",
        CURLOPT_POSTFIELDS => json_encode($data),
        CURLOPT_HTTPHEADER => array(
            "Accept: application/json",
            "Authorization: Bearer " . $payping_token,
            "Content-Type: application/json"
        ),
    ));

    $response = curl_exec($curl);
    $http_code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $err = curl_error($curl);
    curl_close($curl);

    if ($http_code == 200) {
        $stmt = $connect->prepare("UPDATE user SET balancerial = balancerial + ? WHERE id = ?");
        $stmt->bind_param("is", $amount_toman, $user_id);
        $stmt->execute();

        $stmt_log = $connect->prepare("INSERT INTO rial_charges (user_id, amount, authority, ref_id, status, created_at) VALUES (?, ?, ?, ?, 'completed', NOW())");
        $auth_dummy = $refid;
        $stmt_log->bind_param("siss", $user_id, $amount_toman, $auth_dummy, $refid);
        $stmt_log->execute();

        $sets_query = $connect->query("SELECT balanceinvite FROM settings LIMIT 1");
        $settings_row = $sets_query->fetch_assoc();
        $invite_percent = $settings_row['balanceinvite'] ?? 0;

        $user_for_invite_res = $connect->query("SELECT inviter FROM user WHERE id = '$user_id' LIMIT 1");

        if ($user_for_invite_res && $user_for_invite_res->num_rows > 0) {
            $user_for_invite = $user_for_invite_res->fetch_assoc();

            if (!empty($user_for_invite['inviter']) && $invite_percent > 0) {
                $inviter_id = $user_for_invite['inviter'];

                $bonus_amount = (int)(($amount_toman * $invite_percent) / 100);

                if ($bonus_amount > 0) {
                    $connect->query("UPDATE user SET balancerial = balancerial + $bonus_amount WHERE id = '$inviter_id'");

                    $msg_inviter = "💰 تبریک! یکی از زیرمجموعه‌های شما از طریق پی‌پینگ خرید کرد.\n\n" .
                        "🎁 مبلغ " . number_format($bonus_amount) . " تومان پاداش به کیف پول شما اضافه شد.";
                    sendMessage($inviter_id, $msg_inviter);
                }
            }
        }

        sendMessage($user_id, "✅ پرداخت پی‌پینگ موفق: " . number_format($amount_toman) . " تومان شارژ شدید.");
        sendMessage($admins[0], "✅ واریز پی‌پینگ: " . number_format($amount_toman) . " تومان\nکاربر: $user_id");

        echo str_replace(['{TITLE}', '{COLOR}', '{ICON}', '{MESSAGE}'], ['پرداخت موفق', '#28a745', '✅', 'پرداخت موفق بود. کد پیگیری: ' . $refid], $base_page_style);

    } else {
        echo str_replace(['{TITLE}', '{COLOR}', '{ICON}', '{MESSAGE}'], ['خطا در تایید', '#dc3545', '❌', 'تایید پرداخت انجام نشد.'], $base_page_style);
    }

} else {
    echo str_replace(['{TITLE}', '{COLOR}', '{ICON}', '{MESSAGE}'], ['پرداخت ناموفق', '#dc3545', '❌', 'تراکنش توسط کاربر لغو شد.'], $base_page_style);

    $stmt_log_fail = $connect->prepare("INSERT INTO rial_charges (user_id, amount, authority, status, created_at) VALUES (?, ?, ?, 'failed', NOW())");
    $auth_dummy = 'cancelled';
    $stmt_log_fail->bind_param("sis", $user_id, $amount_toman, $auth_dummy);
    $stmt_log_fail->execute();
}
?>