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

if (!isset($_POST['product_id'], $_POST['payment_method'], $_POST['order_id'], $_POST['quantity'], $_POST['total_harga'], $_POST['tipe_pengambilan'])) {
    header("Location: ../product.php");
    exit;
}

$memberId = $_POST['member_id'];
$alamat = $_POST['alamat'];
$product_id = intval($_POST['product_id']);
$payment_method = $_POST['payment_method'];
$order_id = $_POST['order_id'];
$quantity = intval($_POST['quantity']);
$total_harga = intval($_POST['total_harga']);
$tipe_pengambilan = $_POST['tipe_pengambilan'];

$query = "SELECT * FROM products WHERE product_id = $product_id";
$result = mysqli_query($conn, $query);
if (!$product = mysqli_fetch_assoc($result)) {
    header("Location: ../product.php");
    exit;
}

if ($quantity > $product['stok']) {
    echo "Stok tidak mencukupi.";
    exit;
}

$customer_name = $_SESSION['FullName'] ?? 'User';
$member_id = $_SESSION['UserID'] ?? '0';
$status = 'Pending';
$type = 'Produk';

mysqli_query($conn, "UPDATE members SET alamat='$alamat' WHERE member_id='$member_id'");

$newStock = $product['stok'] - $quantity;
mysqli_query($conn, "UPDATE products SET stok = $newStock WHERE product_id = $product_id");

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

$sqlItem = "INSERT INTO order_items (order_id, product_id, jumlah, harga_satuan)
            VALUES ('$order_id', '$product_id', '$quantity', '{$product['harga']}')";
mysqli_query($conn, $sqlItem);

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, $total_harga); 
    $stmt->execute();
    $stmt->close();

    header("Location: ../detail_bayar_produk.php?order_id=$order_id&method=$payment_method&va=$va_number&product_id=$product_id");
} else {
    header("Location: ../detail_bayar_produk.php?order_id=$order_id&method=$payment_method&product_id=$product_id");
}
exit;
?>
