<?php
//print_r($cursos->result());

?>

<!-- ==== Modal ==== -->

<!-- Modal de Perfil -->
<div class="modal fade" id="modalPerfil" tabindex="-1" role="dialog" aria-labelledby="modalPerfilLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="modalPerfilLabel">Mi Perfil</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body has-success">
                <form id="formPerfil">
                    <div class="text-center">
                    <img id="imgPerfil" src="" class="rounded-circle" width="100" height="100" alt="Imagen de perfil">
                        <input type="file" id="imagenPerfil" class="form-control mt-2">
                    </div>
                    <div class="form-group">
                        <label>Usuario</label>
                        <input type="text" id="user" class="form-control" disabled>
                    </div>
                    <div class="form-group ">
                        <label>Nueva Contraseña</label>
                        <input type="text" id="pass" class="form-control" disabled>
                    </div>
                    <div class="form-group">
                        <label>Nombres</label>
                        <input type="text" id="nombres" class="form-control" disabled>
                    </div>
                    <div class="form-group">
                        <label>Primer Apellido</label>
                        <input type="text" id="primerApellido" class="form-control" disabled>
                    </div>
                    <div class="form-group">
                        <label>Segundo Apellido</label>
                        <input type="text" id="segundoApellido" class="form-control" disabled>
                    </div>
                    <div class="form-group">
                        <label>Cédula</label>
                        <input type="text" id="cedula" class="form-control" disabled>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-info" id="habilitarEdit">Editar</button>
                <button type="button" class="btn btn-success" id="guardarPerfil">Guardar Cambios</button>
                <button type="button" class="btn btn-dark" data-dismiss="modal">Cerrar</button>
            </div>
        </div>
    </div>
</div>


<!-- ==== Fin Modal==== -->
<body class="skin-default fixed-layout">
    <!-- ============================================================== -->
    <!-- Precargador: estilo que puedes encontrar en spinners.css -->
    <!-- ============================================================== -->
    <div class="preloader">
        <div class="loader">
            <div class="loader__figure"></div>
            <p class="loader__label">Registro de Asistencia</p>
        </div>
    </div>
    <!-- ============================================================== -->
    <!-- Main wrapper - style you can find in pages.scss -->
    <!-- ============================================================== -->
    <div id="main-wrapper">
        <!-- ============================================================== -->
        <!-- Topbar header - style you can find in pages.scss -->
        <!-- ============================================================== -->
        <header class="topbar">
            <nav class="navbar top-navbar navbar-expand-md navbar-dark">
                <!-- ============================================================== -->
                <!-- Logo -->
                <!-- ============================================================== -->
                <div class="navbar-header">
                    <a class="navbar-brand" href="">
                        <!-- Logo icon --><b>
                            <!--You can put here icon as well // <i class="wi wi-sunset"></i> //-->
                            <!-- Dark Logo icon -->
                            <img src="<?php echo base_url(); ?>/assets/images/asis-ico40x40.png" alt="homepage"
                                class="dark-logo" />
                            <!-- Light Logo icon -->
                            <img src="<?php echo base_url(); ?>/assets/images/asis-ico40x40.png" alt="homepage"
                                class="light-logo" />
                        </b>
                        <!--End Logo icon -->
                        <!-- Logo text -->
                        <span>
                            <!-- dark Logo text -->
                            <!-- <img src="<?php echo base_url(); ?>/assets/images/logo-text.png" alt="homepage"
                                class="dark-logo" /> -->
                            <!-- Light Logo text -->
                            <!-- <img src="<?php echo base_url(); ?>/assets/images/logo-light-text.png" class="light-logo"
                                alt="homepage" /> -->
                        </span> 
                    </a>
                </div>
                <!-- ============================================================== -->
                <!-- End Logo -->
                <!-- ============================================================== -->
                <div class="navbar-collapse">
                    <!-- ============================================================== -->
                    <!-- toggle and nav items -->
                    <!-- ============================================================== -->
                    <ul class="navbar-nav mr-auto">
                        <!-- Botón para móviles (se muestra solo en pantallas pequeñas) -->
                        <li class="nav-item d-block d-md-none"> 
                            <a class="nav-link nav-toggler waves-effect waves-dark" href="javascript:void(0)">
                                <i class="ti-menu"></i>
                            </a> 
                        </li>

                        <!-- Botón para tablet/escritorio (oculto en móviles) -->
                        <li class="nav-item d-none d-md-block"> 
                            <a class="nav-link sidebartoggler waves-effect waves-dark" href="javascript:void(0)">
                                <i class="icon-menu"></i>
                            </a> 
                        </li>
                    </ul>

                    <!-- ============================================================== -->
                    <!-- User profile and search -->
                    <!-- ============================================================== -->
                    <ul class="navbar-nav my-lg-0">

                        <!-- User Profile -->
                        <!-- ============================================================== -->
                        <li class="nav-item dropdown u-pro">
                            <a class="nav-link dropdown-toggle waves-effect waves-dark profile-pic" href=""
                                data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"><img
                                    src="<?php echo base_url().$this->session->userdata('imagen'); ?>" alt="user" class=""> <span
                                    class="hidden-md-down"><?php echo $this->session->userdata('user'); ?> &nbsp;<i class="fa fa-angle-down"></i></span> </a>
                            <div class="dropdown-menu dropdown-menu-right animated flipInY">
                                
                                <a href="javascript:void(0)" data-toggle="modal" data-target="#modalPerfil" class="dropdown-item"><i class="ti-settings"></i> Mi perfil</a>
                                
                                <!-- <a href="javascript:void(0)" class="dropdown-item"><i class="ti-wallet"></i> My
                                    Balance</a>
                                
                                <a href="javascript:void(0)" class="dropdown-item"><i class="ti-email"></i> Inbox</a>
                                
                                <div class="dropdown-divider"></div>
                                
                                <a href="javascript:void(0)" class="dropdown-item"><i class="ti-settings"></i> Account
                                    Setting</a> -->
                                <!-- text-->
                                <div class="dropdown-divider"></div>
                                <!-- text-->
                                <a href="<?php echo base_url('login/logout'); ?>" class="dropdown-item"><i class="fa fa-power-off"></i> Salir</a>
                                <!-- text-->
                            </div>
                        </li>
                        <!-- ============================================================== -->
                        <!-- End User Profile -->
                        <!-- ============================================================== -->
                        <li class="nav-item right-side-toggle"> <a class="nav-link  waves-effect waves-light"
                                href="javascript:void(0)"><i class="ti-settings"></i></a></li>
                    </ul>
                </div>
            </nav>
        </header>
        <!-- ============================================================== -->
        <!-- End Topbar header -->
        <!-- ============================================================== -->
        <!-- ============================================================== -->
        <!-- Left Sidebar - style you can find in sidebar.scss  -->
        <!-- ============================================================== -->
        <aside class="left-sidebar">
            <!-- Sidebar scroll-->
            <div class="scroll-sidebar">
                <!-- Sidebar navigation-->
                <nav class="sidebar-nav">
                    <ul id="sidebarnav">
                        <li class="user-pro"> <a class="has-arrow waves-effect waves-dark" href="javascript:void(0)"
                                aria-expanded="false"><img src="<?php echo base_url().$this->session->userdata('imagen'); ?>"
                                    alt="user-img" class="img-circle"><span class="hide-menu"><?php echo $this->session->userdata('user'); ?></span></a>
                            <ul aria-expanded="false" class="collapse">
                            <li>
                                <a href="javascript:void(0)" data-toggle="modal" data-target="#modalPerfil">
                                    <i class="ti-user"></i> Mi Perfil
                                </a>
                            </li>
                                <!-- <li><a href="javascript:void(0)"><i class="ti-wallet"></i> Mi Balance</a></li>
                                <li><a href="javascript:void(0)"><i class="ti-email"></i> Bandeja</a></li>
                                <li><a href="javascript:void(0)"><i class="ti-settings"></i> Configuración Cuenta</a>
                                </li> -->
                                <li><a href="<?php echo base_url('login/logout'); ?>"><i class="fa fa-power-off"></i> Salir</a></li>
                            </ul>
                        </li>
                        <li class="nav-small-cap text-center font-weight-bold h5">=== MENÚ ===</li>

                        <li> <a class=" waves-effect waves-dark" href="<?php echo base_url('tablero/'); ?>"
                                aria-expanded="false"><i class="ti-layout-grid2"></i><span class="hide-menu">Escritorio
                                </span></a>

                        </li>

                        <li> <a class="has-arrow waves-effect waves-dark" href="javascript:void(0)"
                                aria-expanded="false"><i class="ti-user"></i><span
                                    class="hide-menu">Estudiantes</span></a>
                            <ul aria-expanded="false" class="collapse">
                                <?php foreach ($cursos->result() as $row): ?>
                                    <li>
                                        <a
                                            href="<?php echo base_url('estudiante/index/' . $row->idCurso . '/' . $row->idParalelo); ?>">
                                            <?php echo $row->cortoCurso . ' ' . $row->nombreParalelo; ?>
                                        </a>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </li>
                        <li> <a class="has-arrow waves-effect waves-dark" href="javascript:void(0)"
                                aria-expanded="false"><i class="ti-pencil-alt"></i><span
                                    class="hide-menu">Asistencia</span></a>
                            <ul aria-expanded="false" class="collapse">
                                <?php foreach ($cursos->result() as $row): ?>
                                    <li>
                                        <a
                                            href="<?php echo base_url('asistencia/index/' . $row->idCurso . '/' . $row->idParalelo); ?>">
                                            <?php echo $row->cortoCurso . ' ' . $row->nombreParalelo; ?>
                                        </a>
                                    </li>
                                <?php endforeach; ?>
                            </ul>
                        </li>
                        <li> <a class="has-arrow waves-effect waves-dark" href="javascript:void(0)"
                                aria-expanded="false"><i class="ti-file"></i>
                                <sp class="hide-menu">Reporte</span>
                            </a>
                            <ul aria-expanded="false" class="collapse">
                                <li><a href="<?php echo base_url('reporte/'); ?>">Asistencia </a></li>
                            </ul>
                        </li>
                        <li> <a class="has-arrow waves-effect waves-dark" href="javascript:void(0)"
                                aria-expanded="false"><i class="ti-image"></i>
                                <sp class="hide-menu">Apuntes</span>
                            </a>
                            <ul aria-expanded="false" class="collapse">
                                <li><a href="<?php echo base_url('apunte/'); ?>">Apuntes </a></li>
                            </ul>
                        </li>
                        <li> <a class="has-arrow waves-effect waves-dark" href="javascript:void(0)"
                                aria-expanded="false"><i class="ti-settings"></i>
                                <sp class="hide-menu">Configuración</span>
                            </a>
                            <ul aria-expanded="false" class="collapse">
                                <li><a href="<?php echo base_url('trimestre/'); ?>">Trimestre </a></li>
                                <li><a href="<?php echo base_url('mensaje/'); ?>">Mensaje </a></li>
                            </ul>
                        </li>
                    </ul>
                </nav>
                <!-- End Sidebar navigation -->
            </div>
            <!-- End Sidebar scroll-->
        </aside>
        <!-- ============================================================== -->
        <!-- Finalizar barra lateral izquierda: estilo que puede encontrar en sidebar.scss  -->
        <!-- ============================================================== -->
        <!-- ============================================================== -->
        <!-- Page wrapper  -->
        <!-- ============================================================== -->
        <div class="page-wrapper">
            <!-- ============================================================== -->
            <!-- Container fluid  -->
            <!-- ============================================================== -->
            <div class="container-fluid">


<script>
    $(document).ready(function () {
    // Cargar datos cuando se abra el modal
    
    $('#modalPerfil').on('show.bs.modal', function () {
        //console.log($('#imgPerfil').attr('src'));
        $.ajax({
            url: "<?= base_url('usuario/getUsuario') ?>",  // Ruta del backend que devuelve los datos
            type: 'POST',
            dataType: 'json',
            success: function (data) {
                let usuario = data[0]; // Obtiene el primer objeto del array
                $('#user').val(usuario.user);
                $('#nombres').val(usuario.nombres);
                $('#primerApellido').val(usuario.primerApellido);
                $('#segundoApellido').val(usuario.segundoApellido);
                $('#cedula').val(usuario.cedula);
                let rutaImagen = "<?= base_url() ?>" + usuario.imagen;
                $('#imgPerfil').attr('src', rutaImagen);

            }
        });
    });

    // Guardar cambios en el perfil
    $('#guardarPerfil').click(function () {
    var formData = new FormData();
    //formData.append('idUsuario', $('#idUsuario').val());  // Asegúrate de tener este campo en el modal
    formData.append('user', $('#user').val());
    formData.append('pass', $('#pass').val());
    formData.append('nombres', $('#nombres').val());
    formData.append('primerApellido', $('#primerApellido').val());
    formData.append('segundoApellido', $('#segundoApellido').val());
    formData.append('cedula', $('#cedula').val());
        
    // Verifica si se ha escrito algo en la contraseña
    // var pass = $('#pass').val().trim(); // Elimina espacios
    // if (pass.length >= 4) {  // Solo agrega la contraseña si no está vacía
    //     formData.append('pass', pass);
    // }

    // Verifica si se subió una imagen nueva
    var imagen = $('#imagenPerfil')[0].files[0];
    if (imagen) {
        formData.append('imagen', imagen);
    }

    $.ajax({
        url: '<?= base_url('usuario/update') ?>',  // Ruta del backend
        type: 'POST',
        data: formData,
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (response) {
            if (response.status === 'success') {
                swal(response.message);
                swal({   
                    title: "¡Éxito!",   
                    text: response.message,   
                    timer: 3000,   
                    showConfirmButton: true 
                });
                $('#modalPerfil').modal('hide');
                //location.reload();  // Recargar la página para ver los cambios
            } else {
                swal('Error: ' + response.message);
            }
        },
        error: function (xhr, status, error) {
            //console.error("Error en la solicitud:", error);
            swal('Error en la solicitud:' + error);
        }
    });
});

$('#habilitarEdit').click(function () {
    $('#user').prop('disabled', false);
    $('#pass').prop('disabled', false);  // Habilita el campo de contraseña
    $('#nombres').prop('disabled', false);
    $('#primerApellido').prop('disabled', false);
    $('#segundoApellido').prop('disabled', false);
    $('#cedula').prop('disabled', false);
    
    $(this).hide();  // Oculta el botón después de habilitar el campo
});



});

</script>