<?php $__env->startSection('title'); ?> Inicio <?php $__env->stopSection(); ?>
<?php $__env->startSection('content'); ?>
<!-- this is breadcrumbs -->
<?php $__env->startComponent('components.breadcrumb'); ?>
<?php $__env->slot('li_1'); ?> Inicio <?php $__env->endSlot(); ?>
<?php $__env->slot('li_2'); ?> Panel Caja <?php $__env->endSlot(); ?>
<?php $__env->slot('title'); ?> Caja <?php $__env->endSlot(); ?>
<?php echo $__env->renderComponent(); ?>

<!-- start page content -->
<div class="row">
    <div class="col-12">
        <div class="card">
            <div class="card-body mb-n3">
                <button type="button" class="btn btn-de-primary btn-sm px-4 mt-0 mb-3" 
                    data-bs-toggle="modal" 
                    data-bs-target="#modalTransaccion">
                    <i class="fas fa-plus"></i> Nueva Transacción
                </button>

                
                <div class="table-responsive">
                    
                    <table id="tablaSemestres" class="table table-striped mb-0 table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>#</th>
                                <th>Fecha</th>
                                <th>Tipo</th>
                                <th>Concepto</th>
                                <th>Monto (S/)</th>
                                <th>Estado</th>
                                <th>Caja</th>
                                <th>DNI</th>
                                <th>Apellidos y Nombres</th>
                                <th class="text-end">Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $__empty_1 = true; $__currentLoopData = $transacciones; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $t): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <tr>
                                    <td><?php echo e($loop->iteration); ?></td>
                                    <td><?php echo e($t->fecha); ?></td>
                                    <td>
                                        <span class="badge <?php echo e($t->tipo == 'ingreso' ? 'bg-success' : 'bg-info'); ?>">
                                            <?php echo e(ucfirst($t->tipo)); ?>

                                        </span>
                                    </td>
                                    <td><?php echo e($t->concepto->nombre ?? '-'); ?></td>
                                    <td>S/ <?php echo e(number_format($t->monto, 2)); ?></td>
                                    <td>
                                        <span class="badge <?php echo e($t->estado == 'aceptado' ? 'bg-primary' : 'bg-danger'); ?>">
                                            <?php echo e(ucfirst($t->estado)); ?>

                                        </span>
                                    </td>
                                    <td><?php echo e($t->caja->nombre ?? '-'); ?></td>
                                    <td><?php echo e($t->dni ?? '-'); ?></td>
                                    <td><?php echo e($t->apellidos); ?> <?php echo e($t->nombres); ?></td>
                                    <td class="text-end">
                                        
                                        
                                        <button onclick="anularTransaccion(<?php echo e($t->id_transaccion); ?>)" class="btn btn-sm btn-outline-danger">
                                            <i class="bi bi-x-circle"></i>
                                        </button>


                                        <a href="<?php echo e(route('transacciones.pdf', $t->id_transaccion)); ?>" class="btn btn-sm btn-outline-info" target="_blank">
                                            <i class="bi bi-printer"></i>
                                        </a>

                                    </td>
                                </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <tr>
                                    <td colspan="10" class="text-center text-muted">No hay transacciones registradas.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
            <!--end card-body-->
        </div>
        <!--end card-->
    </div>
    <!--end col-->
</div>

<!-- Modal Nueva Transacción -->
<div class="modal fade" id="modalTransaccion" tabindex="-1" aria-labelledby="modalTransaccionLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content border-0 shadow-lg rounded-4">
            <div class="modal-header bg-de-primary text-white rounded-top-4">
                <h5 class="modal-title">
                    <i class="fas fa-plus-circle me-2"></i> Registrar Nueva Transacción
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>

            <form id="formNuevaTransaccion">
                <div class="modal-body px-4 py-3">
                    <!-- Sección 1: Información de transacción -->
                    <h6 class="text-muted mb-3 border-bottom pb-1">
                        <i class="bi bi-wallet2 me-1 text-primary"></i> Datos de la Transacción
                    </h6>
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Caja <span class="text-danger">*</span></label>
                            <select name="caja_id" class="form-select" required>
                                <option value="">Seleccione una caja...</option>
                                <?php $__currentLoopData = $cajas; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $caja): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($caja->id_caja); ?>">
                                        <?php echo e($caja->nombre); ?> (<?php echo e(date('d/m/Y', strtotime($caja->fecha_apertura))); ?>)
                                    </option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label">Tipo <span class="text-danger">*</span></label>
                            <select name="tipo" class="form-select" required>
                                <option value="">Seleccione...</option>
                                <option value="ingreso">Ingreso</option>
                                <option value="egreso">Egreso</option>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Fecha <span class="text-danger">*</span></label>
                            <input type="date" name="fecha" class="form-control" value="<?php echo e(date('Y-m-d')); ?>" required>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Concepto <span class="text-danger">*</span></label>
                            <select name="concepto_id" class="form-select" id="selectConcepto" required>
                                <option value="">Seleccione...</option>
                                <?php $__currentLoopData = $conceptos; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $concepto): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($concepto->id_concepto); ?>" data-precio="<?php echo e($concepto->precio); ?>">
                                        <?php echo e($concepto->nombre); ?>

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

                        <div class="col-md-6">
                            <label class="form-label">Monto (S/.) <span class="text-danger">*</span></label>
                            <input type="number" name="monto" class="form-control" min="0" step="0.01" placeholder="0.00" required>
                        </div>
                    </div>

                    <!-- Sección 2: Datos del Cliente (opcional) -->
                    <h6 class="text-muted mb-3 border-bottom pb-1">
                        <i class="bi bi-person-badge me-1 text-secondary"></i> Datos del Cliente
                    </h6>
                    <div class="row g-3 mb-3">
                        <div class="col-md-4">
                            <label class="form-label">DNI</label>
                            <input type="text" name="dni" class="form-control" maxlength="15" placeholder="Opcional">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Nombres</label>
                            <input type="text" name="nombres" class="form-control" maxlength="30" placeholder="Opcional">
                        </div>
                        <div class="col-md-4">
                            <label class="form-label">Apellidos</label>
                            <input type="text" name="apellidos" class="form-control" maxlength="30" placeholder="Opcional">
                        </div>
                    </div>

                    <!-- Observación -->
                    <div class="mb-3">
                        <label class="form-label">Observación</label>
                        <textarea name="observacion" class="form-control" rows="2" placeholder="Detalles adicionales (opcional)"></textarea>
                    </div>
                </div>

                <div class="modal-footer bg-light rounded-bottom-4 px-4 py-2">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        <i class="bi bi-x-circle me-1"></i> Cancelar
                    </button>
                    <button type="submit" class="btn btn-de-primary">
                        <i class="bi bi-save me-1"></i> Guardar Transacción
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>





<?php $__env->stopSection(); ?>
<?php $__env->startSection('script'); ?>
<!-- jQuery y DataTables -->

<!-- jQuery y DataTables -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script>

<!-- DataTables Buttons -->
<script src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.2.7/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.colVis.min.js"></script>

<!-- DataTables CSS -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>

<script>
    $(document).ready(function () {
        $("#tablaSemestres").DataTable({
            "responsive": true,
            "lengthChange": true,
            "autoWidth": false,
            "buttons": [
                {
                    extend: 'collection',
                    text: 'Opciones',
                    buttons: [
                        { extend: 'copy', text: 'Copiar' },
                        { extend: 'csv', text: 'CSV' },
                        { extend: 'excel', text: 'Excel', title: 'Periodos Académicos' },
                        { extend: 'pdf', text: 'PDF' },
                        { extend: 'print', text: 'Imprimir' }
                    ]
                },
                { extend: 'colvis', text: 'Visibilidad de Columna' }
            ],
            "paging": true,
            "searching": true,
            "info": true,
            "language": {
                "search": "Buscar:",
                "lengthMenu": "Mostrar _MENU_ registros por página",
                "info": "Mostrando _START_ a _END_ de _TOTAL_ entradas",
                "paginate": {
                    "first": "Primero",
                    "previous": "Anterior",
                    "next": "Siguiente",
                    "last": "Último"
                }
            }
        }).buttons().container().appendTo('#tablaSemestres_wrapper .col-md-6:eq(0)');
    });
</script>


<script>
    // Autocompletar monto al elegir concepto
    document.getElementById('selectConcepto').addEventListener('change', function () {
        const selected = this.options[this.selectedIndex];
        const precio = selected.getAttribute('data-precio');
        if (precio) {
            document.querySelector('input[name="monto"]').value = precio;
        }
    });
</script>
<!-- agregar -->
<script>
    document.getElementById('formNuevaTransaccion').addEventListener('submit', function(e) {
        e.preventDefault();

        const form = this;
        const formData = new FormData(form);

        fetch("<?php echo e(route('transacciones.store')); ?>", {
            method: "POST",
            headers: {
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                Swal.fire({
                    icon: 'success',
                    title: '¡Transacción registrada!',
                    timer: 1500,
                    showConfirmButton: false
                }).then(() => {
                    form.reset();
                    const modal = bootstrap.Modal.getInstance(document.getElementById('modalTransaccion'));
                    modal.hide();
                    location.reload(); // Opcional: recargar para ver en la tabla
                });
            } else {
                Swal.fire('Error', data.message || 'No se pudo registrar la transacción.', 'error');
            }
        })
        .catch(() => {
            Swal.fire('Error', 'Error del servidor. Intenta nuevamente.', 'error');
        });
    });
</script>
<!-- anular -->
<script>
function anularTransaccion(id) {
    Swal.fire({
        title: '¿Estás seguro?',
        text: "Esta acción anulará la transacción.",
        icon: 'warning',
        input: 'text',
        inputLabel: 'Motivo de anulación',
        inputPlaceholder: 'Escribe el motivo...',
        inputValidator: (value) => {
            if (!value) {
                return 'Debes ingresar un motivo';
            }
        },
        showCancelButton: true,
        confirmButtonText: 'Sí, anular',
        cancelButtonText: 'Cancelar'
    }).then((result) => {
        if (result.isConfirmed) {
            fetch(`/transacciones/${id}/anular`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
                },
                body: JSON.stringify({ motivo: result.value })
            })
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    Swal.fire('Anulada', data.message, 'success')
                        .then(() => location.reload());
                } else {
                    Swal.fire('Error', data.message, 'error');
                }
            })
            .catch(() => {
                Swal.fire('Error', 'Error de servidor', 'error');
            });
        }
    });
}
</script>

<?php $__env->stopSection(); ?>

<?php echo $__env->make('layouts.master', \Illuminate\Support\Arr::except(get_defined_vars(), ['__data', '__path']))->render(); ?><?php /**PATH /home/dedu/public_html/iestpjuanhuarin.dedu.pe/resources/views/transacciones/index.blade.php ENDPATH**/ ?>