<?php
require("../mainconfig.php");

// Ambil data akun QRIS dari database
$check_token = mysqli_query($db, "SELECT * FROM akun_qris");
$cek_token = mysqli_fetch_assoc($check_token);

// Ambil daftar deposit dengan status Waiting
$check_deposit = mysqli_query($db, "SELECT * FROM topup WHERE status = 'Waiting'");

/* ==========================
   FUNGSI CEK STATUS MUTASI
   ========================== */
function cek_status($nominal) {
    $url = 'https://app.orderkuota.com/api/v2/qris/mutasi/1531673';
    
    // Buat timestamp (dalam milidetik)
    $timestamp = round(microtime(true) * 1000);
    
    $signature = "0f4281aea38cab8f1212efe422671c5e66baf82ad8b24cece5c1169ba19a5095f46a925e5c652f7a96b9c9e66e2db9240d1ff5e1111cdf6c02802d0fe28597a9";

    // Data POST sesuai cURL terbaru
    $postdata = http_build_query([
        "app_reg_id" => "",
        "phone_uuid" => "fRY7qYvGQgKWDZ1N916dRg",
        "phone_model" => "ASUS_X01BDA",
        "requests[qris_history][keterangan]" => "",
        "requests[qris_history][jumlah]" => "",
        "request_time" => $timestamp,
        "phone_android_version" => "9",
        "app_version_code" => "250811",
        "auth_username" => "anugrahkim28",
        "requests[qris_history][page]" => "1",
        "auth_token" => "1531673:TP7tr5S8QIM3bRBezswNnX1KlWuOvgDF",
        "app_version_name" => "25.08.11",
        "ui_mode" => "light",
        "requests[qris_history][dari_tanggal]" => "",
        "requests[0]" => "account",
        "requests[qris_history][ke_tanggal]" => ""
    ]);

    // Header sesuai API terbaru
    $headers = [
        "signature: $signature",
        "timestamp: $timestamp",
        "Content-Type: application/x-www-form-urlencoded",
        "User-Agent: okhttp/4.12.0",
        "Accept-Encoding: gzip"
    ];

    // Gunakan cURL
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
    curl_setopt($ch, CURLOPT_ENCODING, "gzip"); // Penting!
    $response = curl_exec($ch);
    curl_close($ch);

    // Decode hasil JSON
    $result = json_decode($response, true);

    if (!$result || !isset($result['qris_history']['results'])) {
        return "error";
    }

    // Cek mutasi QRIS untuk menemukan nominal yang sesuai
    foreach ($result['qris_history']['results'] as $trx) {
        // Hanya cek transaksi masuk (status IN)
        if ($trx['status'] === "IN") {
            $kredit = str_replace('.', '', $trx['kredit']); // Hilangkan titik
            if ($kredit == $nominal) {
                return "ketemu";
            }
        }
    }
    return "tidak ketemu";
}

/* ==========================
   PROSES CEK DEPOSIT
   ========================== */
if (mysqli_num_rows($check_deposit) == 0) {
    $update_monitor = mysqli_query($db,"UPDATE monitor_cron SET status = 'Success', response = 'Deposit request not found', tanggal = '$date $time' WHERE judul = 'cek_deposit'");
    die("Deposit request not found.");
} else {
    while($data_order = mysqli_fetch_assoc($check_deposit)) {
        $rate = $cek_token['rate'];
        $yang_dibayar = (($data_order['jumlah'] - $data_order['kode_unik']) / $rate) + $data_order['kode_unik'];
        $depo_user = $data_order['username'];
        $check_user = mysqli_query($db, "SELECT * FROM users WHERE username = '$depo_user'");
        $data_user = mysqli_fetch_assoc($check_user);

        // Cek mutasi
        $outputnya = cek_status($yang_dibayar);

        if ($outputnya == "ketemu") {
            $tambah_saldo = ($data_user['balance'] + $data_order['jumlah']) - $data_order['kode_unik'] + ($data_order['kode_unik'] * $rate);
            $ubah_penulisan = number_format($data_order['jumlah'] - $data_order['kode_unik'] + ($data_order['kode_unik'] * $rate), 0, ',', '.');
            $untuk_quantity = $data_order['jumlah'] - $data_order['kode_unik'] + ($data_order['kode_unik'] * $rate);

            // Update saldo user
            mysqli_query($db, "UPDATE users SET balance = '$tambah_saldo' WHERE username = '$depo_user'");
            mysqli_query($db, "UPDATE topup SET status = 'Completed' WHERE username = '$depo_user'");
            mysqli_query($db, "INSERT INTO balance_history(username, action, quantity, msg, tanggal) VALUES ('$depo_user','Add Balance','$untuk_quantity','Kamu telah berhasil melakukan Topup saldo sebesar Rp $ubah_penulisan','$date $time')");
            mysqli_query($db, "INSERT INTO catatan (username, note, waktu) VALUES ('$depo_user', 'Kamu telah berhasil melakukan Topup saldo sebesar $ubah_penulisan', '$date $time')");

            $msg_type = "success";
            $msg_content = "Data Topup ditemukan, Username : $depo_user, Nominal : $ubah_penulisan<br/>";
        } else {
            $msg_type = "error";
            $msg_content = "Error, Data Topup tidak ditemukan, mohon transfer sesuai nominal, jika terkendala hubungi Admin.";
        }

        // Update monitor_cron
        mysqli_query($db, "UPDATE monitor_cron SET status = 'Success', response = '$msg_content', tanggal = '$date $time' WHERE judul = 'cek_deposit'");

        echo $msg_content;
    }
}
?>
