<?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 Administrador <?php $__env->endSlot(); ?>
<?php $__env->slot('title'); ?> Anuncios <?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="#modalNuevoAnuncio">
                    <i class="fas fa-plus"></i> Agregar Nueo Anuncio
                </button>
                <div class="table-responsive">
                    <table id="tablaAreas" class="table table-striped mb-0 table-hover">
                        <thead class="table-light">
                            <tr>
                                <th>#</th>
                                <th>Título</th>
                                <th>Contenido</th>
                                <th>Plan de Estudio</th>
                                <th>Estado</th>
                                <th class="text-center">Acciones</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php $__empty_1 = true; $__currentLoopData = $anuncios; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $anuncio): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); $__empty_1 = false; ?>
                                <tr>
                                    <td><?php echo e($anuncio->id_anuncio); ?></td>
                                    <td><?php echo e($anuncio->titulo); ?></td>
                                    <td><?php echo e(Str::limit(strip_tags($anuncio->contenido), 60)); ?></td>
                                    <td><?php echo e($anuncio->planEstudio->nombre ?? '-'); ?></td>
                                    <td>
                                        <?php if($anuncio->activo): ?>
                                            <span class="badge bg-success">Activo</span>
                                        <?php else: ?>
                                            <span class="badge bg-secondary">Inactivo</span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-center">
                                        <button class="btn btn-sm btn-warning btnEditarAnuncio" data-id="<?php echo e($anuncio->id_anuncio); ?>">
                                            <i class="bi bi-pencil-square"></i>
                                        </button>
                                        <button class="btn btn-sm btn-danger btnEliminarAnuncio" data-id="<?php echo e($anuncio->id_anuncio); ?>">
                                            <i class="bi bi-trash"></i>
                                        </button>
                                    </td>

                                </tr>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); if ($__empty_1): ?>
                                <tr>
                                    <td colspan="6" class="text-center text-muted">No se encontraron anuncios.</td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>

                </div>
            </div>
            <!--end card-body-->
        </div>
        <!--end card-->
    </div>
    <!--end col-->
</div>

<!-- Modal: Nuevo Anuncio (AJAX) -->
<div class="modal fade" id="modalNuevoAnuncio" tabindex="-1" aria-labelledby="modalNuevoAnuncioLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form id="formNuevoAnuncio">
            <?php echo csrf_field(); ?>
            <div class="modal-content">
                <div class="modal-header bg-primary text-white">
                    <h5 class="modal-title" id="modalNuevoAnuncioLabel">
                        <i class="fas fa-bullhorn me-1"></i> Nuevo Anuncio
                    </h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Título</label>
                        <input type="text" name="titulo" class="form-control" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Contenido</label>
                        <textarea name="contenido" class="form-control" rows="4" required></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Plan de Estudio</label>
                        <select name="plan_estudio_id" class="form-select" required>
                            <option value="" disabled selected>Seleccione un plan</option>
                            <?php $__currentLoopData = $planes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $plan): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($plan->id); ?>"><?php echo e($plan->nombre); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label d-block">Estado</label>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="activo" value="1" checked>
                            <label class="form-check-label">Activo</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input class="form-check-input" type="radio" name="activo" value="0">
                            <label class="form-check-label">Inactivo</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-de-primary">
                        <i class="fas fa-check me-1"></i> Guardar
                    </button>
                </div>
            </div>
        </form>
    </div>
</div>

<!-- Modal Editar Anuncio -->
<div class="modal fade" id="modalEditarAnuncio" tabindex="-1" aria-labelledby="modalEditarAnuncioLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <form id="formEditarAnuncio">
            <?php echo csrf_field(); ?>
            <?php echo method_field('PUT'); ?>
            <input type="hidden" name="id_anuncio" id="editar_id_anuncio">
            <div class="modal-content">
                <div class="modal-header bg-warning text-white">
                    <h5 class="modal-title"><i class="bi bi-pencil-square me-1"></i> Editar Anuncio</h5>
                    <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">Título</label>
                        <input type="text" name="titulo" id="editar_titulo" class="form-control" required>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Contenido</label>
                        <textarea name="contenido" id="editar_contenido" class="form-control" rows="4" required></textarea>
                    </div>

                    <div class="mb-3">
                        <label class="form-label">Plan de Estudio</label>
                        <select name="plan_estudio_id" id="editar_plan_estudio_id" class="form-select" required>
                            <?php $__currentLoopData = $planes; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $plan): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                <option value="<?php echo e($plan->id); ?>"><?php echo e($plan->nombre); ?></option>
                            <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                        </select>
                    </div>

                    <div class="mb-3">
                        <label class="form-label d-block">Estado</label>
                        <div class="form-check form-check-inline">
                            <input type="radio" name="activo" id="editar_activo_1" value="1" class="form-check-input">
                            <label class="form-check-label" for="editar_activo_1">Activo</label>
                        </div>
                        <div class="form-check form-check-inline">
                            <input type="radio" name="activo" id="editar_activo_0" value="0" class="form-check-input">
                            <label class="form-check-label" for="editar_activo_0">Inactivo</label>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-light" data-bs-dismiss="modal">Cancelar</button>
                    <button type="submit" class="btn btn-warning"><i class="bi bi-check"></i> Guardar Cambios</button>
                </div>
            </div>
        </form>
    </div>
</div>





<!--end row-->


<?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 () {
        $("#tablaAreas").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('#tablaAreas_wrapper .col-md-6:eq(0)');
    });
</script>
<!-- agregar  -->
<script>
    document.getElementById('formNuevoAnuncio').addEventListener('submit', function(e) {
        e.preventDefault();

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

        fetch("<?php echo e(route('anuncios.store')); ?>", {
            method: "POST",
            headers: {
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
            },
            body: formData
        })
        .then(response => {
            if (!response.ok) throw new Error('Error al guardar');
            return response.json();
        })
        .then(data => {
            Swal.fire({
                icon: 'success',
                title: 'Éxito',
                text: 'Anuncio registrado correctamente'
            }).then(() => {
                location.reload(); // O puedes actualizar solo la tabla si prefieres
            });
        })
        .catch(() => {
            Swal.fire('Error', 'No se pudo guardar el anuncio', 'error');
        });
    });
</script>

<script>
    // Cargar datos al modal de edición
    $(document).on('click', '.btnEditarAnuncio', function () {
        const id = $(this).data('id');

        fetch(`/anuncios/${id}`)
            .then(res => res.json())
            .then(data => {
                $('#editar_id_anuncio').val(data.id_anuncio);
                $('#editar_titulo').val(data.titulo);
                $('#editar_contenido').val(data.contenido);
                $('#editar_plan_estudio_id').val(data.plan_estudio_id);
                $(`input[name="activo"][value="${data.activo}"]`).prop('checked', true);

                const modal = new bootstrap.Modal(document.getElementById('modalEditarAnuncio'));
                modal.show();
            })
            .catch(() => Swal.fire('Error', 'No se pudo cargar el anuncio.', 'error'));
    });

    // Enviar cambios del anuncio
    $('#formEditarAnuncio').on('submit', function (e) {
        e.preventDefault();
        const id = $('#editar_id_anuncio').val();
        const formData = new FormData(this);

        fetch(`/anuncios/${id}`, {
            method: 'POST',
            headers: {
                'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: formData
        })
        .then(res => {
            if (!res.ok) throw new Error();
            return res.json();
        })
        .then(data => {
            Swal.fire('Actualizado', 'El anuncio ha sido actualizado.', 'success')
                .then(() => location.reload());
        })
        .catch(() => Swal.fire('Error', 'No se pudo actualizar.', 'error'));
    });

    // Eliminar anuncio
    $(document).on('click', '.btnEliminarAnuncio', function () {
        const id = $(this).data('id');

        Swal.fire({
            title: '¿Eliminar este anuncio?',
            text: "No se podrá recuperar luego.",
            icon: 'warning',
            showCancelButton: true,
            confirmButtonText: 'Sí, eliminar',
            cancelButtonText: 'Cancelar'
        }).then((result) => {
            if (result.isConfirmed) {
                fetch(`/anuncios/${id}`, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: new URLSearchParams({ _method: 'DELETE' })
                })
                .then(res => {
                    if (!res.ok) throw new Error();
                    return res.json();
                })
                .then(data => {
                    Swal.fire('Eliminado', data.message, 'success')
                        .then(() => location.reload());
                })
                .catch(() => Swal.fire('Error', 'No se pudo eliminar.', '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/iestpcarhuaz.dedu.pe/resources/views/anuncios/index.blade.php ENDPATH**/ ?>