<?php 
/** Gestión de los modales(popups) de los botones permisos_stock y permisos_acciones
 *  Este archivo fue basado en ajax/ajustes-permisos-perfiles.php que se deja como referencia. 
 */
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');

$cookieUser = filter_input(INPUT_COOKIE, 'usuario') ?? null; 
$cookieIdioma = filter_input(INPUT_COOKIE, 'idioma') ?? null; 
if((!isset($usuarioSession) or $awa_session_id != $awa_id) or (isset($cookieUser) AND $cookieUser != $staticUsu )){
    eatCookies();
    header('Location:../index.php');}
empty($cookieIdioma)?
    include('../lg/LG_' . $cookieIdioma . '.php'):
    include('../lg/LG_SP.php');


$codigogrupo = (int)filter_input(INPUT_POST, 'codigogrupo') ?? null;
$perfil      = filter_input(INPUT_POST, 'nombreperfil') ?? null;
$permiso     = filter_input(INPUT_POST, 'tipopermiso') ?? null; // stock (antes 0 ) o acciones (antes 1)

$Schema = new Schema($con);
$Agenda = new Agenda($con);
$html = '';
$modalTitle = $permiso === "stock" ? '<i class="fas fa-cubes mr-2"></i>' . $permisos_de_stock_lg . ": <span class='font-weight-light'>" . $perfil . "</span>": '<i class="fas fa-pencil-alt mr-2"></i>' . $permisos_de_acciones_lg . ": <span class='font-weight-light'>" . $perfil . "</span>";
$modal_size = $permiso === "stock" ? 'modal-xl' : 'modal-lg';

$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">';

if($permiso === "stock") {
    $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 '%$" . $codigogrupo . "%')");
    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
                $checkedlectura = strpos($row['ACCESO'], $codigogrupo . "$1") ? 'checked' : FALSE;
                $html .= '<td class="text-center">';
                    $html .= '<div class="custom-control custom-checkbox">';
                        $html .= '<input type="checkbox" class="custom-control-input modal_permisos_stock" id="escritura-' . $row['CODIGO'] . '" value="' . $row['CODIGO'] . '" aria-label="1@' . $row['ACCESO'] . '" ' . $checkedlectura . '>';
                        $html .= '<label class="custom-control-label" for="escritura-' . $row['CODIGO'] . '"></label>';
                    $html .= '</div>';
                $html .= '</td>';

                //ESCRITURA
                $checkedescritura = strpos($row['ACCESO'], $codigogrupo . "$2") ? 'checked' : FALSE;
                $html .= '<td class="text-center">';
                    $html .= '<div class="custom-control custom-checkbox">';
                        $html .= '<input type="checkbox" class="custom-control-input modal_permisos_stock" id="lectura-' . $row['CODIGO'] . '" value="' . $row['CODIGO'] . '" aria-label="2@' . $row['ACCESO'] . '" ' . $checkedescritura . '>';
                        $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;
    }
} elseif($permiso === "acciones") {
    $query = " SELECT DISTINCT VEHICULOS_LITERALES.CODIGO, 
                      VEHICULOS_LITERALES.TIPO,
                      VEHICULOS_LITERALES.PADRE,
                      VEHICULOS_LITERALES.DESCRIPCION_SP AS DESCRIPCION_LG, 
                      VEHICULOS_PERMISOS.ACCION AS ID_PERMISOS, 
                      VEHICULOS_PERMISOS.CODIGO AS COD_PERMISOS
                FROM  VEHICULOS_LITERALES LEFT JOIN VEHICULOS_PERMISOS
                    ON  VEHICULOS_PERMISOS.ACCION = VEHICULOS_LITERALES.CODIGO 
                    AND VEHICULOS_PERMISOS.CODIGO = ? 
                WHERE   VEHICULOS_LITERALES.TIPO = ? 
                    AND VEHICULOS_LITERALES.PADRE = ? ; ";
    
    //Se rellenan los permisos de acciones "Padres"
    $res = $Schema->executeQuery( $query , 'isi', [$codigogrupo, "TIP_PER", 0]);
    while($row = $res->fetch_array()) {
        $checked = !empty($row['COD_PERMISOS']) ? 'checked' : FALSE;
        $html .= '<div class="pl-3 mb-2">';
            $html .= '<div class="custom-control custom-switch">';
                $html .= '<input type="checkbox" class="custom-control-input modal_permisos_acciones" id="' . $row['CODIGO'] . '-' . $row['TIPO'] . '" ' . $checked . '>';
                $html .= '<label class="custom-control-label" for="' . $row['CODIGO'] . '-' . $row['TIPO'] . '">' . $row['DESCRIPCION_LG'] . '</label>';
            $html .= '</div>';
        //Se rellena para cada uno sus respectivos permisos "Hijos"
        $resSUB = $Schema->executeQuery( $query ,'isi', [ $codigogrupo, "TIP_PER", $row['CODIGO']]);
        //Se rellenan los permisos de acciones "Hijos"
        while($rowSUB = $resSUB->fetch_array()) {
            $checked2 = !empty($rowSUB['COD_PERMISOS']) ? 'checked' : FALSE;
            $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  modal_permisos_acciones 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>';
}else{
    $html .= $sin_resultados_lg;
}
$html .= '</div>';

//$html .= '<div class="modal-footer">';
//$html .=    '<button type="button" class="btn btn-primary" data-dismiss="modal">' . $guardar_cerrar_lg . '</button>';
//$html .= '</div>';

echo $html;

?>

<script>
    //Permisos stock
    $('.modal_permisos_stock').on('click', function() {
        var aria = $(this).attr('aria-label').split('@');
        var tipo = aria[0];//tipo de permiso
        $(this).toggleClass('is-valid');
        $.post(
                'ajax/ajustes-permisos-usuarios-update.php', 
                {   permisos: "stock", 
                    codperfil: <?= $codigogrupo ?>,
                    value: $(this).val(), //Codigo del stock
                    tipo: tipo, //Identificador de la casilla: 1 lectura, 2 escritura (tipo int)
                    update: ($(this).is(':checked')) ? 1 : 0 //1:Marcado, necesario para multiples pulsaciones
                }
        );
        //console.log("Value: " + value + " Tipo de permiso: " + tipo + " Acceso: " + acceso + " Update: " + update);
    });

    //Permisos acciones
    $('.modal_permisos_acciones').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);
        } else {
            update = 0;
            $(this).removeClass('is-valid');
            $('.secondary-switch-' + id).removeClass('is-valid');
            $('.secondary-switch-' + id).prop('checked', false);
        }

        $.post('ajax/ajustes-permisos-usuarios-update.php',
                {   permisos: "acciones", 
                    codperfil: <?= $codigogrupo ?>,
                    padre : id,
                    update: update
        }, function(data) {
            $('#foo-to-delete').html(data);
        });
    });

    //Funcionalidad adicional para permisos de acciones "Hijos"
    $('.second').on('change', function() {
        if($(this).is(':checked')){
            update = 1; 
            $(this).addClass('is-valid');
        } else {
            update = 0;
            $(this).removeClass('is-valid');
        }

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