<?php
// 1. Logika penangkapan barcode (Direct Add)
include 'aksi/koneksi.php';

if (isset($_GET['id_po'], $_GET['barcode'])) {
    $id_po = mysqli_real_escape_string($conn, $_GET['id_po']);
    $barcode = mysqli_real_escape_string($conn, $_GET['barcode']);
    
    $cek_brg = mysqli_query($conn, "SELECT id_barang FROM barang WHERE kode_barang = '$barcode'");
    $brg = mysqli_fetch_array($cek_brg);
    
    if ($brg) {
        $id_b = $brg['id_barang'];
        mysqli_query($conn, "INSERT INTO po_detail (id_po, id_barang, jumlah) VALUES ('$id_po', '$id_b', '1')");
        echo "<script>window.location='purchase-order.php?id_po=$id_po';</script>";
        exit;
    }
}

// 2. Include file sistem
include '_header.php';
include '_nav.php';
include '_sidebar.php'; 
  
$dataSupplier = query("SELECT * FROM supplier WHERE supplier_cabang = '$sessionCabang' AND supplier_status = '1' ORDER BY supplier_nama ASC");
?>

<style>
/* CSS UNTUK PRINT */
@media print {
    .no-print, .no-print * { display: none !important; }
    .kop-surat { display: block !important; text-align: center; margin-bottom: 20px; border-bottom: 2px solid #000; padding-bottom: 10px; }
    body { font-size: 12pt; }
    table { width: 100%; border-collapse: collapse; }
    table, th, td { border: 1px solid #000; padding: 5px; }
}
.kop-surat { display: none; }
</style>

<div class="content-wrapper">
    <section class="content-header no-print">
        <div class="container-fluid"><h1>Purchase Order</h1></div>
    </section>

    <section class="content">
        <div class="container-fluid">
            
            <div class="card card-primary no-print">
                <div class="card-header"><h3 class="card-title">Buat PO Baru / Tambah Item</h3></div>
                <div class="card-body">
                    <form id="form-po" action="aksi/tambah_detail_po.php" method="POST">
                        <input type="hidden" name="id_po" value="<?= htmlspecialchars($_GET['id_po'] ?? '0'); ?>">
                        <input type="hidden" name="id_cabang" value="<?= $sessionCabang; ?>">
                        <input type="hidden" name="user_input" value="<?= $sessionUserId; ?>">
                        
                        <div class="row align-items-end">
                            <div class="col-md-4">
                                <label>Scan / Cari Barang</label>
                                <div class="input-group">
                                    <select name="inputbarcode" id="pilih-barang" class="form-control" required style="width: 70%;">
                                        <option value="">-- Cari Nama / Kode Barang --</option>
                                        <?php
                                        $q_brg = mysqli_query($conn, "SELECT kode_barang, nama_barang FROM barang");
                                        while ($b = mysqli_fetch_array($q_brg)) {
                                            echo "<option value='".$b['kode_barang']."'>".$b['kode_barang']." - ".$b['nama_barang']."</option>";
                                        }
                                        ?>
                                    </select>
                                    <span class="input-group-append">
                                        <button type="button" class="btn btn-info" data-toggle="modal" data-target="#modal-id">
                                            <i class="fa fa-search"></i>
                                        </button>
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-3">
                                <label>No. PO</label>
                                <input type="text" class="form-control" value="PO-<?= date('YmdHis'); ?>" readonly>
                            </div>
                            <div class="col-md-3">
                                <label>Supplier</label>
                                <select name="id_supplier" class="form-control" required>
    <option value="">-- Pilih Supplier --</option>
    <?php foreach ($dataSupplier as $s) : ?>
        <option value="<?= $s['supplier_id']; ?>"><?= $s['supplier_nama']; ?></option>
    <?php endforeach; ?>
</select>
                            </div>
                            <div class="col-md-2">
                                <button type="submit" name="simpan_po" class="btn btn-primary btn-block">Simpan</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <?php if (isset($_GET['id_po']) && $_GET['id_po'] != '0') : 
                $id_po_get = mysqli_real_escape_string($conn, $_GET['id_po']);
                $data_po = mysqli_fetch_array(mysqli_query($conn, "SELECT po.*, s.supplier_nama FROM purchase_order po JOIN supplier s ON po.id_supplier = s.supplier_id WHERE po.id_po = '$id_po_get'"));
            ?>
            <div class="card card-secondary">
                <div class="kop-surat">
                    <h2>PT.ESKOL BERKAT UTAMA</h2>
                    <p>Jl. Prima Harapan Regency Jl. Lkr. Utara, RT.004/RW.007, Perwira, Kec. Bekasi Utara, Kota Bks, Jawa Barat 17123 - 081196916046</p>
                </div>
                <div class="card-header">
                    <h3 class="card-title">Detail PO: <?= $data_po['no_po'] ?? '-'; ?></h3>
                    <div class="card-tools no-print">
                        <button type="button" class="btn btn-default" onclick="window.print()">
                            <i class="fa fa-print"></i> Cetak PO
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <h5>Supplier: <?= $data_po['supplier_nama'] ?? '-'; ?></h5>
                    <table class="table table-bordered">
                        <thead>
                            <tr>
                                <th>Nama Barang</th>
                                <th>Jumlah</th>
                                <th class="no-print">Aksi</th>
                            </tr>
                        </thead>
                        <tbody id="tabel-po-detail"></tbody>
                    </table>
                </div>
            </div>
            <?php endif; ?>

           <div class="card no-print">
    <div class="card-header"><h3 class="card-title">Riwayat PO</h3></div>
    <div class="card-body">
        <table class="table table-bordered">
            <thead>
                <tr>
                    <th>No</th>
                    <th>No. PO</th>
                    <th>Supplier</th>
                    <th>Daftar Barang</th>
                    <th>Qty</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                <?php 
                $res_r = mysqli_query($conn, "SELECT po.*, s.supplier_nama FROM purchase_order po LEFT JOIN supplier s ON po.id_supplier = s.supplier_id ORDER BY po.id_po DESC");
                
                while($r = mysqli_fetch_array($res_r)) { 
                    $id_po_curr = $r['id_po'];
                    // Mengambil detail barang beserta id_detail agar bisa diupdate
                    $det = mysqli_query($conn, "SELECT pd.id_detail, b.nama_barang, pd.jumlah FROM po_detail pd JOIN barang b ON pd.id_barang = b.id_barang WHERE pd.id_po = '$id_po_curr'");
                ?>
                    <tr>
                        <td><?= $r['id_po']; ?></td>
                        <td><a href="?id_po=<?= $r['id_po']; ?>"><?= $r['no_po']; ?></a></td>
                        <td><?= $r['supplier_nama'] ?? '-'; ?></td>
                        <td>
                            <?php while($d = mysqli_fetch_array($det)) { echo $d['nama_barang'] . "<br><br>"; } ?>
                        </td>
                        <td>
                            <?php 
                            mysqli_data_seek($det, 0);
                            while($d = mysqli_fetch_array($det)) { 
                            ?>
                                <form action="aksi/update_qty.php" method="POST"> style="margin-bottom: 5px;">
                                    <input type="hidden" name="id_detail" value="<?= $d['id_detail']; ?>">
                                    <input type="hidden" name="id_po" value="<?= $id_po_curr; ?>">
                                    <div class="input-group input-group-sm" style="width: 120px;">
                                        <input type="number" name="jumlah" class="form-control" value="<?= $d['jumlah']; ?>" min="1">
                                        <div class="input-group-append">
                                            <button type="submit" class="btn btn-success"><i class="fa fa-check"></i></button>
                                        </div>
                                    </div>
                                </form>
                            <?php } ?>
                        </td>
                        <td><a href="aksi/hapus_po.php?id=<?= $r['id_po']; ?>" class="btn btn-danger btn-sm" onclick="return confirm('Hapus?');"><i class="fa fa-trash"></i></a></td>
                    </tr>
                <?php } ?>
            </tbody>
        </table>
    </div>
</div>

<div class="modal fade" id="modal-id" data-backdrop="static">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Pilih Barang</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <table id="example1" class="table table-bordered table-striped" style="width: 100%;">
                    <thead>
                        <tr>
                            <th>Nama Barang</th>
                            <th>Aksi</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<script>
$(document).ready(function(){
    $('#example1').DataTable({
        "processing": true,
        "ajax": {
            "url": "data-barang.php", // Pastikan file ini bisa diakses langsung
            "type": "GET",
            "dataSrc": "data" // INI KUNCI: Mengambil array dari key "data" di JSON Anda
        },
        "columns": [
            { "data": "nama" }, // Sesuai key di PHP
            { 
                "data": "kode", // Sesuai key di PHP
                "render": function(data, type, row) {
                    // Membuat tombol Pilih dengan kode barang
                    return '<button type="button" class="btn btn-info btn-sm" onclick="pilihBarang(\''+data+'\')">Pilih</button>';
                }
            }
        ]
    });
});
</script>

<script>
function pilihBarang(kode) {
    var selectElement = $('#pilih-barang');
    
    // Cek apakah kode barang sudah ada di pilihan <select>
    if (selectElement.find("option[value='" + kode + "']").length === 0) {
        // Jika belum ada, tambahkan option baru secara paksa
        // Catatan: Jika ingin nama barang muncul, Anda perlu mengirim nama barang dari modal
        selectElement.append(new Option(kode, kode, true, true));
    }
    
    // Pilih kode tersebut dan picu event change agar Select2/Form mendeteksi
    selectElement.val(kode).trigger('change');
    
    // Tutup modal
    $('#modal-id').modal('hide');
    $('.modal-backdrop').remove();
    $('body').removeClass('modal-open').css('overflow', '');
    
    // Debug: Cek apakah nilai sudah berubah di console
    console.log("Nilai select sekarang: " + selectElement.val());
}
</script>

<?php include '_footer.php'; ?>