<?php $__env->startSection('content'); ?>
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<div class="container-fluid">
    <div class="row">
        <div class="col-md-10 col-md-offset-1">
            <div class="panel panel-default">
                <div class="panel-heading"><center>Receta del Producto: <strong><?php echo e($producto->Nombre_Produc); ?></strong></center></div>
                <div class="panel-body">
                    <a href="<?php echo e(route('insumos.indexReceta')); ?>" class="btn btn-default" style="margin-bottom: 20px;">&larr; Volver al Listado</a>

                    <h4>Ingredientes Actuales</h4>
                    <table class="table table-bordered table-striped">
                        <thead>
                            <tr>
                                <th>Insumo Requerido</th>
                                <th>Cantidad a Descontar</th>
                                <th>Unidad de medida</th>
                                <th>Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $__empty_1 = true; foreach($receta as $ingrediente): $__empty_1 = false; ?>
                                <tr id="receta-row-<?php echo e($ingrediente->idReceta); ?>">
                                    <td><?php echo e($ingrediente->insumo->nombre_insumo); ?></td>
                                    <td>
                                        <input type="number" 
                                               class="form-control input-cantidad" 
                                               value="<?php echo e($ingrediente->cantidad); ?>" 
                                               data-id="<?php echo e($ingrediente->idReceta); ?>" 
                                               step="0.01" min="0.01"
                                               style="width: 100px; display: inline-block;">
                                    </td>
                                    <td><?php echo e($ingrediente->volumen->nombre); ?></td>
                                    <td>
                                        <!-- Botón de Modificar con imagen -->
                                        <button type="button" class="btn btn-xs btn-link btn-guardar-cantidad" data-id="<?php echo e($ingrediente->idReceta); ?>" title="Modificar Cantidad">
                                            <img id="icofor" src="<?php echo e(url('images/Modificar.png')); ?>" width="25" height="20" alt="Modificar"/>
                                        </button>
                                        
                                        <?php echo Form::open(['route' => ['insumos.destroyReceta', $ingrediente->idReceta], 'method' => 'DELETE', 'style' => 'display:inline;', 'id' => 'form-eliminar-'.$ingrediente->idReceta]); ?>

                                            <!-- Botón de Eliminar con imagen -->
                                            <button type="button" class="btn btn-xs btn-link btn-eliminar" data-id="<?php echo e($ingrediente->idReceta); ?>" title="Eliminar Ingrediente">
                                                <img id="icofor" src="<?php echo e(url('images/Eliminar.png')); ?>" width="25" height="20" alt="Eliminar"/>
                                            </button>
                                        <?php echo Form::close(); ?>

                                    </td>
                                </tr>
                            <?php endforeach; if ($__empty_1): ?>
                                <tr>
                                    <td colspan="4" class="text-center">Este producto aún no tiene insumos asignados.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>

                    <hr>

                    <h4>Agregar Nuevo Ingrediente a la Receta</h4>
                    <?php if($errors->any()): ?>
                        <div class="alert alert-danger">
                            <ul>
                                <?php foreach($errors->all() as $error): ?>
                                    <li><?php echo e($error); ?></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    <?php endif; ?>
                    
                    <?php echo Form::open(['route' => 'insumos.storeReceta', 'method' => 'POST', 'class' => 'form-horizontal']); ?>

                        <?php echo Form::hidden('productoId', $producto->idProducto); ?>

                        
                        <div class="form-group">
                            <?php echo Form::label('insumoId', 'Insumo', ['class' => 'col-md-4 control-label']); ?>

                            <div class="col-md-6">
                                <?php echo Form::select('insumoId', ['' => 'Seleccione un insumo...'] + $insumos_para_select->toArray(), null, ['class' => 'form-control', 'required', 'id' => 'insumo_select']); ?>

                            </div>
                        </div>

                        <div class="form-group" id="unidad_display_wrapper" style="display: none;">
                            <label class="col-md-4 control-label">Unidad de Medida</label>
                            <div class="col-md-6">
                                <div class="well well-sm" style="margin-bottom: 0;">
                                    <strong id="unidad_display"></strong>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <?php echo Form::label('cantidad', 'Cantidad a Descontar', ['class' => 'col-md-4 control-label']); ?>

                            <div class="col-md-6">
                                <?php echo Form::number('cantidad', null, ['class' => 'form-control', 'required', 'step' => '0.01', 'min' => '0.01']); ?>

                            </div>
                        </div>

                        <input type="hidden" name="volumenId" id="volumen_id_hidden" value="">

                        <div class="form-group">
                            <div class="col-md-6 col-md-offset-4">
                                <button type="submit" class="btn btn-success">
                                    <i class="fa fa-plus"></i> Agregar Ingrediente
                                </button>
                            </div>
                        </div>
                    <?php echo Form::close(); ?>

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

<script>
    document.addEventListener('DOMContentLoaded', function() {
        // Alerta de éxito (ya existente)
        <?php if(session('alert-success')): ?>
            Swal.fire({
                toast: true, position: 'top-end', icon: 'success',
                title: "<?php echo e(session('alert-success')); ?>",
                showConfirmButton: false, timer: 3000, timerProgressBar: true
            });
        <?php endif; ?>

        // Función para mostrar alerta de SweetAlert2 (toast)
        function showAlert(icon, title) {
            Swal.fire({
                toast: true, position: 'top-end', icon: icon,
                title: title,
                showConfirmButton: false, timer: 3000, timerProgressBar: true
            });
        }

        // ======================================================
        // ||      SCRIPT PARA ELIMINAR CON SweetAlert2        ||
        // ======================================================
        document.querySelectorAll('.btn-eliminar').forEach(button => {
            button.addEventListener('click', function(event) {
                event.preventDefault(); // Evita el envío del formulario por defecto
                const id = this.getAttribute('data-id');
                Swal.fire({
                    title: '¿Estás seguro?',
                    text: "¡El ingrediente será eliminado de la receta! Esta acción es irreversible.",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#3085d6',
                    confirmButtonText: 'Sí, ¡eliminar!',
                    cancelButtonText: 'Cancelar'
                }).then((result) => {
                    if (result.isConfirmed) {
                        document.getElementById('form-eliminar-' + id).submit();
                    }
                });
            });
        });

        // ======================================================
        // ||    SCRIPT PARA GUARDAR CANTIDAD CON SweetAlert2  ||
        // ======================================================
        document.querySelectorAll('.btn-guardar-cantidad').forEach(button => {
            button.addEventListener('click', function() {
                const id = this.getAttribute('data-id');
                const row = document.getElementById(`receta-row-${id}`);
                const input = row.querySelector('.input-cantidad');
                const newCantidad = input.value;
                const originalCantidad = input.dataset.originalValue; // Ya se guardó al cargar

                if (parseFloat(newCantidad) <= 0) {
                    showAlert('error', 'La cantidad debe ser mayor a 0.');
                    input.focus();
                    return;
                }
                
                // Si la cantidad no ha cambiado, no hacemos nada
                if (parseFloat(newCantidad) === parseFloat(originalCantidad)) {
                    showAlert('info', 'La cantidad no ha cambiado.');
                    return;
                }

                Swal.fire({
                    title: '¿Confirmar Modificación?',
                    text: `¿Deseas cambiar la cantidad a ${newCantidad}?`,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonColor: '#3085d6',
                    cancelButtonColor: '#d33',
                    confirmButtonText: 'Sí, ¡guardar!',
                    cancelButtonText: 'Cancelar'
                }).then((result) => {
                    if (result.isConfirmed) {
                        // AJAX request solo si el usuario confirma
                        fetch(`/insumos/receta/update-cantidad/${id}`, { 
                            method: 'PUT',
                            headers: {
                                'Content-Type': 'application/json',
                                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>' 
                            },
                            body: JSON.stringify({ cantidad: newCantidad })
                        })
                        .then(response => {
                            if (!response.ok) {
                                return response.json().then(err => { throw new Error(err.message || 'Error al actualizar la cantidad.'); });
                            }
                            return response.json();
                        })
                        .then(data => {
                            if (data.success) {
                                input.dataset.originalValue = newCantidad; // Actualizar el valor original
                                showAlert('success', 'Cantidad actualizada correctamente.');
                            } else {
                                showAlert('error', data.message || 'Error al actualizar la cantidad.');
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            showAlert('error', 'Hubo un problema al conectar con el servidor.');
                        });
                    }
                });
            });
        });

        // Guardar el valor original al cargar la página para cada input de cantidad
        document.querySelectorAll('.input-cantidad').forEach(input => {
            input.dataset.originalValue = input.value;

            // Opcional: Permitir guardar al presionar Enter en el input de cantidad
            input.addEventListener('keypress', function(event) {
                if (event.key === 'Enter') {
                    event.preventDefault(); 
                    const id = this.getAttribute('data-id');
                    const saveButton = document.getElementById(`receta-row-${id}`).querySelector('.btn-guardar-cantidad');
                    saveButton.click(); // Simula un click en el botón Guardar
                }
            });
        });
    });
</script>

<script>
    <?php
        $insumosParaJs = [];
        foreach ($insumos_con_data as $insumo) {
            $insumosParaJs[$insumo->idInsumo] = [
                'volumenId' => $insumo->volumen ? $insumo->volumen->idVolumen : null,
                'volumenNombre' => $insumo->volumen ? $insumo->volumen->nombre : 'N/A'
            ];
        }
    ?>
    const insumosData = <?php echo json_encode($insumosParaJs); ?>;

    document.addEventListener('DOMContentLoaded', function() {
        const insumoSelect = document.getElementById('insumo_select');
        const unidadWrapper = document.getElementById('unidad_display_wrapper');
        const unidadDisplay = document.getElementById('unidad_display');
        const volumenHiddenInput = document.getElementById('volumen_id_hidden');

        insumoSelect.addEventListener('change', function() {
            const selectedInsumoId = this.value;
            if (!selectedInsumoId) {
                unidadWrapper.style.display = 'none';
                volumenHiddenInput.value = '';
                return;
            }
            const insumoInfo = insumosData[selectedInsumoId];
            if (insumoInfo && insumoInfo.volumenId) {
                unidadDisplay.textContent = insumoInfo.volumenNombre;
                volumenHiddenInput.value = insumoInfo.volumenId;
                unidadWrapper.style.display = 'block';
            } else {
                unidadWrapper.style.display = 'none';
                volumenHiddenInput.value = '';
            }
        });
    });
</script>
<?php $__env->stopSection(); ?>
<?php echo $__env->make('app', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>