<?= $this->extend('layouts/master') ?>

<?= $this->section('title') ?>
Crear Módulo
<?= $this->endSection() ?>

<?= $this->section('pageContent') ?>
<div class="card">
    <div class="card-body">
        <h5 class="card-title fw-semibold mb-4">Crear Módulo</h5>

        <div class="row">
            <div class="col-md-12 mb-3">
                <label class="form-label" for="nombre">Nombre</label>
                <input type="text" class="form-control" name="nombre" id="nombre"
                    data-validate="required,min-length" data-min-length="3">
            </div>


            <div class="col-md-12 mb-3">
                <label class="form-label" for="activo">Activo</label>
                <select class="form-select" name="activo" id="activo" 
                        data-validate="required">
                    <option value="" selected disabled>Seleccione…</option>
                    <option value="1">Sí</option>
                    <option value="0">No</option>
                </select>
            </div>
            <div class="col-md-12 mb-3">
                 <button class="btn btn-primary" onclick="save();">Guardar</button>
            </div>
           
        </div>
    </div>
</div>
<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
    function save(){
        if (validator(["#nombre","#activo"])) {
            var formData = new FormData();

            formData.append('nombre', document.getElementById('nombre').value);

            formData.append('activo', document.getElementById('activo').value);

            loading();
            var opcionesFetch = {
                method: 'POST',
                body: formData,
            };
            var url='<?=site_url()?>modulos/store';
            
            fetch(url, opcionesFetch)
            .then(function(response) {
                return response.json();
            })
            .then(function(data) {
                if (data.success) {
                    // Add your success logic here
                    stopLoading();
                    Swal.fire({
                        icon: 'success',
                        title: 'Correcto',
                        text: data.message
                    }).then((okay) => {
                        window.location.href = '<?= site_url('modulos') ?>';
                    })
                } else {
                    stopLoading();
                    Swal.fire({
                        icon: 'warning',
                        title: 'Error',
                        text: data.message
                    })
                }
            })
            .catch(function(error) {
                stopLoading();
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: error
                })
            });
        }
    }
</script>
<?= $this->endSection() ?>