<?= $this->extend('layouts/main_layout') ?>
<?= $this->section('content') ?>

<div class="flex items-center justify-between mb-6">
    <h2 class="text-2xl font-bold text-gray-900 flex items-center gap-2"><i class="bi bi-pencil-square text-2xl"></i> Editar Producto</h2>
    <a href="<?= site_url('products') ?>" class="bg-[#EBDF00]/20 border border-gray-200 rounded-lg px-4 py-2.5 text-sm transition hover:bg-gray-50 no-underline inline-flex items-center gap-2 text-gray-600">
        <i class="bi bi-arrow-left"></i> Volver
    </a>
</div>

<form method="post" action="<?= site_url('products/' . $product['id_producto']) ?>" enctype="multipart/form-data">
    <?= csrf_field() ?>
    <input type="hidden" name="_method" value="POST">
    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <div class="lg:col-span-2 bg-[#EBDF00]/20 rounded-xl shadow-sm border border-gray-100">
            <div class="border-b border-gray-100 px-6 py-4">
                <h5 class="font-semibold text-gray-900 flex items-center gap-2 text-sm"><i class="bi bi-info-circle text-gray-400"></i> Datos del Producto</h5>
            </div>
            <div class="p-6">
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label for="nombre" class="block text-sm font-medium text-gray-500 mb-1">Nombre del Producto *</label>
                        <input type="text" name="nombre" id="nombre" class="w-full bg-[#EBDF00]/20 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#EBDF00] focus:border-[#D4C800] text-gray-700" value="<?= old('nombre', $product['nombre']) ?>" required>
                    </div>
                    <div>
                        <label for="codigo_unico" class="block text-sm font-medium text-gray-500 mb-1">Codigo Unico *</label>
                        <input type="text" name="codigo_unico" id="codigo_unico" class="w-full bg-[#EBDF00]/20 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#EBDF00] focus:border-[#D4C800] text-gray-700" value="<?= old('codigo_unico', $product['codigo_unico']) ?>" required>
                    </div>
                    <div>
                        <label for="id_categoria" class="block text-sm font-medium text-gray-500 mb-1">Categoria *</label>
                        <div class="flex gap-2">
                            <select name="id_categoria" id="id_categoria" class="flex-1 bg-[#EBDF00]/20 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#EBDF00] focus:border-[#D4C800] text-gray-700" required>
                                <option value="">Seleccione...</option>
                                <?php foreach ($categories as $cat): ?>
                                <option value="<?= $cat['id_categoria'] ?>" <?= (old('id_categoria', $product['id_categoria']) == $cat['id_categoria']) ? 'selected' : '' ?>>
                                    <?= esc($cat['nombre']) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                            <button type="button" onclick="openCategoryModal()" class="bg-[#EBDF00] hover:bg-[#D4C800] text-gray-900 px-3 py-2 rounded-lg text-sm shadow-sm transition" title="Agregar categoria">
                                <i class="bi bi-plus-lg"></i>
                            </button>
                        </div>
                    </div>
                    <div class="md:col-span-2 grid grid-cols-2 md:grid-cols-4 gap-4">
                        <div>
                            <label for="precio_compra" class="block text-sm font-medium text-gray-500 mb-1">P. Compra *</label>
                            <div class="flex items-center bg-[#EBDF00]/20 border border-gray-200 rounded-lg overflow-hidden">
                                <span class="px-3 bg-gray-50 text-gray-400 text-sm border-r border-gray-200">S/</span>
                                <input type="number" step="0.01" name="precio_compra" id="precio_compra" class="w-full py-2.5 px-2 text-sm outline-none text-gray-700" value="<?= old('precio_compra', $product['precio_compra']) ?>" min="0" required>
                            </div>
                        </div>
                        <div>
                            <label for="precio_venta" class="block text-sm font-medium text-gray-500 mb-1">P. Venta *</label>
                            <div class="flex items-center bg-[#EBDF00]/20 border border-gray-200 rounded-lg overflow-hidden">
                                <span class="px-3 bg-gray-50 text-gray-400 text-sm border-r border-gray-200">S/</span>
                                <input type="number" step="0.01" name="precio_venta" id="precio_venta" class="w-full py-2.5 px-2 text-sm outline-none text-gray-700" value="<?= old('precio_venta', $product['precio_venta']) ?>" min="0" required>
                            </div>
                        </div>
                        <div>
                            <label for="stock_actual" class="block text-sm font-medium text-gray-500 mb-1">Stock *</label>
                            <input type="number" name="stock_actual" id="stock_actual" class="w-full bg-[#EBDF00]/20 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#EBDF00] focus:border-[#D4C800] text-gray-700" value="<?= old('stock_actual', $product['stock_actual']) ?>" min="0" required>
                        </div>
                        <div>
                            <label for="unidad_medida" class="block text-sm font-medium text-gray-500 mb-1">Unidad *</label>
                            <select name="unidad_medida" id="unidad_medida" class="w-full bg-[#EBDF00]/20 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#EBDF00] focus:border-[#D4C800] text-gray-700" required>
                                <option value="">...</option>
                                <option value="UNIDAD" <?= (old('unidad_medida', $product['unidad_medida']) == 'UNIDAD') ? 'selected' : '' ?>>Unidad</option>
                                <option value="CAJA" <?= (old('unidad_medida', $product['unidad_medida']) == 'CAJA') ? 'selected' : '' ?>>Caja</option>
                                <option value="PAQUETE" <?= (old('unidad_medida', $product['unidad_medida']) == 'PAQUETE') ? 'selected' : '' ?>>Paquete</option>
                                <option value="KILO" <?= (old('unidad_medida', $product['unidad_medida']) == 'KILO') ? 'selected' : '' ?>>Kilo</option>
                                <option value="LITRO" <?= (old('unidad_medida', $product['unidad_medida']) == 'LITRO') ? 'selected' : '' ?>>Litro</option>
                                <option value="METRO" <?= (old('unidad_medida', $product['unidad_medida']) == 'METRO') ? 'selected' : '' ?>>Metro</option>
                            </select>
                        </div>
                    </div>
                </div>
            </div>
        </div>
<div class="bg-[#EBDF00]/20 rounded-xl shadow-sm border border-gray-100">



        
            <div class="border-b border-gray-100 px-6 py-4">
                <h5 class="font-semibold text-gray-900 flex items-center gap-2 text-sm"><i class="bi bi-image text-gray-400"></i> Imagen del Producto</h5>
            </div>
            <div class="p-6 flex flex-col items-center justify-center">
                <div id="previewContainer" class="w-full aspect-square max-h-56 rounded-xl border-2 border-dashed border-gray-200 bg-gray-50 flex items-center justify-center overflow-hidden mb-3">
                    <?php if (!empty($product['imagen'])): ?>
                    <img id="previewImg" src="<?= base_url('uploads/products/' . $product['imagen']) ?>" alt="Imagen actual" class="w-full h-full object-contain">
                    <span id="placeholderIcon" class="text-gray-300 hidden"><i class="bi bi-box-seam text-4xl"></i></span>
                    <?php else: ?>
                    <img id="previewImg" src="#" alt="Vista previa" class="w-full h-full object-contain hidden">
                    <span id="placeholderIcon" class="text-gray-300"><i class="bi bi-box-seam text-4xl"></i></span>
                    <?php endif; ?>
                </div>
                <input type="file" name="imagen" id="imagen" class="w-full text-sm text-gray-600 file:mr-3 file:py-1.5 file:px-3 file:bg-[#EBDF00]/20 file:border file:border-gray-200 file:rounded-lg file:text-sm file:font-medium file:text-gray-700 hover:file:bg-gray-50" accept="image/*" onchange="previewImage(event)">
                <p class="text-xs text-gray-400 mt-2">Formatos: JPG, PNG, GIF</p>
            </div>
        </div>
    </div>
    <div class="flex justify-end gap-3 mt-6">
        <a href="<?= site_url('products') ?>" class="bg-[#EBDF00]/20 border border-gray-200 rounded-lg px-5 py-2.5 text-sm font-medium transition hover:bg-gray-50 no-underline text-gray-600">Cancelar</a>
        <button type="submit" class="bg-[#EBDF00] hover:bg-[#D4C800] text-gray-900 px-5 py-2.5 rounded-lg text-sm font-medium inline-flex items-center gap-2 shadow-sm transition">
            <i class="bi bi-save"></i> Actualizar Producto
        </button>
    </div>
</form>

<div id="categoryModal" class="fixed inset-0 bg-black/40 hidden items-center justify-center z-50" style="display:none" onclick="closeCategoryModal(event)">
    <div class="bg-[#EBDF00]/20 rounded-xl shadow-sm p-6 w-full max-w-sm mx-4 border border-gray-100" onclick="event.stopPropagation()">
        <h3 class="text-lg font-semibold text-gray-900 mb-4 flex items-center gap-2"><i class="bi bi-plus-circle text-emerald-500"></i> Nueva Categoria</h3>
        <form hx-post="<?= site_url('categories/save') ?>" hx-swap="none">
            <?= csrf_field() ?>
            <label class="block text-sm font-medium text-gray-500 mb-1">Nombre de la categoria</label>
            <input type="text" name="nombre" id="newCategoryName" class="w-full bg-[#EBDF00]/20 border border-gray-200 rounded-lg px-4 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-[#EBDF00] focus:border-[#D4C800] text-gray-700" placeholder="Ej: Lacteos">
            <div class="flex justify-end gap-2 mt-4">
                <button type="button" onclick="closeCategoryModal()" class="bg-[#EBDF00]/20 border border-gray-200 rounded-lg px-4 py-2 text-sm font-medium transition hover:bg-gray-50 text-gray-600">Cancelar</button>
                <button type="submit" class="bg-[#EBDF00] hover:bg-[#D4C800] text-gray-900 px-4 py-2 rounded-lg text-sm font-medium inline-flex items-center gap-1 shadow-sm transition">
                    <i class="bi bi-check-lg"></i> Guardar
                </button>
            </div>
        </form>
    </div>
</div>

<script>
function previewImage(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('previewImg').src = e.target.result;
            document.getElementById('previewImg').classList.remove('hidden');
            document.getElementById('placeholderIcon').classList.add('hidden');
        }
        reader.readAsDataURL(file);
    }
}
function openCategoryModal() {
    document.getElementById('categoryModal').style.display = 'flex';
    document.getElementById('newCategoryName').value = '';
    document.getElementById('newCategoryName').focus();
}
function closeCategoryModal(e) {
    if (e && e.target !== e.currentTarget) return;
    document.getElementById('categoryModal').style.display = 'none';
}
document.body.addEventListener('categorySaved', function(e) {
    const data = e.detail;
    const select = document.getElementById('id_categoria');
    const opt = document.createElement('option');
    opt.value = data.id;
    opt.textContent = data.nombre;
    opt.selected = true;
    select.appendChild(opt);
    closeCategoryModal();
});
document.body.addEventListener('categoryError', function(e) {
    alert(e.detail);
});
document.body.addEventListener('htmx:sendError', function() {
    alert('Error de conexion');
});
</script>

<?= $this->endSection() ?>