<?php
header('Content-Type: application/json');
session_start();
include '../db/koneksi.php';

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        throw new Exception('Metode request tidak valid.');
    }

    if (!isset($_SESSION['id'])) {
        throw new Exception('Sesi pengguna tidak ditemukan. Silakan login kembali.');
    }

    $qpending = mysqli_query($koneksi, "SELECT * FROM tb_deposit WHERE username='" . $_SESSION['username'] . "' AND status='Pending'");
    if (mysqli_num_rows($qpending) > 0) {
        throw new Exception('Anda memiliki deposit pending. Silakan selesaikan atau batalkan deposit tersebut sebelum membuat yang baru.');
    }

    $qpending = mysqli_query($koneksi, "SELECT * FROM tb_deposit WHERE username='" . $_SESSION['username'] . "' AND status='Pending'");

    $query_uuid = mysqli_query($koneksi, "SELECT uuid FROM tb_pga LIMIT 1");
    $uuid1 = null;
    if ($query_uuid && mysqli_num_rows($query_uuid) > 0) {
        $uuid_data = mysqli_fetch_assoc($query_uuid);
        $uuid1 = $uuid_data['uuid'];
    }
    $user_id   = $_SESSION['id'];
    $username = $_SESSION['username'] ?? '';
    $uuid      = $uuid1;
    $log_file  = __DIR__ . '/qris_log.txt';

    $jumlah = $_POST['amount'] ?? '0';

    $cleanAmount = preg_replace('/[^0-9]/', '', $jumlah);
    $amount = (int)$cleanAmount;
    $promo_id = $_POST['promo_id'] ?? null;

    if ($amount < 1000) {
        throw new Exception('Minimal deposit adalah Rp 10.000.');
    }

    $reference_number = 'DEP' . time() . rand(1000, 9999);

    $post_data = [
        'username' => $username,
        'amount'   => $amount,
        'uuid'     => $uuid,
        'bonus'    => '0',
    ];

    file_put_contents($log_file, "[" . date("Y-m-d H:i:s") . "] REQUEST: " . json_encode($post_data) . "\n", FILE_APPEND);

    $ch = curl_init('https://qris.otomatis.vip/api/generate');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/x-www-form-urlencoded']);
    $response = curl_exec($ch);
    $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curl_error = curl_error($ch);
    curl_close($ch);

    file_put_contents($log_file, "[" . date("Y-m-d H:i:s") . "] RESPONSE: status=$http_status, body=$response, error=$curl_error\n", FILE_APPEND);

    if ($curl_error) {
        throw new Exception("Gagal menghubungi API: $curl_error");
    }

    if ($http_status != 200) {
        throw new Exception("API gagal merespon: HTTP $http_status");
    }

    $data = json_decode($response, true);
    if (isset($data['status']) && $data['status'] == true) {
        $qr_string = $data['data'] ?? '';
        if (empty($qr_string)) {
            throw new Exception('Data QR tidak ditemukan dari API.');
        }

        $qr_url = "https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=" . urlencode($qr_string);
        $expired_at = date('Y-m-d H:i:s', strtotime('+15 minutes'));

        $_SESSION['qr_image'] = $qr_url;
        $_SESSION['amount'] = $amount;
        $_SESSION['expired'] = $expired_at;

        echo json_encode([
            'success' => true,
            'message' => 'QRIS berhasil dibuat! Silakan scan QR untuk menyelesaikan pembayaran.',
            'data' => [
                'reference_number' => $reference_number,
                'amount' => number_format($amount, 0, ',', '.'),
                'expired_at' => $expired_at,
                'qr_image' => $qr_url,
                'qr_string' => $qr_string
            ]
        ]);
    } else {
        throw new Exception('API mengembalikan error: ' . ($data['message'] ?? 'Tidak ada pesan error'));
    }
} catch (Exception $e) {
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}
