<?php

    if(isset($_SESSION['MSG_INFO'])) {
        $show =  $_SESSION['MSG_INFO'] == 'EQUIP' ? 'show' : FALSE;      
    }

    $html = '<div class="card">';
        $html .= '<div class="card-header" id="heading4">';
            $html .= '<h5 class="mb-0">';
                $html .= '<button class="btn btn-link collapsed" data-toggle="collapse" data-target="#collapse6" aria-expanded="false" aria-controls="collapse6">';
                    $html .= '<i class="fab fa-delicious fa-lg mr-2"></i>' . $equipamiento_lg;
                $html .= '</button>';
            $html .= '</h5>';
        $html .= '</div>';

        $html .= '<div id="collapse6" class="collapse ' . $show . '" aria-labelledby="heading6" data-parent="#accordion">';
            $html .= '<div class="card-body my-3 ml-3">';
                
                //Coche externo
                if(!empty($fila["CODE_EXT"])) {

                    $res = $Schema->executeQuery('SELECT * FROM VEHICULOS_EQUIPAMIENTOS_REL WHERE CATEGORIA = ? AND VEHICULO = ?', 'ii', [0, $_SESSION['CODIGO_COCHE']]);
                    if($res->num_rows) {
                        $html .= '<ul>';
                            while($row = $res->fetch_array()) {
                                $html .= '<li><h5 class="font-weight-normal">' . ucfirst(mb_strtolower($row['EQUIPAMIENTO'], 'UTF-8')) . '</h5></li>';
                            }
                        $html .= '</ul>';
                    } else {
                        $html .= '<h5 class="font-weight-normal">' . $sin_resultados_lg . '</h5>';
                    }

                } else {
                    //Coche interno
                    $html .= '<div class="d-flex flex-wrap">';
                        $res = $con->query('SELECT * FROM VEHICULOS_EQUIPAMIENTOS_CAT');
                        while($row = $res->fetch_array()) {
                            /* <i id="' . $row['CODIGO'] . '" class="fas fa-plus mr-2 plus-minus" data-toggle="collapse" href="#cat' . $row['CODIGO'] . '" role="button" aria-expanded="false" aria-controls="cat' . $row['CODIGO'] . '"></i> */
                            $html .= '<div class="btn btn-primary mr-2 mb-3 c-pointer" >
                            <i class="fas fa-search-plus mr-2"></i>
                            <span data-toggle="modal" data-target="#modal-' . $row['CODIGO'] . '">' .  ucfirst(mb_strtolower($row['DESCRIPCION'], 'UTF-8')) . '</span></div>';


                            

                            //Modal
                            $html .= '<div class="modal fade" id="modal-' . $row['CODIGO'] . '" tabindex="-1" aria-hidden="true">';
                                $html .= '<div class="modal-dialog">';
                                    $html .= '<div class="modal-content">';
                                    $html .= '<div class="modal-header">';
                                        $html .= '<h5 class="modal-title" id="exampleModalLabel">' . ucfirst(mb_strtolower($row['DESCRIPCION'], 'UTF-8')) . '</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">';
                                        
                                        $resSwitch = $Schema->executeQuery('SELECT R.EQUIPAMIENTO,R.ALIAS,R.CATEGORIA,R.VEHICULO
                                        FROM VEHICULOS_EQUIPAMIENTOS_REL R
                                        WHERE R.CATEGORIA = ? AND R.VEHICULO = ?
                                        UNION
                                        SELECT B.DESCRIPCION AS EQUIPAMIENTO,B.ALIAS,B.CATEGORIA,NULL AS VEHICULO
                                        FROM VEHICULOS_EQUIPAMIENTOS_BASE B
                                        WHERE B.CATEGORIA = ? AND B.ALIAS NOT IN (SELECT ALIAS 
                                        FROM VEHICULOS_EQUIPAMIENTOS_REL 
                                        WHERE CATEGORIA = ? AND VEHICULO = ?)
                                        ORDER BY EQUIPAMIENTO ASC', 'iiiii', [$row['CODIGO'], $_SESSION['CODIGO_COCHE'], $row['CODIGO'], $row['CODIGO'], $_SESSION['CODIGO_COCHE']]);

                                        if($resSwitch->num_rows) {
                                            $nr = 0;
                                            while($rowSwitch = $resSwitch->fetch_array()) {
                                                $nr++;
                                                $checked = $rowSwitch['VEHICULO'] != NULL ? 'checked' : FALSE;
                                                $html .= '<div class="custom-control custom-switch div-switch">';
                                                    $html .= '<input type="checkbox" class="custom-control-input input-switch" id="switch-' . $rowSwitch['ALIAS'] . '" ' . $checked . ' value="' . $rowSwitch['CATEGORIA'] . "@" . $rowSwitch['EQUIPAMIENTO'] . '@' . $rowSwitch['ALIAS'] . '">';
                                                    $html .= '<label class="custom-control-label" for="switch-' . $rowSwitch['ALIAS'] . '">' . ucfirst(mb_strtolower($rowSwitch['EQUIPAMIENTO'], 'UTF-8')) . '</label>';
                                                $html .= '</div>';
                                            }
                                        }
                                        $html .= '<div id="divs-switchs-' . $row['ALIAS'] . '"></div>';
                                        $html .= '<div id="new-switchs-' . $row['ALIAS'] . '"></div>';


                                        //NEW EQUIP 
                                        $html .= '<div class="input-group mt-3">';
                                            $html .= '<label class="d-block w-100">' . $anadir_mas_equipamiento_lg . '</label>';
                                            $html .= '<textarea class="form-control new-textarea-' . $row['ALIAS'] . '" aria-label="With textarea"></textarea>';
                                            $html .= '<button class="btn btn-secondary rounded-0 add-new" aria-label="' . $row['CODIGO'] . '" value="' . $row['ALIAS'] . '"><i class="fas fa-check"></i></button>';
                                            $html .= '<div class="w-100 text-danger d-none invalid">
                                            ' . $campo_obligatorio_lg .'</div>';
    
                                        $html .= '</div>';


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

                    $html .= '</div>';


                    //Collapse
                    $res = $con->query('SELECT * FROM VEHICULOS_EQUIPAMIENTOS_CAT');
                    while($row = $res->fetch_array()){
                        
                        $html .= '<div class="col-12">';
                            $html .= '<div class="mb-3" id="cat' . $row['CODIGO'] . '">';
                                $html .= '<div class="">';
                                    $html .= '<ul>';
                                        $html .= '<li><h5>' . ucfirst(mb_strtolower($row['DESCRIPCION'], 'UTF-8')) . '</h5>';
                                            $html .= '<ul id="ul_' . $row['CODIGO'] . '">';
                                                $resREL = $Schema->executeQuery('SELECT B.*, R.*
                                                FROM VEHICULOS_EQUIPAMIENTOS_BASE B
                                                LEFT JOIN VEHICULOS_EQUIPAMIENTOS_REL R ON B.DESCRIPCION = R.EQUIPAMIENTO 
                                                WHERE R.VEHICULO = ? 
                                                AND B.CATEGORIA = ?
                                                ORDER BY B.DESCRIPCION ASC', 'ii', [$_SESSION['CODIGO_COCHE'], $row['CODIGO']]);
                                                
                                                while($rowREL = $resREL->fetch_array()) {
                                                    $html .= '<li class="' . $rowREL['ALIAS'] . '"><h6>' . ucfirst(mb_strtolower($rowREL['EQUIPAMIENTO'], 'UTF-8')) . '</h6></li>';
                                                }
                                                
                                            $html .= '</ul>';
                                    $html .= '</ul>';
                                $html .= '</div>';
                            $html .= '</div>';
                        $html .= '</div>';

                    }

                    /* $html .= '<div id="foo"></div>'; */
                    
                }
            $html .= '</div>';
        $html .= '</div>';


    $html .= '</div>';
        


    echo $html;

?>

<script>

    //Toggle +/- animation
    $('.plus-minus').on('click', function() {
        $(this).toggleClass('fa-plus fa-minus');
    })

    //Insert to DATA BASE
    function updateGear(gear = false, category, alias, update) {
        $.post('ajax/equipamiento.php', {gear: gear, category: category, alias: alias, update: update})
    }

    //update / delete equipamiento basico
    function flipSwitch() {
        $('.input-switch').on('click', function() {
            var update;//0 == Delete, 1 == Insert
            let value = $(this).val().split('@');//multiple valores en un input separados por @
            var category = value[0];//Categoria
            var gear = value[1];//Descripcion
            var alias = value[2];//Alias
            console.log($(this).val());
            
            if($(this).is(':checked')) {
                update = 1;
                //Generar en le listado el recientemente agregado
                $("#ul_" + category).append('<li class="' + alias + '"><h6>' + gear + '</h6></li>');
                console.log('in')
            } else {
                update = 0;
                //Eliminar del listado el recientemente agregado
                $('.' + alias).remove();
                console.log('out')
                console.log("ALIAS: " + alias);


            }
            //Llamada a las BBDD
            updateGear(gear, category, alias, update)
        })
    }
    flipSwitch();


    $('.add-new').on('click', function() {
        

        //Valores para añadir
        let id = $(this).val();//get the id
        var texto = $('.new-textarea-' + id).val();
        if(texto != '') {
            //Modificar estilos
            $(this).removeClass('btn-secondary');
            $(this).addClass('btn-success');
            $(this).html('<i class="fas fa-check-double"></i>');


            var category = $(this).attr('aria-label');
            var alias = Math.random().toString(36).substring(2, 5) + "" + Date.now();//gererar un string randmo para el alias

            //generar input
            var input = $('<div class="custom-control custom-switch div-switch" id="div-new-switch-' + alias + '">' +
                                '<input type="checkbox" class="custom-control-input input-switch" id="switch-' + alias + '" checked value="' + category + "@" + texto + '@' + alias + '">' +
                                '<label class="custom-control-label" for="switch-' + alias + '">' + texto + '</label>' + 
                            '</div>'); 
            $('#divs-switchs-' + id).append(input);
            $('.invalid').removeClass('d-block');
            $('.invalid').addClass('d-none');
            updateGear(texto, category, alias, 1)
            
            $('.new-textarea-' + id).val('');
            $('#ul_' + category).append('<li class="' + alias + '"><h6>' + texto + '</h6></li>')
            

        } else {
            $('.invalid').removeClass('d-none');
            $('.invalid').addClass('d-block');
        }
        


        $("#switch-" + alias).on('change', function() {
            $('#div-new-switch-' + alias).fadeOut(500)
            $('.' + alias).fadeOut(500);
            updateGear(false, category, alias, 0)
        })
        /* alert('texto: ' + texto + ' category: ' + category + ' alias: ' + alias) */
        
    })

    /* $('.add-new').on('click', function() {
        let id = $(this).val();//get the id
        var category = $(this).attr('aria-label');
        var alias = Math.random().toString(36).substring(2, 5) + "" + Date.now();//gererar un string randmo para el alias
        var input = $('<div class="input-group mb-3" id="div-new-equip-' + alias + '">' +
                        '<div class="custom-file">' + 
                            '<input type="text" class="form-control" id="new-e' + alias + '" placeholder="<?php echo $equipamiento_nuevo_lg; ?>">' +
                        '</div>' + 
                        '<div class="input-group-append">' + 
                            '<button type="button" class="btn btn-secondary new-gear-button" id="new-gear-button' + alias + '"><i class="fas fa-check"></i></button>' +
                        '</div>' + 
                    '</div>')
        $('#divs-' + id).append(input);


        //GEAR value
        //Update and create new switchs
        $('.new-gear-button').on('click', function(data) {
            $(this).removeClass('btn-secondary');
            $(this).addClass('btn-success');
            $(this).html('<i class="fas fa-check-double"></i>');
            $('#div-new-equip-' + alias).fadeOut(500)
            texto = $('#new-e' + alias).val();
            
            var input = $('<div class="custom-control custom-switch div-switch" id="div-new-switch-' + alias + '">' +
                            '<input type="checkbox" class="custom-control-input input-switch" id="switch-' + alias + '" checked value="' + category + "@" + texto + '@' + alias + '">' +
                            '<label class="custom-control-label" for="switch-' + alias + '">' + texto + '</label>' + 
                        '</div>'); 
            if(!$('#switch-' + alias).length) {
                $('#divs-switchs-' + id).append(input);
                $('#ul_' + category).append('<li class="' + alias + '"><h6>' + texto + '</h6></li>')
            }
            updateGear(texto, category, alias, 1)


            $("#switch-" + alias).on('change', function() {
                $('#div-new-switch-' + alias).fadeOut(500)
                updateGear(false, category, alias, 0)
            })
        })

        


        //flipSwitch()
        //alert(category)
        
    }) */

    

</script>
