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

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

// 🔌 Koneksi DB
$conn = new mysqli($servername, $username, $password, $database);
$conn->set_charset("utf8mb4");
if ($conn->connect_error) {
    die("Koneksi gagal: " . htmlspecialchars($conn->connect_error));
}

$email = trim($_SESSION['username'] ?? '');
if ($email === '') die("Email pelanggan tidak ditemukan di session.");

// 🔍 Ambil no_id pelanggan
$stmt = $conn->prepare("SELECT no_id FROM pelanggan WHERE Email = ?");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->bind_result($no_plg);
if (!$stmt->fetch()) die("Data pelanggan tidak ditemukan!");
$stmt->close();

// 🔖 Ambil invoice dari URL jika ada
$invoice = trim($_GET['inv'] ?? '');

/* ==========================================================
   MODE 1 — LIST SEMUA INVOICE USER
   ==========================================================*/
if ($invoice === '') {
    $sql = "
        SELECT 
            t.Invoice,
            MAX(t.no_id) AS id_terakhir,
            COALESCE(DATE(MAX(t.Tanggal)), DATE(NOW())) AS Tanggal,
            SUM(
                COALESCE(b.Harga, 0) *
                (1 - COALESCE(b.Diskon, 0)/100.0) *
                COALESCE(t.Jumlah_beli, 0)
            ) AS Total
        FROM transaksi t
        JOIN barang b ON t.no_brg = b.no_id
        WHERE t.no_plg = ? AND t.Invoice IS NOT NULL AND t.Invoice <> ''
        GROUP BY t.Invoice
        ORDER BY id_terakhir DESC
    ";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $no_plg);
    $stmt->execute();
    $result = $stmt->get_result();
    ?>
    <!DOCTYPE html>
    <html lang="id">
    <head>
        <meta charset="utf-8">
        <title>Riwayat Invoice</title>
        <style>
            body {font-family:Verdana,Arial,sans-serif;background:#f7f7f7;margin:0}
            .wrap {max-width:800px;margin:40px auto;background:#fff;padding:24px;border-radius:12px;box-shadow:0 4px 16px rgba(0,0,0,.08);}
            table {width:100%;border-collapse:collapse;margin-top:16px}
            th,td {padding:10px;border-bottom:1px solid #eee;text-align:left}
            th {background:#fafafa}
            h2{text-align:center}
            a.btn {background:#0a7c66;color:#fff;padding:6px 12px;border-radius:6px;text-decoration:none}
            a.btn:hover{background:#0e9c80}
            .center{text-align:center;margin-top:20px}
        </style>
    </head>
    <body>
    <div class="wrap">
        <h2>Riwayat Transaksi Anda</h2>
        <?php if ($result->num_rows > 0): ?>
        <table>
            <tr>
                <th>Tanggal</th>
                <th>Nomor Invoice</th>
                <th>Total</th>
                <th>Aksi</th>
            </tr>
            <?php while($row = $result->fetch_assoc()): ?>
            <tr>
                <td><?= htmlspecialchars($row['Tanggal']) ?></td>
                <td><?= htmlspecialchars($row['Invoice']) ?></td>
                <td>Rp <?= number_format((float)$row['Total'],0,',','.') ?></td>
                <td><a class="btn" href="?inv=<?= urlencode($row['Invoice']) ?>">Lihat</a></td>
            </tr>
            <?php endwhile; ?>
        </table>
        <?php else: ?>
            <p style="text-align:center;">Belum ada transaksi.</p>
        <?php endif; ?>
        <div class="center">
            <a href="dashboard.php" class="btn">Kembali ke Dashboard</a>
            <a href="cetak_invoice.php?inv=<?= urlencode($invoice) ?>" class="btn">🖨 Cetak PDF</a>
        </div>
    </div>
    </body>
    </html>
    <?php
    $stmt->close();
    $conn->close();
    exit;
}

/* ==========================================================
   MODE 2 — LIHAT DETAIL INVOICE
   ==========================================================*/
$stmt = $conn->prepare("
    SELECT 
        b.Nama_barang,
        COALESCE(b.Harga,0) AS Harga,
        COALESCE(b.Diskon,0) AS Diskon,
        COALESCE(t.Jumlah_beli,0) AS Jumlah_beli
    FROM transaksi t
    JOIN barang b ON t.no_brg = b.no_id
    WHERE t.no_plg = ? AND t.Invoice = ?
");
$stmt->bind_param("is", $no_plg, $invoice);
$stmt->execute();
$result = $stmt->get_result();

$items = [];
$total = 0;
while ($r = $result->fetch_assoc()) {
    $hargaAsli   = (float)$r['Harga'];
    $diskon      = (float)$r['Diskon'];
    $qty         = (float)$r['Jumlah_beli'];
    $hargaDiskon = $hargaAsli * (1 - $diskon/100.0);
    $subtotal    = $hargaDiskon * $qty;
    $r['Subtotal'] = $subtotal;
    $total += $subtotal;
    $items[] = $r;
}
$stmt->close();

// 🚚 Ambil ongkos kirim
$ongkos = 0;
$res = $conn->query("SELECT Ongkos FROM kirim LIMIT 1");
if ($row = $res->fetch_assoc()) {
    $ongkos = (float)$row['Ongkos'];
}
$res->free();
$conn->close();

$grand = $total + $ongkos;
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <title>Invoice <?= htmlspecialchars($invoice) ?></title>
    <style>
        body{font-family:Verdana,Arial,sans-serif;background:#f7f7f7;margin:0}
        .wrap{max-width:800px;margin:40px auto;background:#fff;padding:24px;border-radius:12px;box-shadow:0 4px 16px rgba(0,0,0,.08);}
        table{width:100%;border-collapse:collapse;margin-top:16px}
        th,td{padding:10px;border-bottom:1px solid #eee;text-align:left}
        th{background:#fafafa}
        .total{text-align:right;font-weight:bold;padding:10px}
        .center{text-align:center;margin-top:20px}
        a.btn{background:#0a7c66;color:#fff;padding:8px 14px;border-radius:6px;text-decoration:none}
        a.btn:hover{background:#0e9c80}
    </style>
</head>
<body>
<div class="wrap">
    <h2>Invoice <?= htmlspecialchars($invoice) ?></h2>
    <?php if (!empty($items)): ?>
    <table>
        <tr>
            <th>Nama Barang</th>
            <th>Harga</th>
            <th>Diskon (%)</th>
            <th>Jumlah</th>
            <th>Subtotal</th>
        </tr>
        <?php foreach ($items as $it): ?>
        <tr>
            <td><?= htmlspecialchars($it['Nama_barang']) ?></td>
            <td>Rp <?= number_format((float)$it['Harga'],0,',','.') ?></td>
            <td><?= htmlspecialchars($it['Diskon']) ?></td>
            <td><?= htmlspecialchars($it['Jumlah_beli']) ?></td>
            <td>Rp <?= number_format((float)$it['Subtotal'],0,',','.') ?></td>
        </tr>
        <?php endforeach; ?>
        <tr><td colspan="4" class="total">Subtotal:</td>
            <td class="total">Rp <?= number_format((float)$total,0,',','.') ?></td></tr>
        <tr><td colspan="4" class="total">Ongkos Kirim:</td>
            <td class="total">Rp <?= number_format((float)$ongkos,0,',','.') ?></td></tr>
        <tr><td colspan="4" class="total"><b>Total Bayar:</b></td>
            <td class="total"><b>Rp <?= number_format((float)$grand,0,',','.') ?></b></td></tr>
    </table>
    <?php else: ?>
        <p class="center">Item untuk invoice ini tidak ditemukan.</p>
    <?php endif; ?>

    <div class="center">
        <a href="riwayat_invoice.php" class="btn">← Kembali ke Riwayat</a>
        <a href="dashboard.php" class="btn">Dashboard</a>
        <a href="cetak_invoice.php?inv=<?= urlencode($invoice) ?>" class="btn">🖨 Cetak PDF</a>
    </div>
    
</div>
</body>
</html>
