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

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

// =============================================
// KONFIGURASI
// =============================================
define('TELEGRAM_BOT_TOKEN', '8728934350:AAGa-hb0ueh3WGjZTmlp-NrahkALe95K0Ak');
define('TELEGRAM_CHAT_ID',   '6640007661');
define('BUKAOLSHOP_TOKEN',   'V1lBZWVkR2tnTHpNU2pQMk53Z3EwTEZqN0hVa1lKOTlRbFAzSkdTcWRobllxMkVHMkM4cUZ4UE1GT3JXVDEyVXZ2N0NRNmlWUytvS0pDSFU3ZDRTbDZjNmxVSGdQZElyOGhkak4vcm5Kb1hZMUFnd0RVN2Z2YXZlUkFkT203WUVTTjZUaXlNOWhoWFc0T3I3cEhJcTFlNkNwUE5pZVJhWnlpVVhEeUQ0U1pQbUh6Um9HTzVWTiswQWFpV1hNakVH');
define('UPLOAD_DIR',         '../uploads/');

// =============================================
// BUAT TABEL JIKA BELUM ADA
// =============================================
$conn->query("
    CREATE TABLE IF NOT EXISTS deposit (
        id          INT AUTO_INCREMENT PRIMARY KEY,
        nama        VARCHAR(100)   NOT NULL,
        email       VARCHAR(100)   NOT NULL,
        telepon     VARCHAR(20)    NOT NULL,
        jumlah      BIGINT         NOT NULL,
        bukti       VARCHAR(255)   NOT NULL,
        status      ENUM('pending','approved','rejected') DEFAULT 'pending',
        created_at  TIMESTAMP DEFAULT CURRENT_TIMESTAMP
    )
");

// =============================================
// VALIDASI METHOD
// =============================================
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['status' => false, 'message' => 'Method tidak diizinkan']);
    exit;
}

// =============================================
// AMBIL & VALIDASI INPUT
// =============================================
$nama    = trim($_POST['nama']    ?? '');
$email   = trim($_POST['email']   ?? '');
$telepon = trim($_POST['telepon'] ?? '');
$jumlah  = trim($_POST['jumlah']  ?? '');

if (!$nama || !$email || !$telepon || !$jumlah || empty($_FILES['bukti']['name'])) {
    echo json_encode(['status' => false, 'message' => 'Semua field wajib diisi']);
    exit;
}

if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo json_encode(['status' => false, 'message' => 'Format email tidak valid']);
    exit;
}

if (!is_numeric($jumlah) || $jumlah <= 0) {
    echo json_encode(['status' => false, 'message' => 'Jumlah deposit tidak valid']);
    exit;
}

// =============================================
// UPLOAD FILE BUKTI
// =============================================
$allowed_ext = ['jpg', 'jpeg', 'png', 'pdf'];
$file_name   = $_FILES['bukti']['name'];
$file_tmp    = $_FILES['bukti']['tmp_name'];
$file_size   = $_FILES['bukti']['size'];
$file_ext    = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));

if (!in_array($file_ext, $allowed_ext)) {
    echo json_encode(['status' => false, 'message' => 'Format file tidak didukung (jpg, jpeg, png, pdf)']);
    exit;
}

if ($file_size > 5 * 1024 * 1024) {
    echo json_encode(['status' => false, 'message' => 'Ukuran file maksimal 5MB']);
    exit;
}

$new_filename = 'bukti_' . time() . '_' . uniqid() . '.' . $file_ext;
$upload_path  = UPLOAD_DIR . $new_filename;

if (!move_uploaded_file($file_tmp, $upload_path)) {
    echo json_encode(['status' => false, 'message' => 'Gagal mengupload file']);
    exit;
}

// =============================================
// VALIDASI EMAIL MEMBER DI BUKAOLSHOP
// =============================================
$emailValid  = cekEmailMember($email);
$nominal_fmt = 'Rp ' . number_format($jumlah, 0, ',', '.');

if (!$emailValid) {
    // Simpan ke database langsung rejected
    $stmt = $conn->prepare("
        INSERT INTO deposit (nama, email, telepon, jumlah, bukti, status)
        VALUES (?, ?, ?, ?, ?, 'rejected')
    ");
    $stmt->bind_param('sssds', $nama, $email, $telepon, $jumlah, $new_filename);
    $stmt->execute();
    $deposit_id = $stmt->insert_id;
    $stmt->close();

    // Notifikasi Telegram ke admin (tanpa button)
    $pesan_tg_invalid = "
⚠️ <b>DEPOSIT DITOLAK OTOMATIS</b>
━━━━━━━━━━━━━━━━━━
👤 <b>Nama</b>    : $nama
📧 <b>Email</b>   : $email
📱 <b>Telepon</b> : $telepon
💵 <b>Nominal</b> : $nominal_fmt
🔄 <b>Status</b>  : ❌ Email tidak terdaftar di sistem
🆔 <b>ID</b>      : #$deposit_id
━━━━━━━━━━━━━━━━━━
📎 Bukti: $new_filename
";
    sendTelegram($pesan_tg_invalid);
    sendTelegramPhoto($upload_path, "📎 Bukti Deposit #$deposit_id — $nama (EMAIL TIDAK VALID)");

    echo json_encode([
        'status'  => false,
        'message' => 'Email kamu tidak terdaftar di sistem BukaOlshop. Pastikan menggunakan email yang terdaftar.',
    ]);
    exit;
}

// =============================================
// SIMPAN KE DATABASE — STATUS PENDING
// Topup BELUM dilakukan, menunggu konfirmasi admin
// =============================================
$stmt = $conn->prepare("
    INSERT INTO deposit (nama, email, telepon, jumlah, bukti, status)
    VALUES (?, ?, ?, ?, ?, 'pending')
");
$stmt->bind_param('sssds', $nama, $email, $telepon, $jumlah, $new_filename);

if (!$stmt->execute()) {
    echo json_encode(['status' => false, 'message' => 'Gagal menyimpan data']);
    exit;
}

$deposit_id = $stmt->insert_id;
$stmt->close();

// =============================================
// KIRIM NOTIFIKASI TELEGRAM KE ADMIN
// Dengan inline button ✅ Terima & ❌ Tolak
// =============================================
$pesan_tg = "
💰 <b>DEPOSIT MASUK - QR AJAIB</b>
━━━━━━━━━━━━━━━━━━
👤 <b>Nama</b>    : $nama
📧 <b>Email</b>   : $email
📱 <b>Telepon</b> : $telepon
💵 <b>Nominal</b> : $nominal_fmt
🔄 <b>Status</b>  : ⏳ Menunggu Konfirmasi Admin
🆔 <b>ID</b>      : #$deposit_id
━━━━━━━━━━━━━━━━━━
📎 Bukti: $new_filename
";

$inline_keyboard = [
    'inline_keyboard' => [
        [
            ['text' => '✅ Terima',  'callback_data' => 'approve_' . $deposit_id],
            ['text' => '❌ Tolak',   'callback_data' => 'reject_'  . $deposit_id],
        ]
    ]
];

sendTelegramPhotoWithButton($upload_path, $pesan_tg, $inline_keyboard);
function sendTelegramPhotoWithButton($file_path, $caption, $reply_markup) {
    $url = 'https://api.telegram.org/bot' . TELEGRAM_BOT_TOKEN . '/sendPhoto';

    $post = [
        'chat_id'      => TELEGRAM_CHAT_ID,
        'photo'        => new CURLFile(realpath($file_path)),
        'caption'      => $caption,
        'parse_mode'   => 'HTML',
        'reply_markup' => json_encode($reply_markup),
    ];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_exec($ch);
    curl_close($ch);
}

// =============================================
// RESPONSE KE FRONTEND
// =============================================
echo json_encode([
    'status'  => true,
    'message' => 'Bukti berhasil dikirim, menunggu konfirmasi admin.',
    'data'    => [
        'id' => $deposit_id,
    ]
]);


// ============================================================
// 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 NOTIFIKASI TELEGRAM TANPA BUTTON
// =============================================
function sendTelegram($message) {
    $url  = 'https://api.telegram.org/bot' . TELEGRAM_BOT_TOKEN . '/sendMessage';
    $data = [
        'chat_id'    => TELEGRAM_CHAT_ID,
        'text'       => $message,
        'parse_mode' => 'HTML',
    ];

    $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);
    curl_exec($ch);
    curl_close($ch);
}

// =============================================
// FUNGSI NOTIFIKASI TELEGRAM DENGAN BUTTON
// =============================================
function sendTelegramWithButton($message, $reply_markup) {
    $url  = 'https://api.telegram.org/bot' . TELEGRAM_BOT_TOKEN . '/sendMessage';
    $data = [
        'chat_id'      => TELEGRAM_CHAT_ID,
        'text'         => $message,
        'parse_mode'   => 'HTML',
        'reply_markup' => $reply_markup,
    ];

    $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);
    curl_exec($ch);
    curl_close($ch);
}

// =============================================
// FUNGSI KIRIM FOTO BUKTI KE TELEGRAM
// =============================================
function sendTelegramPhoto($file_path, $caption = '') {
    $url = 'https://api.telegram.org/bot' . TELEGRAM_BOT_TOKEN . '/sendPhoto';

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,            $url);
    curl_setopt($ch, CURLOPT_POST,           true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,     [
        'chat_id'    => TELEGRAM_CHAT_ID,
        'photo'      => new CURLFile(realpath($file_path)),
        'caption'    => $caption,
        'parse_mode' => 'HTML',
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT,        15);
    curl_exec($ch);
    curl_close($ch);
}