<?php $__env->startSection('content'); ?>
<?php
    $hoy = now()->format('d-m-Y');
    $estado = '';
    $totalesEgreso = $cajaegreso->filter(function ($item) {
        return $item->estado !== 'AN';
    });
    $totalSoles = $totalesEgreso->sum('monto');
    $totalDolares = $totalesEgreso->sum('monto_dolar');
?>

<style>
    .inputcentrado {
        text-align: center;
        font-weight: bold;
        font-size: 22px;
    }

    thead th {
        text-align: center;
    }

    .panel {
        background: #fff;
        border: 1px solid #d9dee3;
        border-radius: 6px;
        margin-bottom: 20px;
        overflow: hidden;
    }

    .panel-primary {
        border-color: #7a2e2e;
    }

    .panel-primary > .panel-heading {
        background: #7a2e2e;
        color: #fff;
        padding: 12px 15px;
        font-weight: 700;
        font-size: 15px;
    }

    .panel-body {
        padding: 18px;
    }

    .separador {
        border: 0;
        border-top: 1px solid #e5e5e5;
        margin: 18px 0;
    }

    .btn-accion {
        min-width: 34px;
    }

    .fila-anulada,
    .fila-anulada td,
    .fila-anulada a,
    .fila-anulada i {
        color: #dc3545 !important;
    }
</style>

<?php if($errors->any()): ?>
    <div class="alert alert-danger mt-3">
        <strong>Se encontraron errores:</strong>
        <ul class="mb-0 mt-2 ps-3">
            <?php $__currentLoopData = $errors->all(); $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $error): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                <li><?php echo e($error); ?></li>
            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
        </ul>
    </div>
<?php endif; ?>

<?php if(session('pdf_link')): ?>
    <div class="alert alert-success mt-3">
        <a href="<?php echo e(session('pdf_link')); ?>" target="_blank">
            Ver comprobante generado: <?php echo e(session('pdf_filename') ?? 'COMPROBANTE.PDF'); ?>

        </a>
    </div>
<?php endif; ?>

<?php if($estadocaja == 'ABIERTO'): ?>
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-lg-8">
                <div class="panel panel-primary shadow-sm">
                    <div class="panel-heading">CAJA EGRESO</div>

                    <div class="panel-body">
                        <form action="<?php echo e(route('admin.egreso.store')); ?>" method="POST" class="form-horizontal" onsubmit="return checkSubmit();">
                            <?php echo csrf_field(); ?>

                            <div class="row g-2">
                                <div class="col-md-3">
                                    <label for="fecha_movimiento" class="form-label">FECHA</label>
                                    <input readonly class="form-control inputcentrado" id="fecha_movimiento" name="fecha_movimiento" type="text" value="<?php echo e($hoy); ?>">
                                    <input type="hidden" id="fecha_hora_cliente" name="fecha_hora_cliente" value="">
                                </div>

                                <div class="col-md-3">
                                    <label for="serie" class="form-label">SERIE</label>
                                    <input readonly class="form-control inputcentrado" id="serie" name="serie" type="text" value="<?php echo e($serie); ?>" style="color:red;">
                                </div>

                                <div class="col-md-3">
                                    <label for="numero" class="form-label">NUMERO</label>
                                    <input readonly class="form-control inputcentrado" id="numero" name="numero" type="text" value="<?php echo e(str_pad($numero, 8, '0', STR_PAD_LEFT)); ?>" style="color:red;">
                                </div>

                                <div class="col-md-3">
                                    <label for="codigo" class="form-label">CODIGO</label>
                                    <input readonly class="form-control inputcentrado" id="codigo" name="codigo" type="text" value="<?php echo e($codigo); ?>" style="color:blue;">
                                </div>
                            </div>

                            <hr class="separador" style="height: 3px; background-color: #7a2e2e; border: none; margin: 30px 0; opacity: 1;">

                            <div class="row g-2">
                                <div class="col-md-2">
                                    <label for="compra" class="form-label">COMPRA</label>
                                    <input readonly autocomplete="off" class="form-control inputcentrado" id="compra" name="compra" type="number" step="0.01" value="<?php echo e(number_format((float)($apertura_cierre->compra ?? 0), 2, '.', '')); ?>">
                                </div>

                                <div class="col-md-2">
                                    <label for="venta" class="form-label">VENTA</label>
                                    <input step="0.01" autocomplete="off" class="form-control inputcentrado" id="venta" name="venta" type="number" value="<?php echo e(number_format((float)($apertura_cierre->venta ?? 0), 2, '.', '')); ?>" oninput="convertirADolares();">
                                </div>

                                <div class="col-md-8">
                                    <label for="id_proyecto" class="form-label">PROYECTO</label>
                                    <select name="id_proyecto" id="id_proyecto" class="form-select">
                                        <option value="0">Seleccione Proyecto</option>
                                        <?php $__currentLoopData = $proyecto; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $proyectoselect): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <?php if($proyectoselect->estado == 'AC'): ?>
                                                <option value="<?php echo e($proyectoselect->id); ?>">
                                                    <?php echo e($proyectoselect->codigo . '-' . $proyectoselect->nombre); ?>

                                                </option>
                                            <?php endif; ?>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </select>
                                </div>
                            </div>

                            <div class="row g-2 mt-3">
                                <div class="col-md-4">
                                    <label for="dni" class="form-label">DNI CLIENTE</label>
                                    <input autofocus autocomplete="off" class="form-control inputcentrado <?php $__errorArgs = ['dni'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" id="dni" name="dni" type="text" maxlength="8" pattern="\d{8}" title="Solo se permiten 8 digitos" oninput="validateInput(this)" value="<?php echo e(old('dni')); ?>" required>
                                    <?php $__errorArgs = ['dni'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>

                                    <small id="error-message" style="color:red; display:none;">
                                        Debe ingresar exactamente 8 digitos.
                                    </small>

                                    <div id="dni-consulta-msg" class="mt-2"></div>
                                </div>
                            </div>

                            <div class="row g-2 mt-3">
                                <div class="col-md-4">
                                    <label for="nombres" class="form-label">NOMBRES</label>
                                    <input autocomplete="off" class="form-control <?php $__errorArgs = ['nombres'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" id="nombres" name="nombres" type="text" maxlength="255" value="<?php echo e(old('nombres')); ?>" style="text-transform: uppercase;" required>
                                    <?php $__errorArgs = ['nombres'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </div>

                                <div class="col-md-4">
                                    <label for="apellido_paterno" class="form-label">APELLIDO PATERNO</label>
                                    <input autocomplete="off" class="form-control <?php $__errorArgs = ['apellido_paterno'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" id="apellido_paterno" name="apellido_paterno" type="text" maxlength="255" value="<?php echo e(old('apellido_paterno')); ?>" style="text-transform: uppercase;" required>
                                    <?php $__errorArgs = ['apellido_paterno'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </div>

                                <div class="col-md-4">
                                    <label for="apellido_materno" class="form-label">APELLIDO MATERNO</label>
                                    <input autocomplete="off" class="form-control <?php $__errorArgs = ['apellido_materno'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?> is-invalid <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>" id="apellido_materno" name="apellido_materno" type="text" maxlength="255" value="<?php echo e(old('apellido_materno')); ?>" style="text-transform: uppercase;" required>
                                    <?php $__errorArgs = ['apellido_materno'];
$__bag = $errors->getBag($__errorArgs[1] ?? 'default');
if ($__bag->has($__errorArgs[0])) :
if (isset($message)) { $__messageOriginal = $message; }
$message = $__bag->first($__errorArgs[0]); ?>
                                        <div class="invalid-feedback"><?php echo e($message); ?></div>
                                    <?php unset($message);
if (isset($__messageOriginal)) { $message = $__messageOriginal; }
endif;
unset($__errorArgs, $__bag); ?>
                                </div>
                            </div>

                            <div class="row g-2 mt-3">
                                <div class="col-md-10">
                                    <label for="id_codigoegreso" class="form-label">CODIGO EGRESO</label>
                                    <select id="id_codigoegreso" name="id_codigoegreso" class="form-select" required>
                                        <option value="">Cargando...</option>
                                    </select>

                                    <input type="hidden" id="id_sede" name="id_sede" value="<?php echo e(Auth::user()->id_sede); ?>">
                                </div>
                            </div>

                            <div class="row g-2 mt-2">
                                <div class="col-md-12">
                                    <label for="id_codigoegresodetalle" class="form-label">CODIGO EGRESO DETALLE</label>
                                    <select id="id_codigoegresodetalle" name="id_codigoegresodetalle" class="form-select" required>
                                        <option value="">Seleccione codigo egreso</option>
                                    </select>
                                </div>
                            </div>

                            <div class="row g-2 mt-3">
                                <div class="col-md-12">
                                    <label for="concepto" class="form-label">CARGADO A:</label>
                                    <input autocomplete="off" class="form-control" id="concepto" name="concepto" type="text" value="<?php echo e(old('concepto')); ?>">
                                </div>
                            </div>

                            <div class="row g-2 mt-2">
                                <div class="col-md-4">
                                    <label for="monto" class="form-label">MONTO SOLES</label>
                                    <input class="form-control inputcentrado" id="monto" name="monto" type="text" value="<?php echo e(old('monto')); ?>" oninput="this.value = this.value.replace(/[^0-9.]/g, ''); convertirADolares();">
                                </div>

                                <div class="col-md-4">
                                    <label for="monto_dolar" class="form-label">MONTO DOLARES</label>
                                    <input readonly class="form-control inputcentrado" id="monto_dolar" name="monto_dolar" type="text" value="<?php echo e(old('monto_dolar')); ?>">
                                </div>
                            </div>

                            <div class="row g-2 mt-2">
                                <div class="col-md-12">
                                    <label for="detalle" class="form-label">POR:</label>
                                    <input autocomplete="off" class="form-control" id="detalle" name="detalle" type="text" value="<?php echo e(old('detalle')); ?>">
                                </div>
                            </div>

                            <div class="row mt-3">
                                <div class="col-md-12">
                                    <label class="form-label">USUARIO: <?php echo e(Auth::user()->username); ?></label>
                                </div>
                            </div>

                            <hr class="separador">

                            <div class="row">
                                <div class="col-md-6">
                                    <button type="submit" class="btn btn-primary" id="btsubmit" name="btsubmit">
                                        REGISTRAR EGRESO
                                    </button>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <?php if($cajaegreso && count($cajaegreso) > 0): ?>
        <div class="container">
            <div class="row justify-content-center">
                <div class="col-lg-8">
                    <div class="panel panel-primary shadow-sm">
                        <div class="panel-heading">LISTA DE EGRESOS DEL DIA</div>

                        <div class="panel-body">
                            <div class="table-responsive">
                                <table class="table table-bordered table-hover table-sm" style="font-size:12px">
                                    <thead>
                                        <tr>
                                            <th>ITEM</th>
                                            <th>SERIE-NUMERO</th>
                                            <th>ESTADO</th>
                                            <th>CODIGO</th>
                                            <th>MONTO SOLES</th>
                                            <th>MONTO DOLARES</th>
                                            <th>ACCIONES</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php $__currentLoopData = $cajaegreso; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $mostrar): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                            <?php
                                                if($mostrar->estado == 'AC'){
                                                    $estado = 'IMPRESO';
                                                } elseif($mostrar->estado == 'BA' || $mostrar->estado == 'SA'){
                                                    $estado = 'SOLICITA ANULACION';
                                                } elseif($mostrar->estado == 'AN'){
                                                    $estado = 'ANULADO';
                                                } else {
                                                    $estado = $mostrar->estado;
                                                }
                                            ?>

                                            <tr class="<?php echo e($mostrar->estado == 'AN' ? 'fila-anulada' : ''); ?>">
                                                <td class="text-center"><?php echo e($loop->iteration); ?></td>
                                                <td class="text-center"><?php echo e($mostrar->serie); ?>-<?php echo e($mostrar->numero); ?></td>
                                                <td class="text-center"><?php echo e($estado); ?></td>
                                                <td class="text-center"><?php echo e($mostrar->codigo); ?></td>
                                                <td class="text-center"><?php echo e(number_format((float) $mostrar->monto, 2, '.', ',')); ?></td>
                                                <td class="text-center"><?php echo e(number_format((float) $mostrar->monto_dolar, 2, '.', ',')); ?></td>
                                                <td class="text-center">
                                                    <a href="<?php echo e(route('admin.egreso.show', $mostrar->id)); ?>" class="btn btn-sm btn-outline-secondary btn-accion" title="Ver detalle">
                                                        <i class="fas fa-search"></i>
                                                    </a>
                                                    <?php if($mostrar->estado === 'AC'): ?>
                                                        <a href="<?php echo e(route('admin.egreso.edit', $mostrar->id)); ?>" class="btn btn-sm btn-outline-danger btn-accion" title="Solicitar anulacion">
                                                            <i class="fas fa-ban"></i>
                                                        </a>
                                                    <?php endif; ?>
                                                </td>
                                            </tr>
                                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                                    </tbody>
                                    <tfoot>
                                        <tr>
                                            <td colspan="4" class="text-end"><strong>TOTALES</strong></td>
                                            <td class="text-center"><strong><?php echo e(number_format((float) $totalSoles, 2, '.', ',')); ?></strong></td>
                                            <td class="text-center"><strong><?php echo e(number_format((float) $totalDolares, 2, '.', ',')); ?></strong></td>
                                            <td></td>
                                        </tr>
                                    </tfoot>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    <?php endif; ?>
<?php else: ?>
    <div class="alert alert-warning">
        LA CAJA NO ESTA APERTURADA.
        <br>
        FAVOR REALIZAR UNA APERTURA DE CAJA
        <br>
        EN EL MENU CAJA/APERTURA, O EN EL PANEL DE CONTROL
    </div>
<?php endif; ?>

<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>

<script src="<?php echo e(asset('js/jquery.min.js')); ?>"></script>
<script src="<?php echo e(asset('js/bootstrap3-typeahead.min.js')); ?>"></script>

<script>
    window.reniecConfig = {
        url: "<?php echo e(route('reniec.consultar.dni')); ?>",
        csrfToken: "<?php echo e(csrf_token()); ?>"
    };

    window.codigoEgresoConfig = {
        urlCodigoEgreso: "<?php echo e(url('admin/ajax/codigo-egreso')); ?>",
        urlCodigoEgresoDetalle: "<?php echo e(url('admin/ajax/codigo-egreso-detalle')); ?>",
        urlConceptos: "<?php echo e(url('admin/ajax/egreso-conceptos')); ?>",
        urlDetalles: "<?php echo e(url('admin/ajax/egreso-detalles')); ?>"
    };
</script>

<script src="<?php echo e(asset('js/codigoegreso.js')); ?>?v=<?php echo e(@filemtime(public_path('js/codigoegreso.js'))); ?>"></script>
<script src="<?php echo e(asset('js/buscardnicliente.js')); ?>?v=<?php echo e(@filemtime(public_path('js/buscardnicliente.js'))); ?>"></script>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const pdfLink = <?php echo json_encode(session('pdf_link'), 15, 512) ?>;
    if (pdfLink) {
        window.open(pdfLink, '_blank');
    }

    function pad(value) {
        return String(value).padStart(2, '0');
    }

    function actualizarFechaCliente() {
        const ahora = new Date();
        const fechaMovimiento = document.getElementById('fecha_movimiento');
        const fechaHoraCliente = document.getElementById('fecha_hora_cliente');

        if (fechaMovimiento) {
            fechaMovimiento.value = `${pad(ahora.getDate())}-${pad(ahora.getMonth() + 1)}-${ahora.getFullYear()}`;
        }

        if (fechaHoraCliente) {
            fechaHoraCliente.value = `${ahora.getFullYear()}-${pad(ahora.getMonth() + 1)}-${pad(ahora.getDate())} ${pad(ahora.getHours())}:${pad(ahora.getMinutes())}:${pad(ahora.getSeconds())}`;
        }
    }

    actualizarFechaCliente();
    setInterval(actualizarFechaCliente, 1000);
});

function convertirADolares() {
    let montoRaw = document.getElementById('monto')?.value.replace(/,/g, '') ?? '';
    let ventaRaw = document.getElementById('venta')?.value.replace(/,/g, '') ?? '';

    const montoSoles = parseFloat(montoRaw);
    const tipoCambio = parseFloat(ventaRaw);

    if (!isNaN(montoSoles) && !isNaN(tipoCambio) && tipoCambio > 0) {
        const montoDolares = montoSoles / tipoCambio;
        const inputDolar = document.getElementById('monto_dolar');
        if (inputDolar) {
            inputDolar.value = montoDolares.toFixed(2);
        }
    } else {
        const inputDolar = document.getElementById('monto_dolar');
        if (inputDolar) {
            inputDolar.value = '';
        }
    }
}

function validateInput(input) {
    const errorMessage = document.getElementById('error-message');

    input.value = input.value.replace(/\D/g, '');

    if (input.value.length < 8) {
        if (errorMessage) errorMessage.style.display = 'inline';
    } else {
        if (errorMessage) errorMessage.style.display = 'none';
    }
}

document.getElementById("monto")?.addEventListener("blur", function () {
    let value = this.value.replace(/,/g, '');

    if (value) {
        let number = parseFloat(value);
        if (!isNaN(number)) {
            this.value = number.toLocaleString('en-US', {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        }
    }
});

function checkSubmit() {
    const btn = document.getElementById("btsubmit");
    if (btn) {
        btn.innerText = "Enviando...";
        btn.disabled = true;
    }
    alert("LOS DATOS SERAN PROCESADOS");
    return true;
}
</script>
<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.app', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH D:\laragon\www\seminario\resources\views/Caja/egreso/index.blade.php ENDPATH**/ ?>