<?php
$barang = $barang ?? [];
$selectedKategori = (string) old('kategori_id', $barang['kategori_id'] ?? '');
$barangId = (int) ($barang['id'] ?? 0);
$disableStokAwal = (bool) ($disableStokAwal ?? false);
$stokAwalValue = $disableStokAwal
    ? ($barang['stok_awal'] ?? '0')
    : old('stok_awal', $barang['stok_awal'] ?? '0');
$kodeBarangValue = old('kode_barang', $barang['kode_barang'] ?? ($kodeBarang ?? ''));
?>

<section class="content-area">
    <?php $errors = session()->getFlashdata('errors'); ?>
    <?php if ($errors) : ?>
        <div class="alert alert-danger">
            <?php foreach ($errors as $error) : ?>
                <div><?= esc($error) ?></div>
            <?php endforeach; ?>
        </div>
    <?php endif; ?>

    <div class="panel p-4">
        <form action="<?= esc($action, 'attr') ?>" method="post" enctype="multipart/form-data" id="barangForm">
            <?= csrf_field() ?>

            <?php if (! empty($barang['foto'])) : ?>
                <div class="mb-4">
                    <div class="fw-semibold mb-2">Foto Saat Ini</div>
                    <img src="<?= base_url('uploads/barang/' . $barang['foto']) ?>" alt="Foto <?= esc($barang['nama_barang'] ?? '-') ?>" class="preview-photo">
                </div>
            <?php endif; ?>

            <div class="row g-4">
                <div class="col-12 col-lg-3">
                    <label for="kode_barang" class="form-label fw-semibold">Kode Barang</label>
                    <input type="text" class="form-control" id="kode_barang" name="kode_barang" value="<?= esc($kodeBarangValue, 'attr') ?>" data-check-url="<?= site_url('admin/barang/check-kode') ?>" data-exclude-id="<?= esc((string) $barangId, 'attr') ?>" readonly required>
                    <div class="form-text" id="kodeBarangFeedback">Kode dibuat otomatis. QR Code Barang menggunakan kode ini.</div>
                </div>

                 <div class="col-12 col-lg-3">
                    <label for="barcode" class="form-label fw-semibold">Barcode</label>
                    <input type="text" class="form-control" id="barcode" name="barcode" value="<?= esc(old('barcode', $barang['barcode'] ?? ''), 'attr') ?>" placeholder="<?= esc($kodeBarangValue, 'attr') ?>">
                    <div class="form-text">Kosongkan jika barcode ingin otomatis sama dengan kode barang.</div>
                </div>

                <div class="col-12 col-lg-6">
                    <label for="nama_barang" class="form-label fw-semibold">Nama Barang</label>
                    <input type="text" class="form-control" id="nama_barang" name="nama_barang" value="<?= esc(old('nama_barang', $barang['nama_barang'] ?? ''), 'attr') ?>" required>
                </div>

               

                <div class="col-12 col-lg-4">
                    <label for="kategori_id" class="form-label fw-semibold">Kategori</label>
                    <select class="form-select select2" id="kategori_id" name="kategori_id" data-placeholder="Pilih kategori" required>
                        <option value=""></option>
                        <?php foreach ($kategori as $item) : ?>
                            <option value="<?= esc($item['id'], 'attr') ?>" <?= $selectedKategori === (string) $item['id'] ? 'selected' : '' ?>>
                                <?= esc($item['nama_kategori']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div class="col-12 col-lg-2">
                    <label for="satuan" class="form-label fw-semibold">Satuan</label>
                    <input type="text" class="form-control" id="satuan" name="satuan" value="<?= esc(old('satuan', $barang['satuan'] ?? ''), 'attr') ?>" placeholder="pcs, unit, box" required>
                </div>

                <div class="col-12 col-lg-2">
                    <label for="stok_awal" class="form-label fw-semibold">Stok Awal</label>
                    <?php if ($disableStokAwal) : ?>
                        <input type="hidden" name="stok_awal" value="<?= esc((string) $stokAwalValue, 'attr') ?>">
                    <?php endif; ?>
                    <input type="number" class="form-control" id="stok_awal" name="<?= $disableStokAwal ? '' : 'stok_awal' ?>" value="<?= esc((string) $stokAwalValue, 'attr') ?>" min="0" <?= $disableStokAwal ? 'disabled' : 'required' ?>>
                    <?php if ($disableStokAwal) : ?>
                        <div class="form-text text-secondary">Stok awal dikunci karena barang sudah memiliki transaksi pembelian, penjualan, service, atau penyesuaian stok.</div>
                    <?php endif; ?>
                </div>

                <div class="col-12 col-lg-4">
                    <label for="stok_minimum" class="form-label fw-semibold">Stok Minimum</label>
                    <input type="number" class="form-control" id="stok_minimum" name="stok_minimum" value="<?= esc(old('stok_minimum', $barang['stok_minimum'] ?? '0'), 'attr') ?>" min="0" required>
                    <div class="form-text">Jika stok saat ini =< angka ini, barang ditandai hampir habis.</div>
                </div>

                <div class="col-12 col-lg-4">
                    <label for="lokasi_barang" class="form-label fw-semibold">Lokasi Barang</label>
                    <input type="text" class="form-control" id="lokasi_barang" name="lokasi_barang" value="<?= esc(old('lokasi_barang', $barang['lokasi_barang'] ?? ''), 'attr') ?>" placeholder="Contoh: Lemari A, baris 2 atau Ruang Lab">
                </div>

                <div class="col-12 col-lg-4">
                    <label for="harga_beli" class="form-label fw-semibold">Harga Beli</label>
                    <input type="number" class="form-control" id="harga_beli" name="harga_beli" value="<?= esc(old('harga_beli', $barang['harga_beli'] ?? '0'), 'attr') ?>" min="0" step="1" required>
                </div>

                <div class="col-12 col-lg-4">
                    <label for="harga_jual" class="form-label fw-semibold">Harga Jual</label>
                    <input type="number" class="form-control" id="harga_jual" name="harga_jual" value="<?= esc(old('harga_jual', $barang['harga_jual'] ?? '0'), 'attr') ?>" min="0" step="1" required>
                    <div class="form-text" id="hargaJualFeedback">Harga jual tidak boleh lebih kecil dari harga beli.</div>
                </div>

                <div class="col-12">
                    <label for="deskripsi_barang" class="form-label fw-semibold">Deskripsi Barang</label>
                    <textarea class="form-control" id="deskripsi_barang" name="deskripsi_barang" rows="3"><?= esc(old('deskripsi_barang', $barang['deskripsi_barang'] ?? '')) ?></textarea>
                </div>

                <div class="col-12">
                    <label for="foto" class="form-label fw-semibold"><?= empty($barang['foto']) ? 'Foto Barang' : 'Ganti Foto Barang' ?></label>
                    <input type="file" class="filepond-upload" id="foto" name="foto_upload" accept=".jpg,.jpeg,.png,.webp,image/*" data-temp-field="foto_temp" data-upload-url="<?= site_url('admin/uploads/temp/barang-photo') ?>">
                    <input type="hidden" name="foto_temp" value="<?= esc((string) old('foto_temp'), 'attr') ?>">
                    <div class="form-text">Format jpg, jpeg, png, atau webp. Maksimal 2 MB. Tombol submit otomatis nonaktif saat upload berjalan.</div>
                </div>
            </div>

            <div class="d-flex justify-content-end gap-2 mt-4">
                <a href="<?= site_url('admin/barang') ?>" class="btn btn-light">Batal</a>
                <button type="submit" class="btn btn-dark"><?= esc($submitLabel ?? 'Simpan') ?></button>
            </div>
        </form>
    </div>
</section>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const form = document.getElementById('barangForm');
        const kodeInput = document.getElementById('kode_barang');
        const feedback = document.getElementById('kodeBarangFeedback');
        const hargaBeliInput = document.getElementById('harga_beli');
        const hargaJualInput = document.getElementById('harga_jual');
        const hargaJualFeedback = document.getElementById('hargaJualFeedback');
        let checkTimer = null;
        let isKodeAvailable = true;

        const setFeedback = function (message, state) {
            feedback.textContent = message;
            feedback.className = 'form-text';
            kodeInput.classList.remove('is-valid', 'is-invalid');

            if (state === 'valid') {
                feedback.classList.add('text-success');
                kodeInput.classList.add('is-valid');
            }

            if (state === 'invalid') {
                feedback.classList.add('text-danger');
                kodeInput.classList.add('is-invalid');
            }
        };

        const checkKodeBarang = function () {
            const kode = kodeInput.value.trim();

            if (kode === '') {
                isKodeAvailable = false;
                setFeedback('Kode barang wajib diisi.', 'invalid');
                return;
            }

            const params = new URLSearchParams({
                kode_barang: kode,
                exclude_id: kodeInput.dataset.excludeId || '0'
            });

            setFeedback('Memeriksa kode barang...', null);

            fetch(kodeInput.dataset.checkUrl + '?' + params.toString(), {
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
                .then(function (response) {
                    return response.json();
                })
                .then(function (payload) {
                    isKodeAvailable = payload.available === true;
                    setFeedback(payload.message || (isKodeAvailable ? 'Kode barang tersedia.' : 'Kode barang sudah digunakan.'), isKodeAvailable ? 'valid' : 'invalid');
                })
                .catch(function () {
                    isKodeAvailable = false;
                    setFeedback('Gagal memeriksa kode barang. Coba lagi.', 'invalid');
                });
        };

        kodeInput.addEventListener('input', function () {
            window.clearTimeout(checkTimer);
            isKodeAvailable = false;
            checkTimer = window.setTimeout(checkKodeBarang, 400);
        });

        kodeInput.addEventListener('blur', checkKodeBarang);

        const isHargaJualValid = function () {
            const hargaBeli = Number(hargaBeliInput.value || 0);
            const hargaJual = Number(hargaJualInput.value || 0);
            const isValid = hargaJual >= hargaBeli;

            hargaJualInput.classList.toggle('is-invalid', ! isValid);
            hargaJualFeedback.classList.toggle('text-danger', ! isValid);

            return isValid;
        };

        hargaBeliInput.addEventListener('input', isHargaJualValid);
        hargaJualInput.addEventListener('input', isHargaJualValid);

        form.addEventListener('submit', function (event) {
            if (! isKodeAvailable) {
                event.preventDefault();
                checkKodeBarang();
                kodeInput.focus();
            }

            if (! isHargaJualValid()) {
                event.preventDefault();
                hargaJualInput.focus();
            }
        });
    });
</script>
