<?php
include "koneksi.php";

$id = intval($_GET['id'] ?? 0);

// Ambil transaksi master
$trans = $conn->query("SELECT * FROM tabel_transaksi WHERE id=$id")->fetch_assoc();
if (!$trans) {
    die("Transaksi tidak ditemukan!");
}

// Ambil detail transaksi
$detail = $conn->query("SELECT d.*, p.nama_produk 
    FROM tabel_transaksi_detail d 
    JOIN tabel_produk p ON d.produk_id = p.id 
    WHERE d.transaksi_id=$id");

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

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

    // Hitung total baru
    $total = 0;
    foreach ($items as $i => $pid) {
        $qty = (int)$qtys[$i];
        $harga = (float)$hargas[$i];
        $total += $qty * $harga;
    }

    $grand_total = $total; // tanpa PPN

    // Update master
    $stmt = $conn->prepare("UPDATE tabel_transaksi SET tanggal=?, customer=?, total=?, grand_total=? WHERE id=?");
    $stmt->bind_param("ssddi", $tanggal, $customer, $total, $grand_total, $id);
    $stmt->execute();

    // Hapus detail lama
    $conn->query("DELETE FROM tabel_transaksi_detail WHERE transaksi_id=$id");

    // Insert detail baru
    foreach ($items as $i => $pid) {
        $qty = (int)$qtys[$i];
        $harga = (float)$hargas[$i];
        $subtotal = $qty * $harga;

        $stmt_d = $conn->prepare("INSERT INTO tabel_transaksi_detail (transaksi_id, produk_id, qty, harga, subtotal) VALUES (?,?,?,?,?)");
        $stmt_d->bind_param("iiidd", $id, $pid, $qty, $harga, $subtotal);
        $stmt_d->execute();
    }

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

<div class="container mt-4">
    <h3>Edit Transaksi</h3>
    <form method="post">
        <div class="mb-3">
            <label>Tanggal</label>
            <input type="date" name="tanggal" class="form-control" value="<?= $trans['tanggal'] ?>" required>
        </div>
        <div class="mb-3">
            <label>Customer</label>
            <input type="text" name="customer" class="form-control" value="<?= $trans['customer'] ?>" required>
        </div>

        <h5>Detail Produk</h5>
        <table class="table table-bordered" id="tabelProduk">
            <thead>
                <tr>
                    <th>Produk</th>
                    <th>Harga</th>
                    <th>Qty</th>
                    <th>Subtotal</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php while($d = $detail->fetch_assoc()): ?>
                <tr>
                    <td>
                        <select name="produk_id[]" class="form-control" onchange="updateHarga(this)">
                            <option value="">-- Pilih Produk --</option>
                            <?php 
                            $produk->data_seek(0); 
                            while($p = $produk->fetch_assoc()): ?>
                                <option value="<?= $p['id'] ?>" data-harga="<?= $p['harga_eceran'] ?>"
                                    <?= ($p['id']==$d['produk_id']) ? 'selected' : '' ?>>
                                    <?= $p['nama_produk'] ?>
                                </option>
                            <?php endwhile; ?>
                        </select>
                    </td>
                    <td><input type="number" step="0.01" name="harga[]" class="form-control harga" value="<?= $d['harga'] ?>"></td>
                    <td><input type="number" name="qty[]" class="form-control qty" value="<?= $d['qty'] ?>" min="1"></td>
                    <td><input type="number" step="0.01" class="form-control subtotal" value="<?= $d['subtotal'] ?>" readonly></td>
                    <td><button type="button" class="btn btn-danger btn-sm" onclick="hapusRow(this)">X</button></td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>

        <button type="button" class="btn btn-info" onclick="tambahRow()">+ Tambah Produk</button>
        <br><br>
        <button type="submit" name="update" class="btn btn-success">Update Transaksi</button>
        <a href="index.php?page=transaksi" class="btn btn-secondary">Kembali</a>
        <a href="transaksi_cetak.php?id=<?= $id ?>" target="_blank" class="btn btn-primary">
    <i class="bi bi-printer"></i> Cetak Nota
</a>

    </form>
</div>

<script>
function updateHarga(el) {
    let harga = el.selectedOptions[0].getAttribute('data-harga');
    let tr = el.closest('tr');
    tr.querySelector('.harga').value = harga;
    hitungSubtotal(tr);
}
function hapusRow(btn) {
    btn.closest('tr').remove();
}
function tambahRow() {
    let tr = document.querySelector('#tabelProduk tbody tr').cloneNode(true);
    tr.querySelectorAll('input').forEach(i => i.value = '');
    document.querySelector('#tabelProduk tbody').appendChild(tr);
}
function hitungSubtotal(tr) {
    let harga = parseFloat(tr.querySelector('.harga').value) || 0;
    let qty = parseInt(tr.querySelector('.qty').value) || 0;
    tr.querySelector('.subtotal').value = (harga * qty).toFixed(2);
}
document.querySelectorAll('.qty, .harga').forEach(el=>{
    el.addEventListener('input', ()=>hitungSubtotal(el.closest('tr')));
});
</script>
