<?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'); ?> Conceptos <?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="#modalNuevoConcepto">
                    <i class="fas fa-plus"></i> Agregar Nuevo Concepto
                </button>
                <div class="table-responsive">
                    
                    <table id="tablaSemestres" class="table table-striped mb-0 table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>#</th>
                                <th>Nombre</th>
                                <th>Precio</th>
                                <th>Tipo</th>
                                <th>Estado</th>
                                <th class="text-end">Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $__empty_1 = true; $__currentLoopData = $conceptos; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $concepto): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <tr>
                                    <td><?php echo e($loop->iteration); ?></td>
                                    <td><?php echo e($concepto->nombre); ?></td>
                                    <td>S/ <?php echo e(number_format($concepto->precio, 2)); ?></td>
                                    <td><?php echo e($concepto->tipo_concepto ?? '-'); ?></td>
                                    <td>
                                        <?php if($concepto->activo): ?>
                                            <span class="badge bg-success">Activo</span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">Inactivo</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end">
                                        <button type="button" class="btn btn-sm btn-outline-primary" onclick="editarConcepto(<?php echo e($concepto->id_concepto); ?>)">
                                            <i class="bi bi-pencil-square"></i>
                                        </button>

                                        <button type="button" class="btn btn-sm btn-outline-danger" onclick="eliminarConcepto(<?php echo e($concepto->id_concepto); ?>)">
                                            <i class="bi bi-trash3"></i>
                                        </button>

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


<div class="modal fade" id="modalNuevoConcepto" tabindex="-1" aria-labelledby="modalNuevoConceptoLabel" aria-hidden="true">
    <div class="modal-dialog modal-md modal-dialog-centered">
        <div class="modal-content rounded-4">
            <div class="modal-header bg-primary text-white">
                <h5 class="modal-title" id="modalNuevoConceptoLabel">
                    <i class="bi bi-plus-circle me-2"></i> Nuevo Concepto
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <form id="formConcepto">
                <div class="modal-body">
                    <?php echo csrf_field(); ?>
                    <div class="mb-3">
                        <label class="form-label">Nombre del Concepto</label>
                        <input type="text" class="form-control" name="nombre" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Precio (S/)</label>
                        <input type="number" step="0.01" min="0" class="form-control" name="precio" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Tipo</label>
                        <select name="tipo_concepto" class="form-select" required>
                            <option value="">Seleccione</option>
                            <option value="RDR">RDR</option>
                            <option value="Otros">Otros</option>
                            
                        </select>
                    </div>

                    <div class="form-check form-switch">
                        <input class="form-check-input" type="checkbox" name="activo" id="activo" checked>
                        <label class="form-check-label" for="activo">Activo</label>
                    </div>
                </div>

                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">
                        <i class="bi bi-save me-1"></i> Guardar
                    </button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        Cancelar
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>



<!--end row-->
<!-- Modal de edición de concepto -->
<div class="modal fade" id="modalEditarConcepto" tabindex="-1" aria-labelledby="modalEditarConceptoLabel" aria-hidden="true">
    <div class="modal-dialog">
        <form id="formEditarConcepto" class="modal-content">
            <?php echo csrf_field(); ?>
            <?php echo method_field('PUT'); ?>
            <div class="modal-header">
                <h5 class="modal-title" id="modalEditarConceptoLabel">
                    <i class="bi bi-pencil-square me-1"></i> Editar Concepto
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Cerrar"></button>
            </div>

            <div class="modal-body">
                <input type="hidden" id="editar_id_concepto">

                <div class="mb-3">
                    <label for="editar_nombre" class="form-label">Nombre</label>
                    <input type="text" class="form-control" id="editar_nombre" name="nombre" required>
                </div>

                <div class="mb-3">
                    <label for="editar_precio" class="form-label">Precio</label>
                    <input type="number" class="form-control" id="editar_precio" name="precio" step="0.01" min="0" required>
                </div>

                <div class="mb-3">
                    <label for="editar_tipo_concepto" class="form-label">Tipo de Concepto</label>
                    <input type="text" class="form-control" id="editar_tipo_concepto" name="tipo_concepto">
                </div>
            </div>

            <div class="modal-footer">
                <button type="submit" class="btn btn-success">
                    <i class="bi bi-save me-1"></i> Guardar Cambios
                </button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
            </div>
        </form>
    </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>

<!-- Agregar-->
<script>
    document.getElementById('formConcepto').addEventListener('submit', function (e) {
        e.preventDefault();

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

        // Convertir checkbox "activo"
        formData.set('activo', form.activo.checked ? 1 : 0);

        fetch("<?php echo e(route('conceptos.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: '¡Guardado!',
                    text: 'El concepto fue registrado correctamente.',
                    timer: 2000,
                    showConfirmButton: false
                }).then(() => {
                    location.reload();
                });
            } else {
                Swal.fire('Error', data.message || 'Hubo un problema al registrar.', 'error');
            }
        })
        .catch(error => {
            console.error(error);
            Swal.fire('Error', 'Error inesperado al procesar el formulario.', 'error');
        });
    });
</script>

<script>
    function eliminarConcepto(id) {
        Swal.fire({
            title: '¿Estás seguro?',
            text: 'Esta acción no se puede deshacer',
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí, eliminar',
            cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                fetch(`/conceptos/${id}`, {
                    method: 'DELETE',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
                    }
                })
                .then(res => res.json())
                .then(data => {
                    if (data.success) {
                        Swal.fire('Eliminado', 'El concepto fue eliminado correctamente', 'success')
                            .then(() => location.reload());
                    } else {
                        Swal.fire('Error', data.message || 'No se pudo eliminar el concepto', 'error');
                    }
                });
            }
        });
    }

</script>

<script>
    function editarConcepto(id) {
        fetch(`/conceptos/${id}`)
            .then(res => res.json())
            .then(data => {
                if (data.success) {
                    const concepto = data.concepto;

                    document.getElementById('editar_id_concepto').value = concepto.id_concepto;
                    document.getElementById('editar_nombre').value = concepto.nombre;
                    document.getElementById('editar_precio').value = concepto.precio;
                    document.getElementById('editar_tipo_concepto').value = concepto.tipo_concepto ?? '';

                    new bootstrap.Modal(document.getElementById('modalEditarConcepto')).show();
                } else {
                    Swal.fire('Error', 'No se pudo cargar el concepto.', 'error');
                }
            });
    }

    document.getElementById('formEditarConcepto').addEventListener('submit', function(e) {
        e.preventDefault();

        const id = document.getElementById('editar_id_concepto').value;
        const formData = new FormData(this);

        fetch(`/conceptos/${id}`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                Swal.fire('¡Éxito!', 'Concepto actualizado correctamente.', 'success')
                    .then(() => location.reload());
            } else {
                Swal.fire('Error', data.message || 'No se pudo actualizar.', '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/iegb.dedu.pe/resources/views/caja/conceptos/index.blade.php ENDPATH**/ ?>