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

if(!isset($_SESSION['user'])){
    die("Session user tidak ada");
}

$username = $_SESSION['user'];

$data = mysqli_query($conn, "
    SELECT k.*, p.harga
    FROM keranjang k
    JOIN produk p ON k.produk_id = p.id
    WHERE k.username='$username'
");

if(mysqli_num_rows($data) == 0){
    die("Keranjang kosong atau username tidak cocok");
}

while($d = mysqli_fetch_assoc($data)){
    $produk_id = $d['produk_id'];
    $qty = $d['qty'];
    $total = $d['harga'] * $qty;

    $insert = mysqli_query($conn, "
        INSERT INTO orders(username, produk_id, qty, total_harga, status, tanggal)
        VALUES('$username','$produk_id','$qty','$total','Dibayar',NOW())
    ");

    if(!$insert){
        die("Gagal insert orders: " . mysqli_error($conn));
    }

    mysqli_query($conn, "
        UPDATE produk
        SET stok = stok - $qty
        WHERE id = $produk_id
    ");
}

mysqli_query($conn, "
    DELETE FROM keranjang
    WHERE username='$username'
");

header("Location: orders.php");
exit;
?>