<?php
/**
 * callback.php
 * Endpoint ini dipanggil oleh Telegram saat admin klik button Terima/Tolak.
 * Daftarkan sebagai Webhook:
 *   https://api.telegram.org/bot<TOKEN>/setWebhook?url=https://yourdomain.com/api/callback.php
 */

require_once '../config/db.php';

define('TELEGRAM_BOT_TOKEN', '8728934350:AAGa-hb0ueh3WGjZTmlp-NrahkALe95K0Ak');
define('BUKAOLSHOP_TOKEN',   'V1lBZWVkR2tnTHpNU2pQMk53Z3EwTEZqN0hVa1lKOTlRbFAzSkdTcWRobllxMkVHMkM4cUZ4UE1GT3JXVDEyVXZ2N0NRNmlWUytvS0pDSFU3ZDRTbDZjNmxVSGdQZElyOGhkak4vcm5Kb1hZMUFnd0RVN2Z2YXZlUkFkT203WUVTTjZUaXlNOWhoWFc0T3I3cEhJcTFlNkNwUE5pZVJhWnlpVVhEeUQ0U1pQbUh6Um9HTzVWTiswQWFpV1hNakVH');

// Ambil payload dari Telegram
$update = json_decode(file_get_contents('php://input'), true);

// Hanya proses callback_query (klik inline button)
if (!isset($update['callback_query'])) {
    http_response_code(200);
    exit;
}

$callback    = $update['callback_query'];
$callback_id = $callback['id'];
$chat_id     = $callback['message']['chat']['id'];
$message_id  = $callback['message']['message_id'];
$data        = $callback['data']; // contoh: "approve_5" atau "reject_5"

// Parse aksi dan deposit_id
[$aksi, $deposit_id] = explode('_', $data, 2);
$deposit_id = intval($deposit_id);

if (!in_array($aksi, ['approve', 'reject']) || !$deposit_id) {
    answerCallback($callback_id, '❌ Data tidak valid');
    exit;
}

// Ambil data deposit (hanya yang masih pending)
$stmt = $conn->prepare("SELECT * FROM deposit WHERE id = ? AND status = 'pending'");
$stmt->bind_param('i', $deposit_id);
$stmt->execute();
$deposit = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$deposit) {
    answerCallback($callback_id, '⚠️ Deposit sudah diproses sebelumnya');
    editMessage($chat_id, $message_id, $callback['message']['text'], '⚠️ Sudah diproses');
    exit;
}

$nama        = $deposit['nama'];
$email       = $deposit['email'];
$jumlah      = $deposit['jumlah'];
$bukti       = $deposit['bukti'];
$nominal_fmt = 'Rp ' . number_format($jumlah, 0, ',', '.');

// =============================================
// PROSES APPROVE / REJECT
// =============================================
if ($aksi === 'approve') {

    // Validasi email sebelum topup
    if (!cekEmailMember($email)) {
        $conn->query("UPDATE deposit SET status='rejected' WHERE id=$deposit_id");

        kirimNotifMember(
            $email,
            '❌ Konfirmasi Saldo Gagal',
            "Mohon maaf konfirmasi saldo anda gagal silahkan hubungi admin"
        );

        $status_label = '❌ REJECTED — Email Tidak Terdaftar';
        answerCallback($callback_id, '❌ Email tidak terdaftar di sistem!');

    } else {
        $topup_result = topupSaldo($email, $jumlah);

        // ⚠️ DEBUG SEMENTARA — log raw response API
        error_log('[TOPUP DEBUG] raw response: ' . json_encode($topup_result, JSON_UNESCAPED_UNICODE));

        $topup_sukses = isset($topup_result['code']) && $topup_result['code'] == 200;

        if ($topup_sukses) {
            $conn->query("UPDATE deposit SET status='approved' WHERE id=$deposit_id");

            kirimNotifMember(
                $email,
                '💰 Deposit Berhasil Dikonfirmasi',
                "Halo $nama! Deposit kamu sebesar $nominal_fmt telah dikonfirmasi dan saldo kamu sudah ditambahkan. Terima kasih! 🎉"
            );

            $status_label = '✅ APPROVED — Saldo Berhasil Ditambahkan';
            answerCallback($callback_id, '✅ Deposit berhasil di-approve!');

        } else {
            $conn->query("UPDATE deposit SET status='rejected' WHERE id=$deposit_id");

            kirimNotifMember(
                $email,
                '❌ Konfirmasi Saldo Gagal',
                "Mohon maaf konfirmasi saldo anda gagal silahkan hubungi admin"
            );

            $status_label = '⚠️ APPROVE GAGAL — API Topup Error';
            answerCallback($callback_id, '⚠️ Approve gagal, API topup error!');
        }
    }

} else {
    // =============================================
    // REJECT — Admin klik tombol Tolak
    // =============================================
    $conn->query("UPDATE deposit SET status='rejected' WHERE id=$deposit_id");

    kirimNotifMember(
        $email,
        '❌ Konfirmasi Saldo Gagal',
        "Mohon maaf konfirmasi saldo anda gagal silahkan hubungi admin"
    );

    $status_label = '❌ REJECTED — Ditolak Admin';
    answerCallback($callback_id, '❌ Deposit berhasil ditolak');
}

// =============================================
// EDIT PESAN TELEGRAM — Hapus button, tampilkan status akhir
// =============================================
$pesan_update =
"💰 <b>DEPOSIT - QR AJAIB</b>
━━━━━━━━━━━━━━━━━━
👤 <b>Nama</b>    : {$nama}
📧 <b>Email</b>   : {$email}
💵 <b>Nominal</b> : {$nominal_fmt}
🔄 <b>Status</b>  : {$status_label}
🆔 <b>ID</b>      : #{$deposit_id}
━━━━━━━━━━━━━━━━━━
📎 Bukti: {$bukti}";

editCaption($chat_id, $message_id, $pesan_update);

http_response_code(200);
exit;

function editCaption($chat_id, $message_id, $caption) {
    $url = 'https://api.telegram.org/bot' . TELEGRAM_BOT_TOKEN . '/editMessageCaption';

    tgPost($url, [
        'chat_id'    => $chat_id,
        'message_id' => $message_id,
        'caption'    => $caption,
        'parse_mode' => 'HTML',
        'reply_markup' => ['inline_keyboard' => []] // hapus tombol
    ]);
}
// ============================================================
// FUNGSI CEK EMAIL MEMBER BUKAOLSHOP (loop semua halaman)
// ============================================================
function cekEmailMember($email) {
    $header = ["Authorization: Bearer " . BUKAOLSHOP_TOKEN];
    $page   = 1;

    do {
        $query = http_build_query(['page' => $page]);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,            "https://bukaolshop.net/api/v1/member/list?" . $query);
        curl_setopt($ch, CURLOPT_HTTPHEADER,     $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT,        10);
        $result = curl_exec($ch);
        curl_close($ch);

        $data = json_decode($result, true);

        if (empty($data['data']) || !is_array($data['data'])) {
            break;
        }

        // Cari email di halaman ini (case-insensitive)
        foreach ($data['data'] as $member) {
            if (isset($member['email_user']) && strtolower($member['email_user']) === strtolower($email)) {
                return true; // ✅ Email ditemukan
            }
        }

        // Ambil total halaman sesuai response API
        $total_page = $data['total_page']
                   ?? $data['last_page']
                   ?? $data['meta']['last_page']
                   ?? 1;

        $page++;

    } while ($page <= $total_page);

    return false; // ❌ Email tidak ditemukan
}

// =============================================
// FUNGSI TOP UP SALDO BUKAOLSHOP
// =============================================
function topupSaldo($email, $jumlah) {
    $header = [
        'Authorization: Bearer ' . BUKAOLSHOP_TOKEN,
        'Content-Type: application/x-www-form-urlencoded',
    ];
    $body = http_build_query([
        'email_user'  => $email,
        'tipe'        => 'tambah',
        'jumlah'      => (int)$jumlah,
        'notifikasi'  => 1,
    ]);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,            'https://bukaolshop.net/api/v1/member/saldo');
    curl_setopt($ch, CURLOPT_HTTPHEADER,     $header);
    curl_setopt($ch, CURLOPT_POST,           true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,     $body);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT,        15);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

// =============================================
// FUNGSI NOTIFIKASI MEMBER BUKAOLSHOP
// =============================================
function kirimNotifMember($email, $judul, $pesan) {
    $header = [
        'Authorization: Bearer ' . BUKAOLSHOP_TOKEN,
        'Content-Type: application/x-www-form-urlencoded',
    ];
    $url  = 'https://bukaolshop.net/api/v1/member/notifikasi';
    $body = http_build_query([
        'email_user'       => $email,
        'judul_notifikasi' => $judul,
        'pesan_notifikasi' => $pesan,
    ]);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,            $url);
    curl_setopt($ch, CURLOPT_HTTPHEADER,     $header);
    curl_setopt($ch, CURLOPT_POST,           true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,     $body);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT,        10);
    $res = curl_exec($ch);
    curl_close($ch);
    return json_decode($res, true);
}

// =============================================
// HELPER FUNCTIONS TELEGRAM
// =============================================
function answerCallback($callback_id, $text) {
    $url = 'https://api.telegram.org/bot' . TELEGRAM_BOT_TOKEN . '/answerCallbackQuery';
    tgPost($url, [
        'callback_query_id' => $callback_id,
        'text'              => $text,
        'show_alert'        => false,
    ]);
}

function editMessage($chat_id, $message_id, $text, $extra_note = '') {
    $url = 'https://api.telegram.org/bot' . TELEGRAM_BOT_TOKEN . '/editMessageText';
    tgPost($url, [
        'chat_id'      => $chat_id,
        'message_id'   => $message_id,
        'text'         => $text . ($extra_note ? "\n\n$extra_note" : ''),
        'parse_mode'   => 'HTML',
        'reply_markup' => ['inline_keyboard' => []], // hapus button setelah diproses
    ]);
}

function tgPost($url, $data) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,            $url);
    curl_setopt($ch, CURLOPT_POST,           true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,     json_encode($data));
    curl_setopt($ch, CURLOPT_HTTPHEADER,     ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT,        10);
    $res = curl_exec($ch);
    curl_close($ch);
    return $res;
}