<?php $__env->startSection('content'); ?>
<script src="<?php echo e(url('js/Productos.js')); ?>"></script>
<div class="container-fluid">
    <div class="row">
		<div class="col-md-8 col-md-offset-2">
			<div class="panel panel-default">
                <div class="panel-heading"><center>Venta</center></div>
                    <div class="panel-body">
                        <?php /* Navbar original */ ?>
                        <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                            <ul class="nav navbar-nav navbar-right">
                                <!-- ... -->
                            </ul>
                        </div>

                        <?php /* TUS ALERTAS ORIGINALES */ ?>
                        <?php if(count($errors) > 0): ?>
                            <div class="alert alert-danger">
                                <strong>Whoops!</strong> Hay algunos problemas!!!.<br><br>
                                <ul>
                                    <?php foreach($errors->all() as $error): ?>
                                        <li><?php echo e($error); ?></li>
                                    <?php endforeach; ?>
                                </ul>
                            </div>
                        <?php endif; ?>
                        <?php /* La alerta Session::get('alert-success') se mostrará también para inventario */ ?>
                        <?php if($alert_session_success = Session::get('alert-success')): ?>
                            <div class="alert alert-success">
                                <?php echo $alert_session_success; ?>

                            </div>
                        <?php endif; ?>
                        <?php /* NUEVAS ALERTAS PARA INVENTARIO (Y OTRAS DE ERROR/INFO GENERAL) */ ?>
                        <?php if(isset($alertaInventario) && $alertaInventario): ?>
                            <div class="alert alert-warning text-center">
                                <strong>¡Atención!</strong> <?php echo e($alertaInventario); ?>

                            </div>
                        <?php endif; ?>
                        <?php if(Session::has('alert-danger')): ?>
                            <div class="alert alert-danger">
                                <?php echo Session::get('alert-danger'); ?>

                            </div>
                        <?php endif; ?>
                         <?php if(Session::has('alert-info')): ?>
                            <div class="alert alert-info">
                                <?php echo Session::get('alert-info'); ?>

                            </div>
                        <?php endif; ?>

                        <?php if(session('confirmar_reabrir_caja')): ?>
                            <div class="alert alert-warning">
                                La caja ya estuvo abierta por usted. ¿Desea abrirla nuevamente?
                                <form method="POST" action="<?php echo e(url('/abrir')); ?>">
                                    @csrf
                                    <input type="hidden" name="Nombre" value="<?php echo e(old('Nombre')); ?>">
                                    <input type="hidden" name="email" value="<?php echo e(old('email')); ?>">
                                    <input type="hidden" name="password" value="<?php echo e(old('password')); ?>">
                                    <input type="hidden" name="saldo" value="<?php echo e(old('saldo')); ?>">
                                    <button type="submit" class="btn btn-primary">Sí, abrir nuevamente</button>
                                    <a href="<?php echo e(url('/factura')); ?>" class="btn btn-secondary">No</a>
                                </form>
                            </div>
                        <?php endif; ?>


                        <div class="form-horizontal">
                        <?php /* El action de este form debe ser /factura para que lo maneje postfactura */ ?>
                        <?php echo Form::open(array('url' =>'/factura', 'method'=>'POST','role'=>'form','id'=>'regForm','name'=>'regForm')); ?>

                        <?php echo Form::token(); ?>

                            <div class="form-group" hidden="">
                                <div class="col-md-4 control-label">
                                    <?php echo Form::label('idfactura','Numero Venta'); ?>

                                </div>
                                <div class="col-md-6">
                                    <?php echo Form::text('idfactura',$venta,array('class'=>'form-control','readonly')); ?>

							    </div>
						    </div>
                            

                            <?php /* SECCIÓN DESHABILITABLE POR INVENTARIO */ ?>
                            <div <?php if(!$puedeOperar): ?> style="opacity:0.5; pointer-events:none;" title="Abra el inventario para operar" <?php endif; ?>>
                                <div class="form-group">
                                    <div class="col-md-4 control-label">
                                        <?php echo Form::label('cliente','Cliente'); ?>

                                    </div>
                                    <div class="col-md-6">
                                        <?php echo Form::number('cliente', (isset($datos[0]) && isset($datos[0]['Cliente'])) ? $datos[0]['Cliente'] : null, array('class'=>'form-control')); ?>

                                    </div>
                                    <center><div class="col-md-12" id="clientes"></div></center>
						        </div>
                                <div class="form-group">
                                    <div class="col-md-4 control-label">
                                        <?php echo Form::label('producto','Producto'); ?>

                                    </div>
                                    <div class="col-md-6">
                                        <?php echo Form::text('producto',@old('producto'),array('class'=>'form-control','id'=>'producto')); ?>

                                    </div>
                                    <center> <div class="col-md-12" id="productos"></div></center>
                                </div>
                                <div class="form-group">
                                    <div class="col-md-4 control-label">
                                        <?php echo Form::label('cantidad','Cantidad'); ?>

                                    </div>
                                    <div class="col-md-6">
                                        <?php echo Form::number('cantidad',@old('cantidad'),array('class'=>'form-control','id'=>'cantidad',)); ?>

                                    </div>
                                </div>
                            </div>
                            <?php /* FIN SECCIÓN DESHABILITABLE */ ?>

                            <div class="form-group">
                                <div id="botones-inventario"><center>
                                    <?php if(isset($inventarioAbiertoUsuario) && $inventarioAbiertoUsuario && Auth::check() && $inventarioAbiertoUsuario->id_usuario == Auth::user()->idUsuario): ?>
                                    <?php echo Form::submit('Agregar',array('name'=>'Agregar','id'=>'Agregar','class'=>'btn btn-primary')); ?>

                                    <?php else: ?>
                                    <button type="button" class="btn btn-primary" disabled title="Por favor abrir inventario para agregar productos.">
                                        Agregar
                                    </button>
                                    <?php endif; ?>
                                    <?php /* NUEVOS BOTONES DE ABRIR/CERRAR INVENTARIO */ ?>
                                    <?php if(isset($inventarioAbiertoUsuario) && $inventarioAbiertoUsuario && Auth::check() && $inventarioAbiertoUsuario->id_usuario == Auth::user()->idUsuario): ?>
                                        <?php echo Form::submit('Cerrar Inventario', ['name'=>'accion', 'id'=>'CerrarInventario', 'class'=>'btn btn-danger']); ?>

                                    <?php elseif(Auth::check() && !App\Models\EstadoInventario::hayInventarioGlobalAbierto() && Session::has('caja')): ?>
                                        <?php if($inventarioCerradoDefinitivo): ?>
                                            <button type="button" class="btn btn-success" disabled title="El ciclo ya está cerrado definitivamente.">
                                                Abrir Inventario
                                            </button>
                                        <?php else: ?>
                                            <?php echo Form::submit('Abrir Inventario', ['name'=>'accion', 'id'=>'AbrirInventario', 'class'=>'btn btn-success']); ?>

                                        <?php endif; ?>
                                    <?php else: ?>
                                        <button type="button" class="btn btn-default" disabled title="<?php echo e((isset($alertaInventario) && $alertaInventario) ? $alertaInventario : 'Debe tener una sesión de caja activa para abrir inventario.'); ?>">
                                            <?php echo e(App\Models\EstadoInventario::hayInventarioGlobalAbierto() ? 'Inventario Ocupado' : 'Abrir Inventario'); ?>

                                        </button>
                                    <?php endif; ?>
                                    <?php /* FIN NUEVOS BOTONES */ ?>

                                    <a href="<?php echo e(route('cargarPedido', ['idPedido' => 0])); ?>" class="btn btn-warning position-relative" id="btn-pendientes" <?php if(!$puedeOperar): ?> style="pointer-events: none; opacity:0.5;" <?php endif; ?>>
                                        Pendientes por facturar
                                        <span id="badge-pedidos" class="badge badge-danger" style="top: -1px; right: -9px; font-size: 12px; background-color: red; color: white; padding: 3px 6px; border-radius: 50%; display: none;">
                                            0
                                        </span>
                                    </a>
                                </center></div>
						    </div>
                        <?php echo Form::close(); ?> <?php /* Cierre del primer form (regForm) */ ?>

                        <?php /* SECCIÓN DESHABILITABLE POR INVENTARIO */ ?>
                        <div <?php if(!$puedeOperar): ?> style="opacity:0.5; pointer-events:none;" title="Abra el inventario para operar" <?php endif; ?>>
                            <table class="table" border="0" WIDTH=100%>
                                <tr>
                                    <th width="20%">Id Producto/Combo</th>
                                    <th width="25%">Producto</th>
                                    <th width="10%">Cantidad</th>
                                    <th width="17%">V. Unidad</th>
                                    <th width="20%">V. Total</th>
                                    <th width="20%">Descuento</th>
                                    <th></th>
                                    <th></th>
                                </tr>
                                <?php if(isset($datos) && is_array($datos) && !empty($datos[0])): ?>
                                    <?php foreach($datos as $mostrar): ?>
                                        <?php if($mostrar): ?>
                                            <?php echo Form::open(array('url' =>'em', 
                                                                'method'=>'POST',
                                                                'role'=>'form',
                                                                'class' => 'form-eliminar-item',
                                                                //'onsubmit' => 'return confirmarEliminacion(this)',
                                                                'class' => 'form-eliminar-item',
                                                                'data-pedido-id' => $mostrar['pedido_id'] ?? '',
                                                                // 'id'=>'regFormm_'.($mostrar['idproducto'] > 0 ? $mostrar['idproducto'] : $mostrar['idcombo']) ,
                                                                'id'=>'regFormm_'.$mostrar['id_table'],
                                                                'name'=>'regFormm')); ?>

                                            <?php echo Form::token(); ?> 
                                            <tr>
                                                <td><?php echo e($mostrar['idproducto'] > 0 ? $mostrar['idproducto'] : $mostrar['idcombo']); ?></td>
                                                <td><?php echo e($mostrar['Producto']); ?></td>
                                                <td><?php echo Form::number('cantidad1',$mostrar['Cantidad'],array('class'=>'form-control','id'=>'cantidad1_'.($mostrar['idproducto'] > 0 ? $mostrar['idproducto'] : $mostrar['idcombo']))); ?></td>
                                                <?php echo Form::hidden('cantidada',$mostrar['Cantidad'],array('class'=>'form-control')); ?>

                                                <td><?php echo e(($mostrar['Valor_unidad']+$mostrar['iva'])); ?></td>
                                                <td><?php echo e($mostrar['Valor_Total']); ?></td>
                                                <td><?php echo Form::number('descpa',$mostrar['descuento'],array('class'=>'form-control','id'=>'descpa_'.($mostrar['idproducto'] > 0 ? $mostrar['idproducto'] : $mostrar['idcombo']),'required')); ?></td>
                                                <td>
                                                    <input type="hidden" name="aid" value="<?php echo e($mostrar['idproducto'] > 0 ? $mostrar['idproducto'] : $mostrar['idcombo']); ?>"/>
                                                    <input type="hidden" name="id_table" value="<?php echo e($mostrar['id_table']); ?>">
                                                    <input type="hidden" name="item_type" value="<?php echo e($mostrar['idproducto'] > 0 ? 'producto' : 'combo'); ?>"/>
                                                    <button class="btn btn-xs btn-link" name="em"  value="Eliminar" type="submit" title="Eliminar"><img id="icofor" src="<?php echo e(url('images/Eliminar.png')); ?>" width="25" height="20" alt="Submit"/></button>
                                                </td>
                                                <td><button class="btn  btn-xs btn-link" name="em"  value="Modificar" type="submit" title="Modificar"><img id="icofor" src="<?php echo e(url('images/Modificar.png')); ?>" width="25" height="20" alt="Submit"/></button></td>
                                            </tr>
                                            <?php echo Form::close(); ?>

                                        <?php endif; ?>
                                    <?php endforeach; ?>
                                <?php endif; ?>
          

                            <?php /* Este formulario va a /factura (antes iba a /recibo) */ ?>
                            <?php echo Form::open(array('url' =>'/recibo', 'method'=>'POST','role'=>'form','id'=>'regFormv','name'=>'regFormv')); ?>

                            <?php echo Form::token(); ?>

          
                                <tr>
                                <?php foreach($valor as $valor): ?>
                                    <td colspan="4" align="right"><?php echo Form::label('stotal','Sub-Total'); ?></td>                                                          
                                    <td><?php echo Form::text('stotal',$valor->total,array('class'=>'form-control','id'=>'stotal','readonly')); ?></td>
                                <?php endforeach; ?>
                            </tr>
                            <tr>
                                <?php foreach($dest as $dest): ?>
                                    <?php
                                        //$sl="";
                                        $sl="readonly";
                                        $obl="";
                                        if(($dest->tdesc)>0){
                                            $sl="readonly";
                                            $obl="required";
                                        }
                                    ?>
                                    <td colspan="4" align="right">&nbsp;&nbsp;<?php echo Form::label('descuento','Descuento'); ?></td>
                                    <td><?php echo Form::number('vdescu',$dest->tdesc,array('class'=>'form-control','id'=>'vdescu',$sl,'onkeyup'=>'descuento()')); ?></td>
                                <?php endforeach; ?>
                            </tr>
                            <tr>
                                <td colspan="4" align="right"><?php echo Form::label('total','Total'); ?></td>                                                          
                                <td><?php echo Form::text('total',($valor->total-$dest->tdesc),array('class'=>'form-control','id'=>'total','readonly')); ?></td>
                            </tr>
                            <tr>
                                <td colspan="4" align="right"> <?php echo Form::label('efectivo','Efectivo'); ?></td> 
                                <td><?php echo Form::number('efectivo',@old('efectivo'),array('class'=>'form-control','id'=>'efectivo','onkeyup'=>'efectivos()')); ?></td>
                            </tr>
                            <tr>
                                <td colspan="4" align="right"> <?php echo Form::label('cambio','Cambio'); ?></td> 
                                <td><?php echo Form::text('cambio',@old('cambio'),array('class'=>'form-control','id'=>'cambio','readonly')); ?></td>
                            </tr>
                            <tr>
                                <td colspan="4" align="right"><?php echo Form::label('formapago','Forma de Pago'); ?></td>
                                <td><?php echo Form::select('formapago',@$formapago,@old('formapago'),array('class'=>'form-control','id'=>'formapago','onchange'=>'vptos()')); ?></td>
                            </tr>                                                    
                            <tr>
                                <td colspan="2" align="right"> <?php echo Form::label('Obs','Observaci&oacute;n (Descuento):'); ?></td> 
                                <td colspan="6"><?php echo Form::text('obsdes',@old('cambio'),array('class'=>'form-control','id'=>'obsdes','maxlength'=>'250',$obl)); ?></td>
                            </tr>
                            <tr>
                                <td colspan="2" align="right"> <?php echo Form::label('Obspt','Observaci&oacute;n (Tarj./Ptos./Créd.):'); ?></td> 
                                <td colspan="6"><?php echo Form::text('obspt',@old('cambio'),array('class'=>'form-control','id'=>'obspt','maxlength'=>'250')); ?></td>
                            </tr>
                            </table>
                            <div class="form-group">
                                <div><center>
                                    <?php echo Form::submit('Generar Venta',array('name'=>'Venta','id'=>'Venta','class'=>'btn btn-primary')); ?>

                                </center></div>
                            </div>
                            <?php echo Form::close(); ?> <?php /* Cierre del segundo form (regFormv) */ ?>
                        </div><?php /* FIN SECCIÓN DESHABILITABLE */ ?>
				</div>
			</div>
		</div>
	</div>
</div>
<?php $__env->stopSection(); ?>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<?php /* REEMPLAZA TU SCRIPT ANTERIOR POR ESTE CÓDIGO */ ?>
<script>
$(document).ready(function() {
    // Escuchar el evento 'submit' en todos los formularios con la clase '.form-eliminar-item'
    $('body').on('submit', '.form-eliminar-item', function(e) {
        
        // Identificamos qué botón se presionó para enviar el formulario
        const botonPresionado = $(document.activeElement);
        const accion = botonPresionado.attr('value'); // Será "Eliminar" o "Modificar"
        
        // Obtenemos los datos del formulario
        const formElement = this;
        const pedidoId = formElement.dataset.pedidoId;
        
        let mensaje = '';
        
        // --- LÓGICA PARA CONSTRUIR EL MENSAJE CORRECTO ---
        
        if (accion === 'Eliminar') {
            if (pedidoId && pedidoId !== '') {
                // Caso 1: Eliminar ítem de un pedido
                mensaje = `Este producto pertenece al Pedido #${pedidoId}. Si lo elimina, se quitarán TODOS los productos de este pedido de la venta actual. ¿Desea continuar?`;
            } else {
                // Caso 2: Eliminar ítem manual
                mensaje = '¿Está seguro de que desea eliminar este ítem?';
            }
        } 
        else if (accion === 'Modificar') {
            if (pedidoId && pedidoId !== '') {
                // Caso 3: Modificar ítem de un pedido
                mensaje = `Este producto pertenece al Pedido #${pedidoId}. ¿Desea editarlo?`;
            } else {
                // Caso 4: Modificar ítem manual
                mensaje = '¿Desea editar este producto?';
            }
        }

        // --- MOSTRAR LA CONFIRMACIÓN ---
        
        // Si no se generó un mensaje, no hacemos nada y dejamos que el formulario se envíe.
        // Pero en este caso, siempre se generará uno.
        if (mensaje) {
            // Mostramos la ventana de confirmación con el mensaje correcto.
            // Si el usuario presiona "Cancelar" (que devuelve 'false'), prevenimos el envío.
            if (!confirm(mensaje)) {
                e.preventDefault(); // Detiene la acción de envío del formulario
            }
        }
    });
});
</script>
<?php if($puedeOperar): ?>
<script>
    function verificarPedidosNuevos() {
        $.ajax({
            url: '<?php echo e(url("/verificar-nuevos-pedidos")); ?>',
            method: 'GET',
            success: function(response) {
                if (response.nuevos > 0) {
                    mostrarNotificacion(response.nuevos);
                }
            }
        });
    }

    function mostrarNotificacion(cantidad) {
    let alerta = $('#alerta-pedidos');
    let badge = $('#badge-pedidos');

    if (cantidad > 0) {
        if (alerta.length === 0) {
            $('body').prepend(`
                <div id="alerta-pedidos" class="alert alert-info text-center" style="position: fixed; top: 0; width: 35%; z-index: 9999;">
                    📦 ¡Hay ${cantidad} pedidos nuevos pendientes!
                    <a href="<?php echo e(route('cargarPedido', ['idPedido' => 0])); ?>" class="btn btn-sm btn-warning">Ver</a>
                </div>
            `);
        } else {
            alerta.html(`📦 ¡Hay ${cantidad} pedidos nuevos pendientes!
                <a href="<?php echo e(route('cargarPedido', ['idPedido' => 0])); ?>" class="btn btn-sm btn-warning">Ver</a>`);
        }
        badge.text(cantidad);
        badge.show();
    } else {
        alerta.remove();
        badge.hide();
    }
}
    setInterval(verificarPedidosNuevos, 6000);
</script>
<?php endif; ?>

<script>
    $(document).ready(function() {
        $('#regForm').on('submit', function(e) {
            var botonPresionado = $(document.activeElement);
            if (botonPresionado.is('#AbrirInventario')) {
                if (!confirm('¿Desea abrir el inventario?')) {
                    e.preventDefault();
                }
            }
            else if (botonPresionado.is('#CerrarInventario')) {
                if (!confirm('¿Desea cerrar el inventario?')) {
                    e.preventDefault(); 
                }
            }
        });
    });
</script>
<script>
    setInterval(() => {
    $("#botones-inventario").load(window.location.href + " #botones-inventario>*");
}, 10000);
</script>
<?php echo $__env->make('app', array_except(get_defined_vars(), array('__data', '__path')))->render(); ?>