<?php
include "koneksi.php";

// Buat nomor transaksi otomatis
$no_transaksi = "TRX" . date("YmdHis");

// Ambil produk untuk dropdown
$produk = $conn->query("SELECT * FROM tabel_produk ORDER BY nama_produk ASC");

// Proses simpan transaksi
if (isset($_POST['simpan'])) {
    $tanggal   = $_POST['tanggal'];
    $customer  = $_POST['customer'];
    $items     = $_POST['produk_id'];
    $qtys      = $_POST['qty'];
    $hargas    = $_POST['harga'];

    $total = 0;

    // Hitung total
    foreach ($items as $i => $produk_raw) {
        // Ambil ID produk (jika format "id - nama", ambil id saja)
        $produk_parts = explode(" - ", $produk_raw, 2);
        $produk_id = (int) trim($produk_parts[0]);

        $qty   = (int) $qtys[$i];
        $harga = (float) $hargas[$i];
        $subtotal = $qty * $harga;
        $total += $subtotal;
    }

    $ppn = $total * 0.11;
    $grand_total = $total;

    // Simpan transaksi master
    $stmt = $conn->prepare("INSERT INTO tabel_transaksi 
        (no_transaksi, tanggal, customer, total, ppn, grand_total) 
        VALUES (?,?,?,?,?,?)");
    $stmt->bind_param("sssddd", $no_transaksi, $tanggal, $customer, $total, $ppn, $grand_total);
    $stmt->execute();
    $transaksi_id = $stmt->insert_id;

    // Simpan detail transaksi
    $stmt_detail = $conn->prepare("INSERT INTO tabel_transaksi_detail 
        (transaksi_id, produk_id, qty, harga, subtotal) 
        VALUES (?,?,?,?,?)");

    $stmt_update_stok = $conn->prepare("UPDATE tabel_produk SET stok = stok - ? WHERE id = ?");

    foreach ($items as $i => $produk_raw) {
        $produk_parts = explode(" - ", $produk_raw, 2);
        $produk_id = (int) trim($produk_parts[0]);

        $qty   = (int) $qtys[$i];
        $harga = (float) $hargas[$i];
        $subtotal = $qty * $harga;

        if ($produk_id > 0) {
            // Insert detail
            $stmt_detail->bind_param("iiidd", $transaksi_id, $produk_id, $qty, $harga, $subtotal);
            $stmt_detail->execute();

            // Update stok
            $stmt_update_stok->bind_param("ii", $qty, $produk_id);
            $stmt_update_stok->execute();
        }
    }

    echo "<script>alert('Transaksi berhasil disimpan!'); location.href='index.php?page=transaksi';</script>";
}
?>

<div class="container mt-4">
    <h3>Tambah Transaksi</h3>
    <form method="post">
        <div class="mb-3">
            <label>No Transaksi</label>
            <input type="text" name="no_transaksi" value="<?= $no_transaksi ?>" class="form-control" readonly>
        </div>
        <div class="mb-3">
            <label>Tanggal</label>
            <input type="date" name="tanggal" class="form-control" value="<?= date('Y-m-d') ?>" required>
        </div>
        <div class="mb-3">
            <label>Customer</label>
            <input type="text" name="customer" class="form-control" required>
        </div>

        <h5>Detail Produk</h5>
        <table class="table table-bordered" id="tabelProduk">
            <thead>
                <tr>
                    <th style="width:40%">Produk</th>
                    <th style="width:15%">Harga</th>
                    <th style="width:10%">Qty</th>
                    <th style="width:20%">Subtotal</th>
                    <th style="width:10%">Aksi</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>
                        <!-- Input manual dengan datalist -->
                        <input list="listProduk" name="produk_id[]" class="form-control" required onchange="setHarga(this)">
                        <datalist id="listProduk">
                            <?php while($p = $produk->fetch_assoc()): ?>
                                <option value="<?= $p['id'] ?> - <?= $p['nama_produk'] ?>" data-harga="<?= $p['harga_eceran'] ?>"></option>
                            <?php endwhile; ?>
                        </datalist>
                    </td>
                    <td><input type="number" name="harga[]" class="form-control harga" oninput="hitungSubtotal(this)"></td>
                    <td><input type="number" name="qty[]" class="form-control qty" value="1" min="1" oninput="hitungSubtotal(this)"></td>
                    <td><input type="number" class="form-control subtotal" readonly></td>
                    <td><button type="button" class="btn btn-danger btn-sm" onclick="hapusRow(this)">🗑</button></td>
                </tr>
            </tbody>
        </table>

        <button type="button" class="btn btn-info" onclick="tambahRow()">+ Tambah Produk</button>
        <br><br>
        <button type="submit" name="simpan" class="btn btn-success">Simpan Transaksi</button>
        <a href="index.php?page=transaksi" class="btn btn-secondary">Kembali</a>
    </form>
</div>

<script>
// Auto isi harga dari datalist
function setHarga(el) {
    let val = el.value;
    let option = Array.from(document.querySelectorAll('#listProduk option')).find(opt => opt.value === val);
    let tr = el.closest('tr');
    if (option) {
        let harga = option.getAttribute('data-harga') || 0;
        tr.querySelector('.harga').value = harga;
        hitungSubtotal(tr.querySelector('.qty'));
    }
}

function hitungSubtotal(el) {
    let tr = el.closest('tr');
    let harga = parseFloat(tr.querySelector('.harga').value) || 0;
    let qty   = parseInt(tr.querySelector('.qty').value) || 0;
    let subtotal = harga * qty;
    tr.querySelector('.subtotal').value = subtotal;
}

function tambahRow() {
    let row = document.querySelector('#tabelProduk tbody tr').cloneNode(true);
    row.querySelector('input[list]').value = "";
    row.querySelector('.harga').value = "";
    row.querySelector('.qty').value = 1;
    row.querySelector('.subtotal').value = "";
    document.querySelector('#tabelProduk tbody').appendChild(row);
}

function hapusRow(btn) {
    let tbody = document.querySelector('#tabelProduk tbody');
    if (tbody.rows.length > 1) {
        btn.closest('tr').remove();
    } else {
        alert("Minimal 1 produk harus ada.");
    }
}
</script>
