<?php
session_start();

include 'db.php';

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


/* Bikin mysqli lempar exception biar gampang ditangkap try/catch */
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

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

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

/* 1) 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()) {
    $stmt->close();
    die("Data pelanggan dengan email ini tidak ada!");
}
$stmt->close();

/* 2) Mulai transaksi DB */
$conn->begin_transaction();

try {
    /* 2a) Buat nomor invoice yang unik */
    do {
        try { $randpart = random_int(0, 9999); } catch (Exception $e) { $randpart = mt_rand(0, 9999); }
        $invoice = "INV" . date('Ymd') . sprintf("%04d", $randpart);

        $cek = $conn->prepare("SELECT 1 FROM transaksi WHERE Invoice = ? LIMIT 1");
        $cek->bind_param("s", $invoice);
        $cek->execute();
        $cek->store_result();
        $exists = $cek->num_rows > 0;
        $cek->close();
    } while ($exists);

    /* 2b) Tempelkan invoice ke item keranjang user yang belum ber-invoice */
    $up = $conn->prepare("UPDATE transaksi 
                          SET Invoice = ? 
                          WHERE no_plg = ? AND (Invoice IS NULL OR Invoice = '')");
    $up->bind_param("si", $invoice, $no_plg);
    $up->execute();

    if ($up->affected_rows <= 0) {
        $up->close();
        $conn->rollback();
        header("Location: dashboard.php");
        exit;
    }
    $up->close();

    /* 2c) Hitung total */
    $totSql = "
        SELECT 
            COALESCE(SUM( (b.Harga * (1 - COALESCE(b.Diskon,0)/100.0)) * t.Jumlah_beli ), 0) AS total_belanja
        FROM transaksi t
        JOIN barang b ON t.no_brg = b.no_id
        WHERE t.no_plg = ? AND t.Invoice = ?
    ";
    $stmtTot = $conn->prepare($totSql);
    $stmtTot->bind_param("is", $no_plg, $invoice);
    $stmtTot->execute();
    $stmtTot->bind_result($tot_jenderal);
    $stmtTot->fetch();
    $stmtTot->close();

    if ($tot_jenderal <= 0) {
        $conn->rollback();
        header("Location: dashboard.php");
        exit;
    }

    /* 2d) Ambil data rekening (ambil baris pertama; fallback '' kalau kosong) */
    $nama_bank = $norek = $an = '';
    $stmtRek = $conn->prepare("SELECT Nama_bank, No_rek, Atas_nama FROM rekening LIMIT 1");
    $stmtRek->execute();
    $stmtRek->bind_result($nama_bank, $norek, $an);
    $stmtRek->fetch(); // jika tabel kosong, variabel tetap '' (fallback)
    $stmtRek->close();

    /* 2e) Ambil email bukti pembayaran (fallback '' kalau kosong) */
    $email_resmi = '';
    $stmtBukti = $conn->prepare("SELECT Email_bukti FROM bukti LIMIT 1");
    $stmtBukti->execute();
    $stmtBukti->bind_result($email_resmi);
    $stmtBukti->fetch();
    $stmtBukti->close();

    /* 2f) Ambil ongkos kirim */
    $ongkos = 0;
    if ($resOngkir = $conn->query("SELECT Ongkos FROM kirim LIMIT 1")) {
        if ($row = $resOngkir->fetch_assoc()) {
            $ongkos = (int)($row['Ongkos'] ?? 0);
        }
        $resOngkir->free();
    }

    $conn->commit();

} catch (Throwable $e) {
    $conn->rollback();
    die("Terjadi kesalahan saat proses checkout: " . htmlspecialchars($e->getMessage()));
}

$conn->close();

/* Total akhir */
$grand_total = $tot_jenderal + $ongkos;
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="utf-8">
    <title>Check Out</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
        :root { --bg:#f7f7f9; --card:#ffffff; --text:#222; --muted:#666; --brand:#0a7c66; }
        * { box-sizing: border-box; }
        body { margin:0; background:var(--bg); color:var(--text); font-family:system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,'Open Sans','Helvetica Neue',sans-serif; }
        .wrap { max-width: 720px; margin: 48px auto; padding: 0 16px; }
        .card { background:var(--card); border-radius:20px; box-shadow:0 8px 24px rgba(0,0,0,.06); padding:28px; }
        h1 { margin:0 0 6px; font-size:28px; }
        .sub { color:var(--muted); margin:0 0 20px; }
        .kv { display:flex; justify-content:space-between; padding:10px 0; border-bottom:1px dashed #e7e7ec; }
        .kv:last-child { border-bottom:none; }
        .kv .k { color:var(--muted); }
        .total { font-size:20px; font-weight:700; color:var(--brand); }
        .cta { margin-top: 22px; display:flex; gap:12px; flex-wrap:wrap; }
        .btn { appearance:none; border:0; border-radius:999px; padding:12px 18px; cursor:pointer; font-weight:600; }
        .btn-primary { background:var(--brand); color:#fff; text-decoration:none; }
        .btn-ghost { background:transparent; color:var(--brand); border:2px solid var(--brand); text-decoration:none; }
        .bank { background:#f0faf7; border:1px solid #d7efe8; border-radius:14px; padding:16px; margin-top:16px; }
        code { background:#eef2ff; padding:2px 6px; border-radius:6px; }
        @media (max-width:520px){ .kv { flex-direction:column; gap:6px; } }
    </style>
</head>
<body>
<div class="wrap">
    <div class="card">
        <h1>Checkout Berhasil ✅</h1>
        <p class="sub">Terima kasih. Simpan nomor invoice ini untuk konfirmasi pembayaran.</p>

        <div class="kv">
            <div class="k">Nomor Invoice</div>
            <div><code><?= htmlspecialchars($invoice) ?></code></div>
        </div>
        <div class="kv">
            <div class="k">Subtotal Barang</div>
            <div>Rp <?= number_format((float)$tot_jenderal, 0, ',', '.') ?></div>
        </div>
        <div class="kv">
            <div class="k">Ongkos Kirim</div>
            <div>Rp <?= number_format((float)$ongkos, 0, ',', '.') ?></div>
        </div>
        <div class="kv">
            <div class="k total">Total Yang Harus Dibayar</div>
            <div class="total">Rp <?= number_format((float)$grand_total, 0, ',', '.') ?></div>
        </div>

        <div class="bank">
            <div><strong>Transfer ke Rekening:</strong></div>
            <div>Nama Bank: <?= htmlspecialchars($nama_bank) !== '' ? htmlspecialchars($nama_bank) : '-' ?></div>
            <div>No. Rek: <?= htmlspecialchars($norek) !== '' ? htmlspecialchars($norek) : '-' ?></div>
            <div>a/n: <?= htmlspecialchars($an) !== '' ? htmlspecialchars($an) : '-' ?></div>
        </div>

        <div style="margin-top:14px">
            Kirim bukti pembayaran ke email kami: <strong><?= htmlspecialchars($email_resmi) !== '' ? htmlspecialchars($email_resmi) : '-' ?></strong>
        </div>

        <div class="cta">
            <a class="btn btn-primary" href="dashboard.php">Selesai</a>
            <a class="btn btn-ghost" href="riwayat_invoice.php?inv=<?= urlencode($invoice) ?>">Lihat Rincian</a>
        </div>
    </div>
</div>
</body>
</html>
