<?php
session_start();
date_default_timezone_set("Asia/Jakarta");
include('../config/koneksi.php');
include('../config/class_softgaming.php');

// Set header untuk JSON response
header('Content-Type: application/json');

// Function untuk response JSON
function jsonResponse($success, $message, $data = null, $code = 200)
{
    http_response_code($code);
    echo json_encode([
        'success' => $success,
        'message' => $message,
        'data' => $data,
        'timestamp' => date('Y-m-d H:i:s')
    ], JSON_PRETTY_PRINT);
    exit;
}

// Check method
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(false, 'Method not allowed. Use POST method.', null, 405);
}

// Cek apakah user sudah login
if (!isset($_SESSION['user'])) {
    jsonResponse(false, 'Anda harus login terlebih dahulu.', null, 401);
}

try {
    // Ambil dan validasi input
    $username = trim($_POST['username'] ?? '');
    $amount = intval($_POST['amount'] ?? 0);
    $gameid = isset($_POST['gameid']) ? intval($_POST['gameid']) : 0;

    // Validasi username
    if (empty($username)) {
        jsonResponse(false, 'Username tidak boleh kosong', null, 400);
    }

    // Validasi amount
    $sql_0 = mysqli_query($conn, "SELECT mindepo FROM tb_seo WHERE cuid = 1 LIMIT 1");
    $s0 = mysqli_fetch_assoc($sql_0);
    $minDeposit = isset($s0['mindepo']) ? (int)str_replace(',', '', $s0['mindepo']) : 10000;

    if ($amount < $minDeposit) {
        jsonResponse(false, 'Minimum deposit adalah Rp ' . number_format($minDeposit, 0, ',', '.'), [
            'min' => $minDeposit,
            'provided' => $amount
        ], 400);
    }

    if ($amount > 10000000) {
        jsonResponse(false, 'Maximum deposit adalah Rp 10.000.000', [
            'max' => 10000000,
            'provided' => $amount
        ], 400);
    }

    // Ambil user data
    $user = mysqli_query($conn, "SELECT * FROM `tb_user` WHERE username = '" . mysqli_real_escape_string($conn, $username) . "'") or die(mysqli_error());
    $u = mysqli_fetch_array($user);

    if (!$u) {
        jsonResponse(false, 'User tidak ditemukan', null, 404);
    }

    $userID = $u['cuid'];

    // Ambil merchant UUID dari config (simpan di tb_seo)
    $configQuery = mysqli_query($conn, "SELECT qris_uuid, qris_uuid2, urlweb, urlweb2 FROM tb_seo WHERE cuid = 1 LIMIT 1");
    $config = mysqli_fetch_assoc($configQuery);

    // Tentukan website mana yang aktif berdasarkan URL saat ini
    $currentHost = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
    $currentUrl = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
    $currentFullUrl = $protocol . $currentHost;

    // Normalize URLs untuk perbandingan (hapus trailing slash)
    $urlweb1 = rtrim($config['urlweb'], '/');
    $urlweb2 = isset($config['urlweb2']) ? rtrim($config['urlweb2'], '/') : '';
    $currentFullUrl = rtrim($currentFullUrl, '/');

    // Tentukan UUID mana yang digunakan
    $merchantUUID = '';
    $urlweb = '';

    if (!empty($urlweb2) && (strpos($currentFullUrl, parse_url($urlweb2, PHP_URL_HOST)) !== false || $currentFullUrl === $urlweb2)) {
        // Website 2 aktif
        $merchantUUID = isset($config['qris_uuid2']) ? $config['qris_uuid2'] : '';
        $urlweb = $config['urlweb2'];
    } else {
        // Website 1 aktif (default)
        $merchantUUID = $config['qris_uuid'];
        $urlweb = $config['urlweb'];
    }

    if (empty($merchantUUID)) {
        $websiteName = !empty($urlweb2) && $currentFullUrl === $urlweb2 ? 'Website 2' : 'Website 1';
        jsonResponse(false, 'Merchant UUID untuk ' . $websiteName . ' belum dikonfigurasi. Silakan hubungi administrator.', null, 500);
    }

    // Generate QRIS via API otomatis.vip
    // custom_ref harus alphanumeric only (max 36 karakter)
    $customRef = 'DEPO' . time() . $userID;
    // Pastikan hanya alphanumeric dan max 36 karakter
    $customRef = preg_replace('/[^a-zA-Z0-9]/', '', $customRef);
    if (strlen($customRef) > 36) {
        $customRef = substr($customRef, -36); // Ambil 36 karakter terakhir
    }

    $postArray = [
        'username' => $username,
        'amount' => $amount,
        'uuid' => $merchantUUID,
        'expire' => 1200, // 20 menit
        'custom_ref' => $customRef
    ];

    $jsonData = json_encode($postArray);
    $headerArray = ['Content-Type: application/json'];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://rest.otomatis.vip/api/generate');
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headerArray);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);

    $response = curl_exec($ch);
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($curlError) {
        jsonResponse(false, 'Error koneksi ke server QRIS: ' . $curlError, null, 500);
    }

    if ($httpCode !== 200) {
        jsonResponse(false, 'Error dari server QRIS. HTTP Code: ' . $httpCode, ['response' => $response], 500);
    }

    $apiResponse = json_decode($response, true);

    if (!$apiResponse || !isset($apiResponse['status'])) {
        jsonResponse(false, 'Response tidak valid dari server QRIS', ['response' => $response], 500);
    }

    if ($apiResponse['status'] !== true) {
        $errorMsg = isset($apiResponse['message']) ? $apiResponse['message'] : 'Gagal generate QRIS';
        jsonResponse(false, $errorMsg, $apiResponse, 500);
    }

    if (!isset($apiResponse['data']) || empty($apiResponse['data'])) {
        jsonResponse(false, 'Data QRIS tidak ditemukan dalam response', $apiResponse, 500);
    }

    if (!isset($apiResponse['trx_id']) || empty($apiResponse['trx_id'])) {
        jsonResponse(false, 'Transaction ID tidak ditemukan dalam response', $apiResponse, 500);
    }

    $qrisData = $apiResponse['data'];
    $trxId = $apiResponse['trx_id'];

    // Generate kode transaksi
    $unik = date('Hs');
    $kode_unik = substr(str_shuffle('1234567890'), 0, 2);
    $kd_transaksi = date('Ymd') . $unik . $kode_unik;
    $created_date = date('Y-m-d H:i:s');

    // Simpan transaksi ke database
    // pay_from harus integer (0 untuk QRIS karena tidak menggunakan bank tertentu)
    // Informasi QRIS disimpan di kolom metode dan note
    $insert_transaksi = mysqli_query($conn, "INSERT INTO `tb_transaksi` 
        (`kd_transaksi`, `date`, `transaksi`, `total`, `saldo`, `note`, `gameid`, `providerID`, `jenis`, `metode`, `pay_from`, `userID`, `status`) 
        VALUES 
        ('$kd_transaksi', '$created_date', 'Top Up QRIS', '$amount', 0, 'QRIS VIP - TRX: $trxId', '$gameid', '0', '1', 'QRIS', '0', '$userID', 0)")
        or die(mysqli_error($conn));

    // Simpan data QRIS ke session untuk ditampilkan di halaman payment
    $_SESSION['qris_payment'] = [
        'kd_transaksi' => $kd_transaksi,
        'trx_id' => $trxId,
        'qris_data' => $qrisData,
        'amount' => $amount,
        'username' => $username,
        'created_at' => time()
    ];

    // Jika ada bonus, hitung dan simpan ke tb_turnover
    if ($gameid > 0) {
        $sql_transaksi = mysqli_query($conn, "SELECT * FROM `tb_post` WHERE cuid = '$gameid'") or die(mysqli_error($conn));
        $st = mysqli_fetch_array($sql_transaksi);

        if ($st) {
            $jml_to = $st['min_to'];
            $persen = $st['persen'] / 100;

            $bonusnya = $amount * $persen;
            $bonuse = round($bonusnya);

            if ($bonuse > 200000) {
                $bonusDepo = 200000;
            } else {
                $bonusDepo = $bonuse;
            }

            $totalTO = ($amount + $bonusDepo) * $jml_to;
            $sisaTO = ($amount + $bonusDepo) * $jml_to;

            $expiredAt = date('Y-m-d H:i:s', strtotime('+1 day'));
            $insertTO = mysqli_query($conn, "INSERT INTO `tb_turnover` 
                (`userID`, `trxID`, `depo`, `bonus`, `jmlh_to`, `total_to`, `sisa_to`, `status`, `created_at`, `expired_at`) 
                VALUES 
                ('$userID', '$kd_transaksi', '$amount', '$bonusDepo', '$jml_to', '$totalTO', '$sisaTO', 0, NOW(), '$expiredAt')")
                or die(mysqli_error($conn));
        }
    }

    // Redirect ke halaman payment (pakai host aktif, bukan url tb_seo yang bisa beda domain)
    if (!function_exists('get_active_base_url')) {
        include(__DIR__ . '/../config/url_helper.php');
    }
    $redirectBase = get_active_base_url();
    if ($redirectBase === '') {
        $redirectBase = rtrim($urlweb ?? '', '/');
    }

    jsonResponse(true, 'QRIS berhasil digenerate', [
        'redirect' => $redirectBase . '/m/account/qris_payment',
        'kd_transaksi' => $kd_transaksi,
        'trx_id' => $trxId
    ], 200);
} catch (Exception $e) {
    error_log('Exception in generate_qris_otomatis: ' . $e->getMessage());
    jsonResponse(false, 'Error: ' . $e->getMessage(), [
        'exception' => get_class($e),
        'file' => $e->getFile(),
        'line' => $e->getLine()
    ], 500);
}
