<?php

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);


include "/www/wwwroot/bilspro/config/connect.php";
include "/www/wwwroot/bilspro/payment/paydisini/api_control.php";

header('Content-Type: application/json');

function generateOrderId($pdo) {
    do {
        $order_id = sprintf('%013d', mt_rand(0, 9999999999999));
        $stmt = $pdo->prepare("SELECT COUNT(*) FROM apk_payment WHERE order_id = :order_id");
        $stmt->bindParam(':order_id', $order_id);
        $stmt->execute();
        $exists = $stmt->fetchColumn();
    } while ($exists > 0);
    return $order_id;
}

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => 'Metode tidak diperbolehkan']);
    exit;
}

$ids = $_POST['ids'] ?? '';
$idm = $_POST['idm'] ?? '';
$idv = $_POST['idv'] ?? '';
$wa  = $_POST['wa']  ?? '';

if (!preg_match('/^[0-9]{10,15}$/', $wa)) {
    echo json_encode(['success' => false, 'message' => 'Nomor WhatsApp tidak valid']);
    exit;
}
if (empty($ids) || empty($idm) || empty($idv)) {
    echo json_encode(['success' => false, 'message' => 'Data tidak lengkap']);
    exit;
}

$stmt = $pdo->prepare("SELECT * FROM profile_paket WHERE id = :idv");
$stmt->execute([':idv' => $idv]);
$data1 = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$data1) {
    echo json_encode(['success' => false, 'message' => 'Data paket tidak ditemukan']);
    exit;
}

$harga = $data1['harga_paket'];
$kodeprofile = $data1['nama_profile'];
$durasi = $data1['durasi'];

$karakter = "QWERTYUIOPASDFGHJKLZXCV12345098760987612345BNMQWERTYUIOPASGHJKLZXCVBNM";
$kodevoucher = $durasi . substr(str_shuffle($karakter), 0, 7) . 'VPG';
$create_time = date('Y-m-d H:i:s');

$stmt = $pdo->prepare("INSERT INTO ganerate_voucher 
    (id_data_server, id_agen_voucher, id_setting_mikrotik, id_profile_paket, voucher, harga, create_time, jenis, nomor_whatsapp)
    VALUES (:ids, NULL, :idm, :idv, :voucher, :harga, :create_time, 'api-pw', :nomor_whatsapp)");
$stmt->execute([
    ':ids' => $ids,
    ':idm' => $idm,
    ':idv' => $idv,
    ':voucher' => $kodevoucher,
    ':harga' => $harga,
    ':create_time' => $create_time,
    ':nomor_whatsapp' => $wa
]);
$last_id = $pdo->lastInsertId();

$order_id = generateOrderId($pdo);
$keterangan = "Pembelian voucher " . $kodevoucher;
$waktu_transaksi = date("Y-m-d H:i:s");

$stmt = $pdo->prepare("INSERT INTO apk_payment 
    (id_data_server, order_id, keterangan, waktu_transaksi, nominal, id_generate, status, jenis) 
    VALUES 
    (:ids, :order_id, :keterangan, :waktu_transaksi, :nominal, :id_generate, 'BELUM DIBAYAR', 'Hotspot')");
$stmt->execute([
    ':ids' => $ids,
    ':order_id' => $order_id,
    ':keterangan' => $keterangan,
    ':waktu_transaksi' => $waktu_transaksi,
    ':nominal' => $harga,
    ':id_generate' => $last_id
]);

$trxData = [
    'unique_code' => $order_id,
    'service' => 'qris',
    'amount' => $harga,
    'note' => $keterangan,
    'valid_time' => 300
];

$response = CreateTransaction($trxData);
$trxResult = json_decode($response);

if ($trxResult && $trxResult->success === true && isset($trxResult->data->qrcode_url)) {
    $qrImage = $trxResult->data->qrcode_url;
    $expired = $trxResult->data->expired;

    $stmt = $pdo->prepare("UPDATE apk_payment SET data_get = :data_get, status = 'PENDING' WHERE order_id = :order_id");
    $stmt->execute([
        ':data_get' => $response,
        ':order_id' => $order_id
    ]);

    echo json_encode([
        'success' => true,
        'voucher' => $kodevoucher,
        'exppay' => $expired,
        'order_id' => $order_id,
        'qr' => $qrImage
    ]);
    exit;
} else {
    echo json_encode(['success' => false, 'message' => 'Gagal membuat transaksi QR']);
    exit;
}
