<?php $__env->startSection('title', 'Usuarios' . ' | ' . config('app.name')); ?>

<?php $__env->startSection('content_header'); ?>
    <div class="w-100">
        <?php
            $breadcrumbs = [
                ['name' => 'Inicio', 'route' => 'dashboard', 'icon' => 'fa-home'],
                ['name' => 'Subcartas', 'route' => 'subcartas.index'],
                ['name' => 'Lista de Subcartas'],
            ];
        ?>

        <nav aria-label="breadcrumb">
            <ol class="breadcrumb bg-light p-2 rounded shadow-sm">
                <?php $__currentLoopData = $breadcrumbs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $breadcrumb): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                    <?php if(isset($breadcrumb['route'])): ?>
                        <li class="breadcrumb-item">
                            <a href="<?php echo e(route($breadcrumb['route'])); ?>">
                                <?php if(isset($breadcrumb['icon'])): ?>
                                    <i class="fas <?php echo e($breadcrumb['icon']); ?> mr-1"></i>
                                <?php endif; ?>
                                <?php echo e($breadcrumb['name']); ?>

                            </a>
                        </li>
                    <?php else: ?>
                        <li class="breadcrumb-item active" aria-current="page"><?php echo e($breadcrumb['name']); ?></li>
                    <?php endif; ?>
                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
            </ol>
        </nav>
    </div>
<?php $__env->stopSection(); ?>

<?php $__env->startSection('content'); ?>
    <div class="m-0">
        <div class="row">
            <div class="col-md-12">
                <div class="card">
                    <div class="card-header">
                        <div class="row align-items-center">
                            <!-- Título -->
                            <div class="col-12 col-md-6">
                                <h5 class="mb-md-0">Gestión de Subcartas</h5>
                            </div>

                            <!-- Botón -->
                            <div class="col-12 col-md-6 text-md-right">
                                <button class="btn btn-success btn-sm" id="createNewSubCarta">
                                    <i class="fas fa-plus"></i> Nueva Subcarta
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="card-body p-2">


                        <div class="table-responsive">
                            <table id="subcartas-table" class="table table-bordered table-striped" style="width: 100%">
                                <thead>
                                    <tr>
                                        <th style="width: 5%"></th>
                                        <th>ID</th>
                                        <th>Nombre</th>
                                        <th>Orden</th>
                                        <th>Estado</th>
                                        <th style="width: 10%">Acciones</th>
                                    </tr>
                                </thead>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Modal para agregar/editar -->
    <div class="modal fade" id="subcartaModal" tabindex="-1" role="dialog" aria-labelledby="subcartaModalLabel"
        aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header bg-secondary text-white">
                    <h5 class="modal-title" id="subcartaModalLabel">Nueva Subcarta</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <form id="subcartaForm">
                    <?php echo csrf_field(); ?>
                    <div class="modal-body">
                        <input type="hidden" id="subcarta_id">

                        
                        <div class="form-group">
                            <label for="carta_id">Carta</label>
                            <select class="form-control" id="carta_id" name="carta_id" required>
                                <option value="">Seleccione una carta</option>
                                <?php $__currentLoopData = $cartas; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $carta): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                                    <option value="<?php echo e($carta->id); ?>"><?php echo e($carta->nombre); ?></option>
                                <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>
                            </select>
                        </div>



                        
                        <h5>Traducciones</h5>
                        <hr>

                        
                        <label><strong>Nombre</strong></label>
                        <?php $__currentLoopData = $langs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $lang): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div class="input-group mb-2">
                                <div class="input-group-prepend">
                                    <span class="input-group-text">
                                        <img src="<?php echo e(asset($lang->image ?? 'images/empty.png')); ?>" alt="<?php echo e($lang->name); ?>"
                                            width="20" height="20" class="me-1">
                                    </span>
                                </div>
                                <input type="text" id="nombre_<?php echo e($lang->code); ?>" 
                                    name="nombre[<?php echo e($lang->code); ?>]" class="form-control"
                                    placeholder="Nombre en <?php echo e($lang->name); ?>" required>
                            </div>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>

                        
                        <label class="mt-3"><strong>Descripción</strong></label>
                        <?php $__currentLoopData = $langs; $__env->addLoop($__currentLoopData); foreach($__currentLoopData as $lang): $__env->incrementLoopIndices(); $loop = $__env->getLastLoop(); ?>
                            <div class="input-group mb-2">
                                <div class="input-group-prepend">
                                    <span class="input-group-text">
                                        <img src="<?php echo e(asset($lang->image ?? 'images/empty.png')); ?>"
                                            alt="<?php echo e($lang->name); ?>" width="20" height="20" class="me-1">
                                    </span>
                                </div>
                                <input type="text" id="descripcion_<?php echo e($lang->code); ?>" 
                                    name="descripcion[<?php echo e($lang->code); ?>]" class="form-control"
                                    placeholder="Descripción en <?php echo e($lang->name); ?>">
                            </div>
                        <?php endforeach; $__env->popLoop(); $loop = $__env->getLastLoop(); ?>


                        
                        <div class="form-group">
                            <label for="orden">Orden</label>
                            <input type="number" class="form-control" id="orden" name="orden" required>
                        </div>

                        
                        <div class="form-group">
                            <div class="custom-control custom-switch">
                                <input type="checkbox" class="custom-control-input" id="activo" name="activo"
                                    value="1" checked>
                                <label class="custom-control-label" for="activo">Activo</label>
                            </div>
                        </div>
                    </div>

                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button>
                        <button type="submit" class="btn btn-primary">Guardar</button>
                    </div>
                </form>
            </div>
        </div>
    </div>




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

<?php $__env->startSection('css'); ?>
    
    
<?php $__env->stopSection(); ?>

<?php $__env->startPush('js'); ?>
    <script>
        $(document).ready(function() {
            // DataTable
            var table = $('#subcartas-table').DataTable({
                responsive: {
                    details: {
                        type: 'column', // el signo + en la primera columna
                        target: 0 // en qué columna colocar el signo +
                    }
                },
                columnDefs: [{
                    className: 'dtr-control', // clase obligatoria para el botón de expandir
                    orderable: false,
                    targets: 0
                }],
                processing: true,
                serverSide: true,
                ajax: {
                    url: "<?php echo e(route('subcartas.datatables')); ?>",
                    type: "POST",
                    headers: {
                        'X-CSRF-TOKEN': '<?php echo e(csrf_token()); ?>'
                    }
                },
                columns: [{
                        data: null,
                        defaultContent: ''
                    }, {
                        data: 'id',
                        name: 'id'
                    },
                    {
                        data: 'nombre',
                        name: 'nombre'
                    },
                    {
                        data: 'orden',
                        name: 'orden'
                    },
                    {
                        data: 'activo',
                        name: 'activo'
                    },
                    {
                        data: 'acciones',
                        name: 'acciones',
                        orderable: false,
                        searchable: false
                    }
                ],
                order: [
                    [1, 'desc']
                ], // <-- orden descendente por la columna "orden"
            });

            // Abrir modal para crear
            $('#createNewSubCarta').click(function() {
                $('#subcartaForm').trigger("reset");
                $('#subcarta_id').val('');
                $('#subcartaModalLabel').text('Nueva Subcarta');
                $('#subcartaModal').modal('show');
            });




            // Abrir modal para editar
            $(document).on('click', '.btn-editar', function() {
                var id = $(this).data('id');

                $.ajax({
                    url: "<?php echo e(url('admin/subcartas')); ?>/" + id,
                    type: 'GET',
                    success: function(response) {
                        console.log("DEBUG response", response); // 👈

                        $('#subcartaModalLabel').text('Editar Subcarta');
                        $('#subcarta_id').val(response.id);
                        $('#carta_id').val(response.carta_id);
                        $('#orden').val(response.orden);
                        $('#activo').prop('checked', response.activo);

                        if (response.translations) {
                            response.translations.forEach(function(translation) {
                                console.log("DEBUG translation", translation); // 👈
                                $('#nombre_' + translation.locale).val(translation
                                    .nombre);
                                $('#descripcion_' + translation.locale).val(translation
                                    .descripcion);
                            });
                        }

                        $('#subcartaModal').modal('show');
                    },
                    error: function(xhr) {
                        toastr.error('Error al cargar los datos de la subcarta');
                    }
                });
            });

            // Configuración de toast global

            // Enviar formulario
            $('#subcartaForm').on('submit', function(e) {
                e.preventDefault();

                var formData = new FormData(this);

                // Token CSRF
                formData.append('_token', $('meta[name="csrf-token"]').attr('content'));

                var id = $('#subcarta_id').val(); // 👈 si hay valor → update
                var url;

                if (id && id.trim() !== '') {
                    // Editar
                    url = "<?php echo e(url('admin/subcartas')); ?>/" + id;
                    formData.append('_method', 'PUT'); // 👈 obligatorio para update
                } else {
                    // Crear
                    url = "<?php echo e(route('subcartas.store')); ?>";
                }

                $.ajax({
                    url: url,
                    type: 'POST', // 👈 siempre POST, Laravel interpreta _method=PUT como update
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response.success) {
                            $('#subcartaModal').modal('hide');
                            table.ajax.reload();
                            Toast.fire({
                                icon: 'success',
                                title: response.message
                            });
                        }
                    },
                    error: function(xhr) {
                        if (xhr.status === 422) {
                            var errors = xhr.responseJSON.errors;
                            $.each(errors, function(key, value) {
                                Toast.fire({
                                    icon: 'error',
                                    title: value[0]
                                });
                            });
                        } else {
                            Toast.fire({
                                icon: 'error',
                                title: xhr.responseJSON.message ||
                                    'Error al guardar la subcarta'
                            });
                        }
                    }
                });
            });



            // Eliminar subcarta
            $(document).on('click', '.btn-eliminar', function() {
                var id = $(this).data('id');

                Swal.fire({
                    title: '¿Está seguro?',
                    text: "No podrá revertir esto.",
                    icon: 'warning',
                    showCancelButton: true,
                    confirmButtonColor: '#d33',
                    cancelButtonColor: '#6c757d',
                    confirmButtonText: 'Sí, eliminar',
                    cancelButtonText: 'Cancelar'
                }).then((result) => {
                    if (result.isConfirmed) {
                        $.ajax({
                            url: "<?php echo e(url('admin/subcartas')); ?>/" + id,
                            type: 'DELETE',
                            data: {
                                _token: "<?php echo e(csrf_token()); ?>" // 👈 CSRF agregado aquí
                            },
                            success: function(response) {
                                if (response.success) {
                                    table.ajax.reload();
                                    Toast.fire({
                                        icon: 'success',
                                        title: response.message
                                    });
                                }
                            },
                            error: function(xhr) {
                                Toast.fire({
                                    icon: 'error',
                                    title: xhr.responseJSON.message ||
                                        'Error al eliminar la subcarta'
                                });
                            }
                        });
                    }
                });
            });


        });
    </script>
<?php $__env->stopPush(); ?>

<?php echo $__env->make('adminlte::page', array_diff_key(get_defined_vars(), ['__data' => 1, '__path' => 1]))->render(); ?><?php /**PATH C:\PAN82\htdocs\manu\resources\views/subcartas/index.blade.php ENDPATH**/ ?>