<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<style>
/* ===== BASE ===== */
.btn:focus, .form-control:focus, .form-select:focus { box-shadow: none; }
.form-control:focus, .form-select:focus {
    border-color: #20c997;
    box-shadow: 0 0 0 3px rgba(32,201,151,.12);
}

/* ===== SECTION CARD ===== */
.form-section {
    border-radius: 14px;
    border: none;
    box-shadow: 0 1px 6px rgba(0,0,0,.07);
    overflow: hidden;
    margin-bottom: 20px;
}
.form-section-header {
    padding: 14px 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.85rem;
    font-weight: 700;
    text-transform: uppercase;
    letter-spacing: .05em;
    border-bottom: 1px solid #f1f3f5;
    color: #374151;
}
.form-section-header i { color: #20c997; font-size: 1rem; }
.form-section-body { padding: 20px; }

/* ===== LABELS ===== */
.field-label {
    font-size: 0.8rem;
    font-weight: 600;
    color: #374151;
    margin-bottom: 5px;
    display: block;
}
.field-label .req { color: #ef4444; margin-left: 2px; }

/* ===== INPUTS ===== */
.form-control, .form-select {
    border-radius: 8px;
    border: 1.5px solid #e5e7eb;
    font-size: 0.88rem;
    padding: 9px 12px;
    color: #111827;
    transition: border-color .2s, box-shadow .2s;
}
.form-control::placeholder { color: #9ca3af; }
.input-icon-wrap { position: relative; }
.input-icon-wrap .icon {
    position: absolute; left: 11px; top: 50%; transform: translateY(-50%);
    color: #20c997; font-size: .9rem; pointer-events: none; z-index: 2;
}
.input-icon-wrap .form-control,
.input-icon-wrap .form-select { padding-left: 34px; }
.input-icon-wrap .btn-append {
    position: absolute; right: 6px; top: 50%; transform: translateY(-50%);
    padding: 4px 10px; font-size: .75rem; border-radius: 6px;
    background: #f3f4f6; border: 1px solid #e5e7eb; color: #6b7280;
    cursor: pointer; transition: background .15s;
}
.input-icon-wrap .btn-append:hover { background: #e5e7eb; }
.input-icon-wrap .form-control.has-append { padding-right: 90px; }

/* ===== FOTO UPLOAD ===== */
.foto-drop {
    border: 2px dashed #d1fae5;
    background: #f0fdf9;
    border-radius: 12px;
    padding: 24px 16px;
    text-align: center;
    cursor: pointer;
    transition: border-color .2s, background .2s;
    position: relative;
}
.foto-drop:hover { border-color: #20c997; background: #e6faf5; }
.foto-drop input[type=file] {
    position: absolute; inset: 0; opacity: 0; cursor: pointer; width: 100%; height: 100%;
}
.foto-drop img#preview-foto {
    width: 100%; max-height: 180px; object-fit: cover;
    border-radius: 8px; display: none;
}
.foto-drop .placeholder-icon { font-size: 2.2rem; color: #20c997; opacity: .6; }
.foto-drop .drop-hint { font-size: .78rem; color: #6b7280; margin-top: 6px; }

/* Foto existing */
.foto-existing {
    border-radius: 10px;
    overflow: hidden;
    margin-bottom: 12px;
    position: relative;
}
.foto-existing img {
    width: 100%;
    max-height: 180px;
    object-fit: cover;
    border-radius: 10px;
}
.foto-existing .badge-existing {
    position: absolute;
    bottom: 8px; left: 8px;
    background: rgba(0,0,0,.55);
    color: #fff;
    font-size: .72rem;
    padding: 3px 10px;
    border-radius: 50px;
    backdrop-filter: blur(4px);
}

/* Gallery preview thumbnails */
#gallery-preview { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; }
.g-thumb { position: relative; width: 72px; height: 72px; }
.g-thumb img { width: 100%; height: 100%; object-fit: cover; border-radius: 8px; }
.g-thumb .rm { position: absolute; top: -5px; right: -5px; width: 18px; height: 18px;
    background: #ef4444; color: #fff; border-radius: 50%; border: none;
    font-size: 10px; display: flex; align-items: center; justify-content: center; cursor: pointer; }

/* ===== ACTION BAR ===== */
.action-bar {
    background: #fff;
    border-radius: 14px;
    box-shadow: 0 1px 6px rgba(0,0,0,.07);
    padding: 16px 20px;
    display: flex;
    gap: 10px;
    align-items: center;
    justify-content: flex-end;
}
.btn-save {
    background: #20c997; border: none; color: #fff;
    border-radius: 8px; padding: 10px 28px;
    font-weight: 700; font-size: .9rem;
    display: flex; align-items: center; gap: 6px;
    transition: background .2s, transform .15s;
}
.btn-save:hover { background: #1aab81; transform: translateY(-1px); color: #fff; }
.btn-cancel {
    background: #f3f4f6; border: 1.5px solid #e5e7eb; color: #6b7280;
    border-radius: 8px; padding: 10px 20px;
    font-weight: 600; font-size: .9rem;
    transition: background .15s;
}
.btn-cancel:hover { background: #e5e7eb; color: #374151; }

/* ===== TIPS BOX ===== */
.tips-box {
    background: #fffbeb;
    border: 1.5px solid #fde68a;
    border-radius: 12px;
    padding: 14px 16px;
    font-size: .8rem; color: #92400e;
}
.tips-box .tips-title { font-weight: 700; margin-bottom: 6px; color: #78350f; }
.tips-box ul { margin: 0; padding-left: 16px; }
.tips-box ul li { margin-bottom: 3px; }

/* ===== MOBILE ===== */
@media (max-width: 767.98px) {
    .container-fluid { padding-left: 12px !important; padding-right: 12px !important; }
    .page-header { flex-direction: column; align-items: flex-start !important; gap: 8px; margin-bottom: 16px !important; }
    .page-header h4 { font-size: 1rem; }
    .page-header nav { display: none; }
    .form-left, .form-right { padding: 0 !important; }
    .form-section-body { padding: 14px; }
    .field-col-half { flex: 0 0 100% !important; max-width: 100% !important; }
    .action-bar { flex-direction: column; }
    .action-bar .btn-save, .action-bar .btn-cancel { width: 100%; justify-content: center; }
}
</style>

<div class="container-fluid px-4 py-3">

    <!-- Header -->
    <div class="d-flex align-items-center justify-content-between mb-4 page-header">
        <div>
            <h4 class="mb-0 fw-bold text-dark">
                <i class="bi bi-pencil-square me-2" style="color:#20c997;"></i>Edit Inventaris
            </h4>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb mb-0 small">
                    <li class="breadcrumb-item"><a href="<?= base_url('dashboard') ?>" class="text-decoration-none" style="color:#20c997;">Home</a></li>
                    <li class="breadcrumb-item"><a href="<?= base_url('inventaris') ?>" class="text-decoration-none" style="color:#20c997;">Inventaris</a></li>
                    <li class="breadcrumb-item"><a href="<?= base_url('inventaris/detail/'.$item->id) ?>" class="text-decoration-none" style="color:#20c997;"><?= htmlspecialchars($item->nama_barang) ?></a></li>
                    <li class="breadcrumb-item active text-muted">Edit</li>
                </ol>
            </nav>
        </div>
        <a href="<?= base_url('inventaris/detail/'.$item->id) ?>" class="btn btn-sm btn-outline-secondary fw-semibold" style="border-radius:8px;">
            <i class="bi bi-arrow-left me-1"></i>Kembali
        </a>
    </div>

    <!-- Validation Errors -->
    <?php if(validation_errors()): ?>
    <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm mb-4" style="border-radius:10px;" role="alert">
        <i class="bi bi-exclamation-triangle-fill me-2"></i><?= validation_errors() ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <?php if($this->session->flashdata('error')): ?>
    <div class="alert alert-danger alert-dismissible fade show border-0 shadow-sm mb-4" style="border-radius:10px;" role="alert">
        <i class="bi bi-x-circle-fill me-2"></i><?= $this->session->flashdata('error') ?>
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    </div>
    <?php endif; ?>

    <form action="<?= base_url('inventaris/edit/'.$item->id) ?>" method="post" enctype="multipart/form-data" id="formInventaris" class="needs-validation" novalidate>

        <div class="row g-4">

            <!-- ===== LEFT: Informasi Barang ===== -->
            <div class="col-lg-8 form-left">

                <!-- Identitas -->
                <div class="form-section">
                    <div class="form-section-header">
                        <i class="bi bi-info-circle-fill"></i> Informasi Barang
                    </div>
                    <div class="form-section-body">
                        <div class="row g-3">

                            <!-- Kode Barang -->
                            <div class="col-md-6">
                                <label class="field-label">Kode Barang <span class="req">*</span></label>
                                <div class="input-icon-wrap">
                                    <i class="bi bi-upc icon"></i>
                                    <input type="text" class="form-control has-append" id="kode_barang" name="kode_barang"
                                           placeholder="INV-2024-001" required
                                           value="<?= set_value('kode_barang', $item->kode_barang) ?>">
                                    <button type="button" class="btn-append" onclick="generateKode()">
                                        <i class="bi bi-magic me-1"></i>Auto
                                    </button>
                                </div>
                                <small class="text-muted" style="font-size:.75rem;">Kode unik identifikasi barang</small>
                            </div>

                            <!-- Nama Barang -->
                            <div class="col-md-6">
                                <label class="field-label">Nama Barang <span class="req">*</span></label>
                                <div class="input-icon-wrap">
                                    <i class="bi bi-box icon"></i>
                                    <input type="text" class="form-control" id="nama_barang" name="nama_barang"
                                           placeholder="Contoh: Laptop ASUS VivoBook" required
                                           value="<?= set_value('nama_barang', $item->nama_barang) ?>">
                                </div>
                            </div>

                            <!-- Kategori -->
                            <div class="col-md-6">
                                <label class="field-label">Kategori <span class="req">*</span></label>
                                <div class="input-icon-wrap">
                                    <i class="bi bi-tags icon"></i>
                                    <select class="form-select" id="kategori" name="kategori" required>
                                        <option value="">-- Pilih Kategori --</option>
                                        <?php foreach($kategori as $key => $value): ?>
                                            <option value="<?= $key ?>"
                                                <?= (set_value('kategori', $item->kategori) == $key) ? 'selected' : '' ?>>
                                                <?= $value ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                            <!-- Kondisi -->
                            <div class="col-md-6">
                                <label class="field-label">Kondisi <span class="req">*</span></label>
                                <div class="input-icon-wrap">
                                    <i class="bi bi-heart-pulse icon"></i>
                                    <select class="form-select" id="kondisi" name="kondisi" required>
                                        <option value="">-- Pilih Kondisi --</option>
                                        <option value="baik"         <?= (set_value('kondisi', $item->kondisi) == 'baik')         ? 'selected' : '' ?>>✅ Baik</option>
                                        <option value="rusak_ringan" <?= (set_value('kondisi', $item->kondisi) == 'rusak_ringan') ? 'selected' : '' ?>>⚠️ Rusak Ringan</option>
                                        <option value="rusak_berat"  <?= (set_value('kondisi', $item->kondisi) == 'rusak_berat')  ? 'selected' : '' ?>>❌ Rusak Berat</option>
                                    </select>
                                </div>
                            </div>

                            <!-- Jumlah -->
                            <div class="col-4 col-md-3">
                                <label class="field-label">Jumlah <span class="req">*</span></label>
                                <input type="number" class="form-control" id="jumlah" name="jumlah"
                                       min="1" value="<?= set_value('jumlah', $item->jumlah) ?>" required>
                            </div>

                            <!-- Satuan -->
                            <div class="col-8 col-md-3">
                                <label class="field-label">Satuan</label>
                                <input type="text" class="form-control" id="satuan" name="satuan"
                                       placeholder="Unit / Pcs / Set"
                                       value="<?= set_value('satuan', $item->satuan) ?>">
                            </div>

                            <!-- Lokasi -->
                            <div class="col-md-6">
                                <label class="field-label">Lokasi Penyimpanan</label>
                                <div class="input-icon-wrap">
                                    <i class="bi bi-geo-alt icon"></i>
                                    <input type="text" class="form-control" id="lokasi" name="lokasi"
                                           placeholder="Gudang RT 01 / Ruang Meeting"
                                           value="<?= set_value('lokasi', $item->lokasi) ?>">
                                </div>
                            </div>

                        </div>
                    </div>
                </div>

                <!-- Pembelian -->
                <div class="form-section">
                    <div class="form-section-header">
                        <i class="bi bi-cash-stack"></i> Data Pembelian
                    </div>
                    <div class="form-section-body">
                        <div class="row g-3">

                            <!-- Tanggal Pembelian -->
                            <div class="col-md-6">
                                <label class="field-label">Tanggal Pembelian</label>
                                <div class="input-icon-wrap">
                                    <i class="bi bi-calendar3 icon"></i>
                                    <input type="date" class="form-control" id="tanggal_pembelian" name="tanggal_pembelian"
                                           value="<?= set_value('tanggal_pembelian', $item->tanggal_pembelian) ?>">
                                </div>
                            </div>

                            <!-- Harga -->
                            <div class="col-md-6">
                                <label class="field-label">Harga Pembelian (Rp)</label>
                                <div class="input-icon-wrap">
                                    <span class="icon fw-bold" style="font-size:.8rem; color:#20c997;">Rp</span>
                                    <input type="text" class="form-control" id="harga_pembelian"
                                           name="harga_pembelian" placeholder="0"
                                           onkeyup="formatRupiah(this)"
                                           value="<?= set_value('harga_pembelian', number_format($item->harga_pembelian, 0, ',', '.')) ?>">
                                </div>
                            </div>

                            <!-- Sumber Dana -->
                            <div class="col-md-6">
                                <label class="field-label">Sumber Dana</label>
                                <div class="input-icon-wrap">
                                    <i class="bi bi-wallet2 icon"></i>
                                    <select class="form-select" id="sumber_dana" name="sumber_dana">
                                        <option value="">-- Pilih Sumber Dana --</option>
                                        <?php
                                        $sumber_options = ['APBD','Bantuan Pemerintah','Swadaya Masyarakat','Hibah','lainnya'];
                                        foreach($sumber_options as $opt):
                                            $selected = (set_value('sumber_dana', $item->sumber_dana) == $opt) ? 'selected' : '';
                                        ?>
                                        <option value="<?= $opt ?>" <?= $selected ?>><?= $opt == 'lainnya' ? 'Lainnya' : $opt ?></option>
                                        <?php endforeach; ?>
                                    </select>
                                </div>
                            </div>

                        </div>
                    </div>
                </div>

                <!-- Keterangan -->
                <div class="form-section">
                    <div class="form-section-header">
                        <i class="bi bi-sticky"></i> Keterangan Tambahan
                    </div>
                    <div class="form-section-body">
                        <textarea class="form-control" id="keterangan" name="keterangan" rows="3"
                                  placeholder="Deskripsikan spesifikasi atau catatan penting tentang barang ini..."
                                  style="resize:vertical;"><?= set_value('keterangan', $item->keterangan) ?></textarea>
                    </div>
                </div>

            </div>

            <!-- ===== RIGHT: Media & Tips ===== -->
            <div class="col-lg-4 form-right">

                <!-- Foto Utama -->
                <div class="form-section">
                    <div class="form-section-header">
                        <i class="bi bi-camera"></i> Foto Utama
                    </div>
                    <div class="form-section-body">

                        <!-- Foto existing -->
                        <?php if(!empty($item->foto)): ?>
                        <div class="foto-existing">
                            <img src="<?= base_url('uploads/inventaris/'.$item->foto) ?>"
                                 alt="Foto saat ini" id="current-foto">
                            <span class="badge-existing"><i class="bi bi-check-circle me-1"></i>Foto saat ini</span>
                        </div>
                        <div class="form-check mb-3">
                            <input class="form-check-input" type="checkbox" id="hapus_foto" name="hapus_foto" value="1"
                                   onchange="toggleHapusFoto(this)">
                            <label class="form-check-label text-danger small fw-semibold" for="hapus_foto">
                                <i class="bi bi-trash me-1"></i>Hapus foto ini
                            </label>
                        </div>
                        <?php endif; ?>

                        <!-- Upload foto baru -->
                        <div class="foto-drop" id="fotoDrop">
                            <input type="file" id="foto" name="foto"
                                   accept="image/jpeg,image/png,image/jpg"
                                   onchange="previewFoto(this)">
                            <img id="preview-foto" src="" alt="Preview">
                            <div id="foto-placeholder">
                                <div class="placeholder-icon"><i class="bi bi-image"></i></div>
                                <p class="mb-0 fw-semibold" style="font-size:.85rem; color:#374151;">
                                    <?= !empty($item->foto) ? 'Klik untuk ganti foto' : 'Klik atau seret foto ke sini' ?>
                                </p>
                                <p class="drop-hint mb-0">JPG / PNG · Maks 2MB</p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Gallery Tambahan -->
                <div class="form-section">
                    <div class="form-section-header">
                        <i class="bi bi-images"></i> Gallery Tambahan
                    </div>
                    <div class="form-section-body">

                        <!-- Gallery existing -->
                        <?php if(!empty($gallery)): ?>
                        <p class="small text-muted fw-semibold mb-2">
                            <i class="bi bi-images me-1" style="color:#20c997;"></i>
                            Foto gallery saat ini (<?= count($gallery) ?>)
                        </p>
                        <div style="display:flex; flex-wrap:wrap; gap:8px; margin-bottom:12px;">
                            <?php foreach($gallery as $g): ?>
                            <div class="g-thumb" id="g-<?= $g->id ?>">
                                <img src="<?= base_url('uploads/inventaris/gallery/'.$g->foto) ?>" alt="Gallery">
                                <button type="button" class="rm"
                                        onclick="hapusGallery(<?= $g->id ?>, this)"
                                        title="Hapus foto ini">✕</button>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <!-- Hidden input untuk gallery yang dihapus -->
                        <div id="hapus-gallery-inputs"></div>
                        <?php endif; ?>

                        <div id="gallery-preview"></div>
                        <label class="d-flex align-items-center gap-2 p-3 w-100 justify-content-center"
                               style="border:1.5px dashed #d1fae5; border-radius:10px; cursor:pointer; background:#f0fdf9; font-size:.83rem; color:#374151; font-weight:600;">
                            <i class="bi bi-plus-circle" style="color:#20c997; font-size:1rem;"></i>
                            Tambah Foto Gallery
                            <input type="file" name="gallery[]" id="gallery" multiple
                                   accept="image/jpeg,image/png,image/jpg"
                                   onchange="previewGallery(this)" style="display:none;">
                        </label>
                        <small class="text-muted d-block mt-2" style="font-size:.75rem;">Bisa pilih lebih dari 1 foto sekaligus</small>
                    </div>
                </div>

                <!-- Tips -->
                <div class="tips-box">
                    <div class="tips-title"><i class="bi bi-lightbulb me-1"></i> Tips Edit</div>
                    <ul>
                        <li>Kosongkan field foto jika tidak ingin menggantinya</li>
                        <li>Kode barang harus tetap unik</li>
                        <li>Periksa kembali data sebelum disimpan</li>
                    </ul>
                </div>

            </div>
        </div>

        <!-- Action Bar -->
        <div class="action-bar mt-2">
            <a href="<?= base_url('inventaris/detail/'.$item->id) ?>" class="btn-cancel btn">
                <i class="bi bi-x me-1"></i>Batal
            </a>
            <button type="submit" class="btn-save btn">
                <i class="bi bi-check-circle"></i> Simpan Perubahan
            </button>
        </div>

    </form>
</div>

<script>
// Auto-generate kode
function generateKode() {
    const year = new Date().getFullYear();
    const rand = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    document.getElementById('kode_barang').value = `INV-${year}-${rand}`;
}

// Format rupiah
function formatRupiah(el) {
    let val = el.value.replace(/[^,\d]/g, '');
    let split = val.split(',');
    let sisa = split[0].length % 3;
    let rp = split[0].substr(0, sisa);
    let ribuan = split[0].substr(sisa).match(/\d{3}/gi);
    if (ribuan) {
        rp += (sisa ? '.' : '') + ribuan.join('.');
    }
    el.value = split[1] !== undefined ? rp + ',' + split[1] : rp;
}

// Preview foto utama baru
function previewFoto(input) {
    const preview     = document.getElementById('preview-foto');
    const placeholder = document.getElementById('foto-placeholder');
    const current     = document.getElementById('current-foto');
    if (input.files && input.files[0]) {
        const reader = new FileReader();
        reader.onload = e => {
            preview.src = e.target.result;
            preview.style.display = 'block';
            placeholder.style.display = 'none';
            if (current) current.style.display = 'none'; // sembunyikan foto lama
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// Toggle hapus foto existing
function toggleHapusFoto(cb) {
    const current = document.getElementById('current-foto');
    if (current) {
        current.style.opacity = cb.checked ? '0.3' : '1';
    }
}

// Preview gallery baru
function previewGallery(input) {
    const container = document.getElementById('gallery-preview');
    container.innerHTML = '';
    if (!input.files) return;
    Array.from(input.files).forEach((file) => {
        const reader = new FileReader();
        reader.onload = e => {
            const wrap = document.createElement('div');
            wrap.className = 'g-thumb';
            wrap.innerHTML = `<img src="${e.target.result}"><button type="button" class="rm" onclick="this.parentNode.remove()">✕</button>`;
            container.appendChild(wrap);
        };
        reader.readAsDataURL(file);
    });
}

// Hapus gallery existing (tandai untuk dihapus)
function hapusGallery(id, btn) {
    const thumb = document.getElementById('g-' + id);
    if (thumb) thumb.style.opacity = '0.3';
    btn.disabled = true;

    const container = document.getElementById('hapus-gallery-inputs');
    const input = document.createElement('input');
    input.type  = 'hidden';
    input.name  = 'hapus_gallery[]';
    input.value = id;
    container.appendChild(input);
}

// Form validation
(function() {
    'use strict';
    window.addEventListener('load', function() {
        document.querySelectorAll('.needs-validation').forEach(form => {
            form.addEventListener('submit', e => {
                if (!form.checkValidity()) { e.preventDefault(); e.stopPropagation(); }
                form.classList.add('was-validated');
            });
        });
    });
})();
</script>