<?php
session_start();

include 'db.php';

// Pastikan user sudah login
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit;
}

// --- Ambil data dari session dengan aman ---
$nomor_brg   = $_SESSION['nomor_id']      ?? null;
$nomor_plg   = $_SESSION['nomor_id_plg']  ?? null;
$jumlah_beli = $_SESSION['jml_beli']      ?? 0;
$harga_baru  = $_SESSION['harga_baru']    ?? 0;

// --- Validasi dasar ---
if (!$nomor_brg || !$nomor_plg || $jumlah_beli <= 0 || $harga_baru <= 0) {
    die("<p style='color:red; text-align:center;'>❌ Data pembelian tidak lengkap atau tidak valid.</p>");
}

// Buat koneksi
$conn = new mysqli($servername, $username, $password, $database);
$conn->set_charset("utf8mb4");

if ($conn->connect_error) {
    die("Gagal koneksi: " . htmlspecialchars($conn->connect_error));
}

try {
    // Mulai transaksi database
    $conn->begin_transaction();

    // --- 1️⃣ Ambil stok lama ---
    $cek = $conn->prepare("SELECT Stok FROM barang WHERE no_id = ?");
    $cek->bind_param("i", $nomor_brg);
    $cek->execute();
    $cek->bind_result($stok_lama);
    if (!$cek->fetch()) {
        throw new Exception("Barang tidak ditemukan.");
    }
    $cek->close();

    if ($stok_lama < $jumlah_beli) {
        throw new Exception("❌ Stok tidak mencukupi. Stok saat ini: $stok_lama.");
    }

    // --- 2️⃣ Hitung total harga ---
    $tot = $jumlah_beli * $harga_baru;

    // --- 3️⃣ Simpan transaksi baru ---
    $stmt = $conn->prepare("
        INSERT INTO transaksi (no_brg, no_plg, Jumlah_beli)
        VALUES (?, ?, ?)
    ");
    $stmt->bind_param("iii", $nomor_brg, $nomor_plg, $jumlah_beli);
    if (!$stmt->execute()) {
        throw new Exception("Gagal menyimpan transaksi: " . $stmt->error);
    }
    $stmt->close();

    // --- 4️⃣ Update stok barang ---
    $stok_baru = $stok_lama - $jumlah_beli;
    $stmt = $conn->prepare("UPDATE barang SET Stok = ? WHERE no_id = ?");
    $stmt->bind_param("ii", $stok_baru, $nomor_brg);
    if (!$stmt->execute()) {
        throw new Exception("Gagal memperbarui stok barang: " . $stmt->error);
    }
    $stmt->close();

    // --- 5️⃣ Commit transaksi ---
    $conn->commit();

} catch (Exception $e) {
    $conn->rollback();
    die("<p style='color:red; text-align:center;'>Terjadi kesalahan: " . htmlspecialchars($e->getMessage()) . "</p>");
} finally {
    $conn->close();
}

?>

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Total Belanja Sementara</title>
    <style>
        body {
            font-family: Verdana, sans-serif;
            background: #f4f4f9;
            color: #333;
        }
        .container {
            text-align: center;
            margin-top: 80px;
        }
        .box {
            background: #fff;
            border: 1px solid #ddd;
            display: inline-block;
            padding: 40px 60px;
            border-radius: 12px;
            box-shadow: 0 4px 10px rgba(0,0,0,0.1);
        }
        h2 {
            color: #0066cc;
        }
        .total {
            font-size: 22px;
            font-weight: bold;
            color: #000;
        }
        .buttons {
            margin-top: 30px;
        }
        a {
            text-decoration: none;
            color: #0066cc;
            font-weight: bold;
        }
        a:hover {
            text-decoration: underline;
        }
        .note {
            margin-top: 15px;
            font-size: 13px;
            color: #777;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="box">
            <h2>✅ Transaksi Berhasil</h2>
            <p>Jumlah dibeli: <strong><?= $jumlah_beli ?></strong> barang</p>
            <p>Harga satuan: Rp <?= number_format($harga_baru, 0, '', '.') ?></p>
            <p class="total">Total: Rp <?= number_format($tot, 0, '', '.') ?></p>
            <div class="buttons">
                <a href="dashboard.php">🛒 Belanja Lagi</a> |
                <a href="cekout.php">💳 Cek Out</a>
            </div>
            <p class="note">Data transaksi tersimpan di database.</p>
        </div>
    </div>
</body>
</html>
