<?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: ../desktop');
    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: ../desktop?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'];

            // 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: ../desktop?error=transaction_creation_failed');
                exit;
            }
        } else {
            header('Location: ../desktop?error=invoice_creation_failed');
            exit;
        }
    } else {
        header('Location: ../desktop?error=user_not_found');
        exit;
    }
} else {
    header('Location: ../desktop?error=missing_data');
    exit;
}

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