<?php
include 'koneksi.php';
include 'koneksiva.php';
session_start();

if (!isset($_POST['package_id'], $_POST['payment_method'], $_POST['order_id'])) {
    header("Location: ../membership.php");
    exit;
}

$package_id = intval($_POST['package_id']);
$payment_method = $_POST['payment_method'];
$order_id = $_POST['order_id'];

$query = "SELECT * FROM membership_packages WHERE package_id = $package_id";
$result = mysqli_query($conn, $query);
if (!$data = mysqli_fetch_assoc($result)) {
    header("Location: ../membership.php");
    exit;
}

$customer_name = $_SESSION['FullName'] ?? 'User';
$member_id = $_SESSION['UserID'] ?? '0';
$amount = $data['price'];
$status = 'Pending';
$type = 'Membership';

$sqlOrder = "INSERT INTO orders (order_id, member_id, order_type, total_harga, metode_bayar, status)
             VALUES ('$order_id', '$member_id', '$type', '$amount', '$payment_method', '$status')";
mysqli_query($conn, $sqlOrder);

$sqlOrder = "INSERT INTO membersip_order (order_id, membership_id, harga)
             VALUES ('$order_id', '$package_id', '$amount')";
mysqli_query($conn, $sqlOrder);

if ($payment_method == "Transfer Bank") {
    $va_number = "88" . rand(10000000, 99999999);
$sqlVA = "INSERT INTO virtual_account (va_number, order_id, customer_name, amount) 
          VALUES (?, ?, ?, ?)";
$stmt = $connva->prepare($sqlVA);
$stmt->bind_param("sssi", $va_number, $order_id, $customer_name, $amount); 
$stmt->execute();
$stmt->close();

        
    header("Location: ../detail_pembayaran.php?order_id=$order_id&method=$payment_method&va=$va_number&package_id=$package_id");

} else {
    header("Location: ../detail_pembayaran.php?order_id=$order_id&method=$payment_method&package_id=$package_id");

}
exit;
?>
