<?php
// Mulai sesi dan set zona waktu
session_start();
date_default_timezone_set("Asia/Jakarta");

// Memasukkan konfigurasi database dan autopayment
require_once('../config/koneksi.php');
include '../config/autopayment.php';

// Memeriksa apakah user sudah login atau belum
if (empty($_SESSION['user']) AND empty($_SESSION['pass'])) {
    header('Location: ../m');
    exit;
}

// Memeriksa apakah data yang diperlukan ada
if (isset($_POST['postID']) && isset($_POST['paymentMethod']) && isset($_POST['amount'])) {
    $userID = $_POST['postID'];
    $paymentMethod = $_POST['paymentMethod'];
    $amount = $_POST['amount'];
    $phoneNumber = isset($_POST['phoneNumber']) ? $_POST['phoneNumber'] : '';

    // Memvalidasi input
    if (!is_numeric($amount) || $amount <= 0) {
        header('Location: ../m?error=invalid_amount');
        exit;
    }

    // Mengambil informasi user
    $sql_user = "SELECT * FROM `tb_user` WHERE cuid = '$userID'";
    $result_user = mysqli_query($conn, $sql_user);
    if (mysqli_num_rows($result_user) > 0) {
        $user = mysqli_fetch_assoc($result_user);

        // Membuat invoice menggunakan metode autopayment
        $response = $AP->createinv($paymentMethod, $amount, $phoneNumber);
        $data = json_decode($response, true);

        if (isset($data['data']['trxid']) && isset($data['data']['checkout_url']) && isset($data['data']['status'])) {
            $trxid = $data['data']['trxid'];
            $checkoutUrl = $data['data']['checkout_url'];
            $status = $data['data']['status'];
            
            $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 ('$trxid',NOW(),'Auto Payment','$amount',0, '$catatan', '$gameid', '0','1','$paymentMethod','$paymentMethod','$userID',0)") or die(mysqli_error($conn));

            // Memasukkan transaksi ke dalam database
            $sql_insert = "INSERT INTO `tb_autopayment` (userID, payment_method, amount, phone_number, status, trxid, created_at) 
                           VALUES ('$userID', '$paymentMethod', '$amount', '$phoneNumber', '$status', '$trxid', NOW())";
            if (mysqli_query($conn, $sql_insert)) {
                header('Location: ' . $checkoutUrl);
                exit;
            } else {
                header('Location: ../m?error=transaction_creation_failed');
                exit;
            }
        } else {
            header('Location: ../m?error=invoice_creation_failed');
            exit;
        }
    } else {
        header('Location: ../m?error=user_not_found');
        exit;
    }
} else {
    header('Location: ../m?error=missing_data');
    exit;
}

// Menutup koneksi database
mysqli_close($conn);
?>
