<?php
session_start();

include 'db.php';

// 🚫 Jika belum login
if (!isset($_SESSION['username'])) {
    header("Location: login.php");
    exit;
}

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

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

// 📧 Ambil email user dari session
$email = $_SESSION['username'];

// 🧾 Ambil transaksi yang belum punya invoice
$sql = "SELECT 
            t.no_id,
            p.Nama,
            p.Alamat,
            p.Email,
            p.No_hape,
            b.Nama_barang,
            b.Harga,
            t.Jumlah_beli
        FROM transaksi t
        JOIN pelanggan p ON t.no_plg = p.no_id
        JOIN barang b ON t.no_brg = b.no_id
        WHERE p.Email = ? AND (t.Invoice IS NULL OR t.Invoice = '')
        ORDER BY t.no_id DESC";

$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $email);
$stmt->execute();
$result = $stmt->get_result();

// 💅 Tampilan tabel
echo "
<!DOCTYPE html>
<html lang='id'>
<head>
<meta charset='UTF-8'>
<title>Keranjang Belanja</title>
<style>
    body { font-family: Verdana; background-color: #f8f9fa; }
    h1 { text-align: center; margin-top: 30px; color: #333; }
    table { width: 95%; margin: 20px auto; border-collapse: collapse; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
    th, td { padding: 10px 12px; border: 1px solid #ccc; text-align: center; }
    th { background-color: #007bff; color: white; }
    tr:nth-child(even) { background-color: #f2f2f2; }
    .total { text-align: right; font-weight: bold; background-color: #ffeeba; }
</style>
</head>
<body>
<h1>🛒 Daftar Belanja yang Belum Checkout</h1>
<table>
<tr>
    <th>No. Transaksi</th>
    <th>Nama Pelanggan</th>
    <th>Alamat</th>
    <th>Email</th>
    <th>No. HP</th>
    <th>Nama Barang</th>
    <th>Harga Satuan</th>
    <th>Jumlah</th>
    <th>Total Harga</th>
</tr>
";

$total_semua = 0;
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        $subtotal = $row['Harga'] * $row['Jumlah_beli'];
        $total_semua += $subtotal;

        echo "<tr>
                <td>{$row['no_id']}</td>
                <td>{$row['Nama']}</td>
                <td>{$row['Alamat']}</td>
                <td>{$row['Email']}</td>
                <td>{$row['No_hape']}</td>
                <td>{$row['Nama_barang']}</td>
                <td align='right'>" . number_format($row['Harga'], 0, ',', '.') . "</td>
                <td align='center'>{$row['Jumlah_beli']}</td>
                <td align='right'>" . number_format($subtotal, 0, ',', '.') . "</td>
              </tr>";
    }
    echo "<tr><td colspan='8' class='total'>Total Belanja</td>
              <td class='total'>" . number_format($total_semua, 0, ',', '.') . "</td></tr>";
} else {
    echo "<tr><td colspan='9' style='color:red; text-align:center;'>Tidak ada data di keranjang belanja.</td></tr>";
}

echo "</table></body></html>";

$stmt->close();
$conn->close();
?>
