<?php
session_start();
include 'db.php';
require 'fpdf/fpdf.php';

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

$email = trim($_SESSION['username'] ?? '');
if ($email === '') {
    die("Sesi tidak valid: email kosong.");
}

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

function fetch_one(mysqli $conn, string $sql, string $types = '', array $params = []): ?array {
    $stmt = $conn->prepare($sql);
    if ($types && $params) $stmt->bind_param($types, ...$params);
    $stmt->execute();
    $res = $stmt->get_result();
    $row = $res->fetch_assoc() ?: null;
    $stmt->close();
    return $row;
}

/** 1️⃣ Ambil total transaksi belum ber-invoice */
$sqlTot = "
    SELECT 
        t.no_plg,
        SUM(t.Jumlah_beli * (CASE WHEN b.Diskon>0 
            THEN (b.Harga - b.Harga*(b.Diskon/100)) ELSE b.Harga END)) AS total_bayar
    FROM transaksi t
    JOIN barang b ON t.no_brg = b.no_id
    JOIN pelanggan p ON t.no_plg = p.no_id
    WHERE p.Email = ? AND t.Invoice IS NULL
";
$agg = fetch_one($conn, $sqlTot, "s", [$email]);

if (!$agg || !$agg['no_plg']) {
    echo "<center><font face=verdana size=4>Tidak ada transaksi di keranjang Anda.</font></center>";
    exit;
}

$no_plg = (int)$agg['no_plg'];
$total_bayar = (float)$agg['total_bayar'];

/** 2️⃣ Ambil data pelanggan */
$pel = fetch_one($conn, "SELECT Nama, Alamat, Email, No_hape FROM pelanggan WHERE Email = ?", "s", [$email]);
$nama_plg = $pel['Nama'] ?? '';
$alamat = $pel['Alamat'] ?? '';
$email_plg = $pel['Email'] ?? '';
$no_hp = $pel['No_hape'] ?? '';

/** 3️⃣ Buat invoice unik dan update transaksi */
$conn->begin_transaction();
try {
    do {
        $rand = random_int(0,9999);
        $invoice = "INV" . date('Ymd') . sprintf("%04d", $rand);
        $upd = $conn->prepare("UPDATE transaksi SET Invoice = ? WHERE no_plg = ? AND Invoice IS NULL");
        $upd->bind_param("si", $invoice, $no_plg);
        $upd->execute();
        if ($upd->affected_rows > 0) break;
    } while (true);
    $conn->commit();
} catch (Throwable $e) {
    $conn->rollback();
    die("Gagal membuat invoice: ".htmlspecialchars($e->getMessage()));
}

/** 4️⃣ Ambil daftar item */
$stmt = $conn->prepare("
    SELECT b.Nama_barang, b.Harga, b.Diskon, t.Jumlah_beli
    FROM transaksi t
    JOIN barang b ON t.no_brg = b.no_id
    WHERE t.Invoice = ?
");
$stmt->bind_param("s", $invoice);
$stmt->execute();
$res = $stmt->get_result();

$items = [];
while ($row = $res->fetch_assoc()) {
    $harga = $row['Harga'];
    $diskon = $row['Diskon'];
    $harga_final = $diskon>0 ? $harga - ($harga*$diskon/100) : $harga;
    $subtotal = $harga_final * $row['Jumlah_beli'];
    $items[] = [
        'nama' => $row['Nama_barang'],
        'harga' => $harga_final,
        'jumlah' => $row['Jumlah_beli'],
        'subtotal' => $subtotal
    ];
}
$stmt->close();

/** 5️⃣ Ambil data rekening & ongkos */
$rek = fetch_one($conn, "SELECT Nama_bank, No_rek, Atas_nama FROM rekening LIMIT 1");
$buk = fetch_one($conn, "SELECT Email_bukti FROM bukti LIMIT 1");
$kir = fetch_one($conn, "SELECT Ongkos FROM kirim LIMIT 1");

$nama_bank = $rek['Nama_bank'] ?? '(belum diset admin)';
$no_rek = $rek['No_rek'] ?? '(belum diset admin)';
$atas_nama = $rek['Atas_nama'] ?? '(belum diset admin)';
$email_resmi = $buk['Email_bukti'] ?? '(belum diset admin)';
$ongkos = isset($kir['Ongkos']) ? (float)$kir['Ongkos'] : 0.0;
$total_akhir = $total_bayar + $ongkos;

$conn->close();

/** 6️⃣ Buat PDF Invoice */
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(190,10,'INVOICE PEMBAYARAN',0,1,'C');

$pdf->SetFont('Arial','',12);
$pdf->Cell(190,8,'Nomor Invoice: '.$invoice,0,1,'C');
$pdf->Ln(8);

$pdf->SetFont('Arial','B',12);
$pdf->Cell(40,8,'Nama',0,0);
$pdf->SetFont('Arial','',12);
$pdf->Cell(100,8,': '.$nama_plg,0,1);

$pdf->SetFont('Arial','B',12);
$pdf->Cell(40,8,'Alamat',0,0);
$pdf->SetFont('Arial','',12);
$pdf->Cell(100,8,': '.$alamat,0,1);

$pdf->SetFont('Arial','B',12);
$pdf->Cell(40,8,'Email',0,0);
$pdf->SetFont('Arial','',12);
$pdf->Cell(100,8,': '.$email_plg,0,1);

$pdf->SetFont('Arial','B',12);
$pdf->Cell(40,8,'No. HP',0,0);
$pdf->SetFont('Arial','',12);
$pdf->Cell(100,8,': '.$no_hp,0,1);

$pdf->Ln(10);
$pdf->SetFont('Arial','B',11);
$pdf->Cell(10,8,'No',1,0,'C');
$pdf->Cell(80,8,'Nama Barang',1,0,'C');
$pdf->Cell(30,8,'Harga',1,0,'C');
$pdf->Cell(20,8,'Qty',1,0,'C');
$pdf->Cell(30,8,'Subtotal',1,1,'C');

$pdf->SetFont('Arial','',11);
$no=1;
foreach($items as $it){
    $pdf->Cell(10,8,$no++,1,0,'C');
    $pdf->Cell(80,8,utf8_decode($it['nama']),1,0);
    $pdf->Cell(30,8,number_format($it['harga'],0,',','.'),1,0,'R');
    $pdf->Cell(20,8,$it['jumlah'],1,0,'C');
    $pdf->Cell(30,8,number_format($it['subtotal'],0,',','.'),1,1,'R');
}
$pdf->SetFont('Arial','B',11);
$pdf->Cell(140,8,'TOTAL',1,0,'R');
$pdf->Cell(30,8,number_format($total_bayar,0,',','.'),1,1,'R');
$pdf->Cell(140,8,'Ongkos Kirim',1,0,'R');
$pdf->Cell(30,8,number_format($ongkos,0,',','.'),1,1,'R');
$pdf->Cell(140,8,'TOTAL BAYAR',1,0,'R');
$pdf->Cell(30,8,number_format($total_akhir,0,',','.'),1,1,'R');

$pdf->Ln(10);
$pdf->SetFont('Arial','',11);
$pdf->MultiCell(190,8,"Silakan transfer ke:\nNama Bank: $nama_bank\nNo. Rek: $no_rek\nA.n: $atas_nama\n\nKirim bukti pembayaran ke email: $email_resmi",0,'L');

$pdf->Ln(10);
$pdf->SetFont('Arial','I',10);
$pdf->Cell(190,6,'Terima kasih telah berbelanja.',0,1,'C');



$pdf->Output('I', "Invoice_$invoice.pdf");
?>
