<?php 
/*Este archivo lo dejo UNICAMENTE como referencia, deberíamos borrarlo una vez acabe 
 * el desarrollo de ajustes-permisos-popup. Este archivo se invocaba desde el ajax(post) 
 * al final de un archivo con el mismo nombre en la carpeta includes/components.
 * La falta de tiempo impide borrarlo a fecha  26/11/2020 ya que no puedo asegurar que falle algun elemento
 */
session_start();
$usuarioSession = $_SESSION['USUARIO'];
$grupo = $_SESSION['GRUPO'];
$contacto = $_SESSION['CONTACTO'];
$awa_session_id = $_SESSION['AWA_SESION_ID'];
include('../lg/config_vo.php');
include('../includes/conex.php');
include('../includes/eat.php');
include('../includes/historial.php');
include('../includes/functions.php');
include('../includes/esquemas.php');
include('../class/Schema.php');
include('../class/MotherCar.php');
include('../class/Static.php');
include('../class/Agenda.php');
include('../class/Rgpd.php');
include('../class/Bibliotecas.php');
include('../class/PuzzleHTML.php');
if(!isset($usuarioSession) or $awa_session_id != $awa_id){
    eatCookies();
    header('Location:../index.php');
}
if(isset($_COOKIE['usuario']) AND $_COOKIE['usuario'] != $staticUsu ){
    eatCookies();
    header('Loction:../index.php');
}
if(isset($_COOKIE['idioma'])){
    include('../lg/LG_' . $_COOKIE['idioma'] . '.php');
} else {
    include('../lg/LG_SP.php');
}

$Schema = new Schema($con);
$Agenda = new Agenda($con);
$html = '';

$usuario = Statics::SafeInput($con, $_POST['usuario']);
$rowUSU = $Schema->executeQuery('SELECT USUARIO FROM USUARIOS WHERE CONTACTO = ?', 'i', [$usuario])->fetch_array();
$usuario_tabla_usuarios = $rowUSU['USUARIO'];
$grupos = Statics::SafeInput($con, $_POST['grupos']);
$Agenda->set_codigo_usuario($usuario);
$mostrar = $Agenda->select_campo('MOSTRAR');
$permiso = Statics::SafeInput($con, $_POST['permiso']);
$modalTitle = $permiso == 0 ? '<i class="fas fa-cubes mr-2"></i>' . $permisos_de_stock_lg . ": <span class='font-weight-light'>" . $mostrar . "</span>": '<i class="fas fa-pencil-alt mr-2"></i>' . $permisos_de_acciones_lg . ": <span class='font-weight-light'>" . $mostrar . "</span>";
$modal_size = $permiso == 0 ? 'modal-xl' : 'modal-lg';




/* $html = '<div class="modal fade" id="open-modals-in-ajax" tabindex="-1" aria-hidden="true">';
    $html .= '<div class="modal-dialog ' . $modal_size . '">';
        $html .= '<div class="modal-content">'; */
            $html .= '<div class="modal-header">';
                $html .= '<h5 class="modal-title text-dark">' . $modalTitle . '</h5>';
                    $html .= '<button type="button" class="close" data-dismiss="modal" aria-label="Close">';
                        $html .= '<span aria-hidden="true">&times;</span>';
                    $html .= '</button>';
            $html .= '</div>';
            $html .= '<div class="modal-body">';
            /* $html .= $usuario; */

            //Permisos de stock == 0
            if($permiso == 0) {
                $res = $con->query("SELECT S.* 
                FROM VEHICULOS_STOCKS S
                WHERE S.ACCESO = '' 
                OR S.ACCESO IS NULL 
                OR S.ACCESO = (S.ACCESO LIKE '%*INT%' 
                OR S.ACCESO LIKE '%$" . $usuario_tabla_usuarios . "%')");
                if($res->num_rows) {
                    $html .= '<table class="table table-bordered">';
                    $html .= '<thead>';
                        $html .= '<tr>';
                            $html .= '<th scope="col">' . $stock_lg . '</th>';
                            $html .= '<th scope="col" class="text-center">' . $lectura_lg . '</th>';
                            $html .= '<th scope="col" class="text-center">' . $escritura_lg . '</th>';
                        $html .= '</tr>';
                    $html .= '</thead>';
                    $html .= '<tbody>';
                    while($row = $res->fetch_array()) {
                        $html .= '<tr>';
                            $html .= '<td>' . $row['DESCRIPCION'] . '</td>';

                            //LECTURA
                            $checked = strpos($row['ACCESO'], $usuario_tabla_usuarios . "$1") ? 'checked' : FALSE;
                            $html .= '<td class="text-center">';
                                $html .= '<div class="custom-control custom-checkbox">';
                                    $html .= '<input type="checkbox" class="custom-control-input read-write" id="escritura-' . $row['CODIGO'] . '" value="' . $row['CODIGO'] . '" aria-label="1@' . $row['ACCESO'] . '" ' . $checked . '>';
                                    $html .= '<label class="custom-control-label" for="escritura-' . $row['CODIGO'] . '"></label>';
                                $html .= '</div>';
                            $html .= '</td>';

                            //ESCRITURA
                            $checked = strpos($row['ACCESO'], $usuario_tabla_usuarios . "$2") ? 'checked' : FALSE;
                            $html .= '<td class="text-center">';
                                $html .= '<div class="custom-control custom-checkbox">';
                                    $html .= '<input type="checkbox" class="custom-control-input read-write" id="lectura-' . $row['CODIGO'] . '" value="' . $row['CODIGO'] . '" aria-label="2@' . $row['ACCESO'] . '" ' . $checked . '>';
                                    $html .= '<label class="custom-control-label" for="lectura-' . $row['CODIGO'] . '"></label>';
                                $html .= '</div>';
                            $html .= '</td>';
                            
                        $html .= '</tr>';
                    }
                    $html .= '</tbody>';
                $html .= '</table>';
                } else {
                    $html .= $sin_resultados_lg;
                }
            } else {
                //Permisos de acciones == 1
                $res = $Schema->executeQuery("SELECT L.*, L.DESCRIPCION_$lg AS DESCRIPCION_LG, P.* 
                FROM VEHICULOS_LITERALES L
                LEFT JOIN VEHICULOS_PERMISOS P ON P.ACCION = L.CODIGO AND P.USUARIO = ?
                LEFT JOIN USUARIOS U ON U.CONTACTO = P.USUARIO
                WHERE L.TIPO = ? AND L.PADRE = ?", 'isi', [$usuario, 'TIP_PER', 0]);
                while($row = $res->fetch_array()) {
                    $checked = !empty($row['USUARIO']) ? 'checked' : FALSE;
                    $html .= '<div class="pl-3 mb-2">';
                        $html .= '<div class="custom-control custom-switch">';
                            $html .= '<input type="checkbox" class="custom-control-input main-switch" id="' . $row['CODIGO'] . '-' . $row['TIPO'] . '" ' . $checked . '>';
                            $html .= '<label class="custom-control-label" for="' . $row['CODIGO'] . '-' . $row['TIPO'] . '">' . $row['DESCRIPCION_LG'] . '</label>';
                        $html .= '</div>';
                        $resSUB = $Schema->executeQuery("SELECT L.*, L.DESCRIPCION_$lg AS DESCRIPCION_LG, P.* 
                        FROM VEHICULOS_LITERALES L
                        LEFT JOIN VEHICULOS_PERMISOS P ON P.ACCION = L.CODIGO AND P.USUARIO = ?
                        LEFT JOIN USUARIOS U ON U.CONTACTO = P.USUARIO
                        WHERE L.TIPO = ? AND L.PADRE = ?", 'isi', [$usuario, 'TIP_PER', $row['CODIGO']]);
                        while($rowSUB = $resSUB->fetch_array()) {
                            $checked2 = !empty($rowSUB['USUARIO']) ? 'checked' : FALSE;
                            /* $checkedSUB = $checked == FALSE ? $checked2 : $checked; */
                            $border_section = $checked ? 'border-primary' : FALSE;
                            $html .= '<div class="border-left ' . $border_section . ' ml-1 pl-4">';
                                $html .= '<div class="custom-control custom-switch ">';
                                    $html .= '<input type="checkbox" class="custom-control-input second secondary-switch-' . $row['CODIGO'] . '" id="' . $rowSUB['CODIGO'] . '-' . $rowSUB['TIPO'] . '" value="' . $rowSUB['CODIGO'] . '" ' . $checked2 . ' aria-label="' . $row['CODIGO'] . '">';
                                    $html .= '<label class="custom-control-label" for="' . $rowSUB['CODIGO'] . '-' . $rowSUB['TIPO'] . '">' . $rowSUB['DESCRIPCION_LG'] . '</label>';
                                $html .= '</div>';
                            $html .= '</div>';
                        }
                    $html .= '</div>';
                }
                $html .= '<div id="foo-to-delete"></div>';
            }
            $html .= '</div>';
            $html .= '<div class="modal-footer">';
                $html .= '<button type="button" class="btn btn-primary" data-dismiss="modal">' . $guardar_cerrar_lg . '</button>';
            $html .= '</div>';
/*         $html .= '</div>';
    $html .= '</div>';
$html .= '</div>'; */

echo $html;

?>

<script>
    var usuario = <?php echo $usuario; ?>;//codigo del usuario

    //Permisos stock
    $('.read-write').on('click', function() {
        var value = $(this).val();//Codigo del stock
        var aria = $(this).attr('aria-label').split('@');
        var tipo = aria[0];//tipo de permiso
        var acceso = aria[1];//acceso OBSOLETO!!
        $(this).toggleClass('is-valid');

        //Update or downgrade
        if($(this).is(':checked')) {
            var update = 1;
        } else {
            var update = 0;
        }
        $.post('ajax/ajustes-permisos-usuarios-update.php', {permisos: 0, usuario: usuario, value: value, tipo: tipo, acceso: acceso, update: update})
        console.log("Value: " + value + " Tipo de permiso: " + tipo + " Acceso: " + acceso + " Update: " + update);
    })


    //Check all and update
    $('.main-switch').on('change', function () {
        var update;

        //get id of the main and manipulate the secondary-switch-[id of the main] class
        var getId = $(this).attr('id').split('-');
        var id = getId[0];

        if($(this).is(':checked')) {
            update = 1;
            $(this).addClass('is-valid');
            $('.secondary-switch-' + id).addClass('is-valid');
            $('.secondary-switch-' + id).prop('checked', true);
            /* second = $('.secondary-switch-' + id).map(function () {return this.value;}).get().join(",") */
        } else {
            update = 0;
            second = false; 
            $(this).removeClass('is-valid');
            $('.secondary-switch-' + id).removeClass('is-valid');
            $('.secondary-switch-' + id).prop('checked', false);
        }

        $.post('ajax/ajustes-permisos-usuarios-update.php', {permisos: 1, usuario: usuario, main: id, update: update}, function(data) {
            $('#foo-to-delete').html(data);
        })
        
    })

    var second = [];
    $('.second').on('change', function() {
        var value = $(this).val();
        /* var main = $(this).attr("aria-label"); */
        permisos = 2;


        if($(this).is(':checked')) {
            update = 1;
            $(this).addClass('is-valid');
            /* second.push(value); */
        } else {
            update = 0;
            $(this).removeClass('is-valid');
            /* second.splice($.inArray(value, second), 1); */
        }
        /* if(second.length == $('.secondary-switch-' + main).length) {
            permisos = 1;
            $('.from-second-' + main).addClass('is-valid');
            $('.from-second-' + main).prop('checked', true);
        } else {
            permisos = 2;
            $('.from-second-' + main).removeClass('is-valid');
            $('.from-second-' + main).prop('checked', false);
            
        } */
        console.log();


        $.post('ajax/ajustes-permisos-usuarios-update.php', {permisos: permisos, usuario: usuario, second: value, update: update}, function(data) {
            $('#foo-to-delete').html(data);
        })
    })
</script>