<?php
    session_start();
    $usuarioSession = $_SESSION['USUARIO'];
    $grupo = $_SESSION['GRUPO'];
    $contacto = $_SESSION['CONTACTO'];
    $awa_session_id = $_SESSION['AWA_SESION_ID'];
    include('../includes/conex.php');
    include('../includes/eat.php');
    include('../includes/functions.php');
    include('../lg/config_vo.php');
    include('../class/Schema.php');
    include('../class/MotherCar.php');
    include('../class/Static.php');
    include('../class/Permisos.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');
    }
    $Permisos = new Permisos($con);

    
    $Schema = new Schema($con);
    $INT = "#*INT$";
    $GRUPO_CONDICION = "#$grupo$";
    $USUARIO_SESSION = "#$usuarioSession$";
    $conditions = '';
    $type = 'iisis';
    $values = [1, 1, 'VO', 0, 'STK'];


    if(!empty($_REQUEST['marca'])) {
        $marca = Statics::SafeInput($con, $_REQUEST['marca']);
        $conditions .= ' AND V.MARCA = ?';
        $type .= 'i';
        array_push($values, $marca);
        $_SESSION['MARCA_FILTRO'] = $marca;
    }
    if(!empty($_REQUEST['modelo'])) {
        $modelo = Statics::SafeInput($con, $_REQUEST['modelo']);
        $conditions .= ' AND V.MODELO = ?';
        $type .= 'i';
        array_push($values, $modelo);
        $_SESSION['MODELO_FILTRO'] = $modelo;
    }
    if(!empty($_REQUEST['combustible'])) {
        $combustible = Statics::SafeInput($con, $_REQUEST['combustible']);
        $conditions .= ' AND V.COMBUSTIBLE = ?';
        $type .= 'i';
        array_push($values, $combustible);
        $_SESSION['COMBUSTIBLE_FILTRO'] = $combustible;
    }
    if(!empty($_REQUEST['cambio'])) {
        $cambio = Statics::SafeInput($con, $_REQUEST['cambio']);
        $conditions .= ' AND V.CAJACAMBIOS = ?';
        $type .= 'i';
        array_push($values, $cambio);
        $_SESSION['CAMBIO_FILTRO'] = $cambio;
    }
    if(!empty($_REQUEST['stock'])) {
        $stock = Statics::SafeInput($con, $_REQUEST['stock']);
        $conditions .= ' AND V.STOCK = ?';
        $type .= 'i';
        array_push($values, $stock);
        $_SESSION['STOCK_FILTRO'] = $stock;
    }
    if(!empty($_REQUEST['year_min']) || !empty($_REQUEST['year_max'])) {
        $year_min = empty($_REQUEST['year_min']) ? NULL : Statics::SafeInput($con, $_REQUEST['year_min']);
        $year_max = Statics::SafeInput($con, $_REQUEST['year_max']);
        $conditions .= ' AND V.ANO_FAB BETWEEN ? AND ?';
        $type .= 'ii';
        array_push($values, $year_min);
        array_push($values, $year_max);
    }
    if(!empty($_REQUEST['precio_max'])) {
        $precio_min = Statics::SafeInput($con, $_REQUEST['precio_min']);
        $precio_max = Statics::SafeInput($con, $_REQUEST['precio_max']);
        $conditions .= ' AND V.VENTA_TOTAL BETWEEN ? AND ? ';
        $type .= 'ii';
        array_push($values, $precio_min);
        array_push($values, $precio_max);
    }
    if(!empty($_REQUEST['km_max'])) {
        if(!empty($_REQUEST['km_min'])) {
            $km_min = Statics::SafeInput($con, $_REQUEST['km_min']);
        } else {
            $km_min = 0;
        }
        $km_max = Statics::SafeInput($con, $_REQUEST['km_max']);
        $conditions .= ' AND V.KM BETWEEN ? AND ? ';
        $type .= 'ii';
        array_push($values, $km_min);
        array_push($values, $km_max);
    }
    if(!empty($_REQUEST['reservados'])) {
        $conditions .= ' AND V.RESERVA IS NOT NULL';
    }
    
    $ESQUEMA = $Schema->select_esquema_o_esquema_estructura(TRUE); 
    $GRUPO = $Schema->select_esquema_o_esquema_estructura(); 
    $GRUPOE_TIPO = $Schema->select_esquema_estructura_valores('TIPO',$ESQUEMA);

    $LISTA = $Schema->select_esquema_estructura_valores('TIPO', $ESQUEMA, 'LISTA');
    $sql_codigo_etiqueta = "SELECT CODIGO FROM ETIQUETAS WHERE GRUPO = $LISTA AND DESCRIPCION = 'FOTO'";
    $res_codigo_etiqueta = $con->query($sql_codigo_etiqueta);
    $row_codigo_etiqueta = $res_codigo_etiqueta->fetch_array(); 
    $ETIQUETA = $row_codigo_etiqueta['CODIGO'];
    $GRUPOE_PUBLICABLE = $Schema->select_esquema_estructura_valores('PUBLICABLE', $ESQUEMA);

    
    
    


    $sql = "SELECT DISTINCT V.CODIGO AS CODIGO, V.ALTA, V.IDCAR, V.MOSTRAR, V.KM, M.DESCRIPCION AS MARCAS, MO.DESCRIPCION AS MODELOS, V.RESERVA, V.MOSTRAR, V.MATRICULA, V.ANO_FAB, V.VENTA_TOTAL, V.UBIC_DIRECCION, MU.LINK, V.MATRICULACION, V.BASTIDOR,
    L1.DESCRIPCION_$lg AS DESCRIPCION_LG1, 
    L2.DESCRIPCION_$lg AS DESCRIPCION_LG2,
    L3.DESCRIPCION_$lg AS DESCRIPCION_LG3,
    L3.EXTRA1 AS EXTRA_COLOR_PRINCIPAL
    FROM (((((((VEHICULOS V
    INNER JOIN VEHICULOS_STOCKS S ON V.STOCK = S.CODIGO)
    INNER JOIN VEHICULOS_MARCAS M ON M.CODIGO = V.MARCA)
    INNER JOIN VEHICULOS_MODELOS MO ON MO.CODIGO = V.MODELO)
    LEFT JOIN VEHICULOS_LITERALES L1 ON L1.CODIGO = V.COMBUSTIBLE AND L1.TIPO = 'TIP_COM')
    LEFT JOIN VEHICULOS_LITERALES L2 ON L2.CODIGO = V.CAJACAMBIOS AND L2.TIPO = 'TIP_CAJ')
    LEFT JOIN VEHICULOS_LITERALES L3 ON L3.CODIGO = V.COLOR_PRINCIPAL AND L3.TIPO = 'COL_PRI')
    LEFT JOIN VEHICULOS_MULTIMEDIA_LINKS MU ON MU.VEHICULO = V.CODIGO AND MU.ORDEN = ?)
    WHERE V.ACTIVO = ?
    AND V.TIPO = ?
    AND V.PAPELERA = ?
    AND V.ESTADO = ?
    AND (S.ACCESO IS NULL OR S.ACCESO LIKE '%$INT%' OR S.ACCESO LIKE '%$GRUPO_CONDICION%' OR S.ACCESO LIKE '%$USUARIO_SESSION%')
    $conditions";
    $nr = 0;
    $res = $Schema->executeQuery($sql, $type, $values);
    $ver_permiso = $Permisos->permisosACC(13, $_SESSION['GRUPO']) ? TRUE : FALSE;
    
    $html = '<div class="table-responsive">';
        $html .= '<table class="table table-hover" id="table-listado-vehiculos">';
            $html .= '<thead>';
                $html .= '<tr>';
                    $html .= '<th scope="col" class="border-top-0"></th>';
                    $html .= '<th scope="col" class="border-top-0">' . $marca_lg . '</th>';
                    $html .= '<th scope="col" class="border-top-0">' . $modelo_lg . '</th>';
                    $html .= '<th scope="col" class="d-none d-md-table-cell border-top-0">' . $year_lg . '</th>';
                    $html .= '<th scope="col" class="d-none d-md-table-cell border-top-0">' . $matricula_lg . '</th>';
                    $html .= '<th scope="col" class="d-none d-md-table-cell border-top-0">' . $km_lg . '</th>';
                    $html .= '<th scope="col" class="d-none d-md-table-cell border-top-0">' . $combustible_lg . '</th>';
                    $html .= '<th scope="col" class="d-none d-md-table-cell border-top-0">' . $cambio_lg . '</th>';
                    $html .= '<th scope="col" class="border-top-0">' . $precio_lg . '</th>';
                    $html .= '<th scope="col" class="border-top-0"></th>';
                $html .= '</tr>';
            $html .= '</thead>';
            $html .= '<tbody>';
                while($row = $res->fetch_array()) {
                    if(Statics::DateDiff($row['ALTA']) > 90) {
                        $color_type = 'text-danger';
                    } elseif(Statics::DateDiff($row['ALTA']) < 60) {
                        $color_type = 'text-success';
                    } else {
                        $color_type = 'text-warning';
                    }
                    $idcar = $_SESSION['control_click'] == 1 ? "resultados-editar.php?idCAR=" . $row['CODIGO'] : "resultados-ficha.php?idCAR=" . $row['CODIGO']; 
                    $html .= '<tr class="c-pointer" data-href="' . $idcar . '">';
                        $img_style = 'class="w-100 rounded img-fit"';
                        $td_style = 'border-top-0 border-bottom text-center';
                        $html .= '<td class="' . $td_style . '"><a>';
                            if(!empty($row['LINK'])) {
                                $html .= url_exists($row['LINK']) ? '<div class="thumbnail-50 overflow-hidden zoom"><img src="' . $row['LINK'] . '" ' . $img_style . '></div>' : '<div class="text-center"><i class="far fa-image fa-3x text-muted"></i></div>';
                            } else {
                                $sql2 = "SELECT E.CLAVE, E.NOMBRE, E.SUFIJO, E.PARTES, E.POS
                                FROM BIBLIOTECA_ELEMENTOS E INNER JOIN BIBLIOTECA_ETIQUETAS T1 ON E.CLAVE = T1.CLAVE
                                INNER JOIN BIBLIOTECA_ETIQUETAS T2 ON E.CLAVE = T2.CLAVE
                                INNER JOIN BIBLIOTECA_ETIQUETAS T3 ON E.CLAVE = T3.CLAVE
                                WHERE T1.ESQUEMA = ? AND T1.GRUPOE = ? AND T1.ETIQUETA = ?
                                AND T2.ESQUEMA = ? AND T2.GRUPOE = ? AND T2.ETIQUETA = ?
                                AND T3.ESQUEMA = ? AND T3.GRUPOE = ? AND T3.ETIQUETA = ?
                                AND E.PAPELERA = ?
                                AND E.CLAVE NOT IN (SELECT DOCUMENTO FROM VEHICULOS_TASACIONES_DOCS) ORDER BY E.POS ASC";
                                $res2 = $Schema->executeQuery($sql2, 'iiiiiiiiii', [$ESQUEMA, $GRUPO, $row['CODIGO'], $ESQUEMA, $GRUPOE_TIPO, $ETIQUETA, $ESQUEMA, $GRUPOE_PUBLICABLE, 1, 0]);
                                if($res2->num_rows) {
                                    $row2 = $res2->fetch_array();
                                    if(file_exists("../img/thumbnail/" . $row['CODIGO'])) {
                                        $html .= '<div class="thumbnail-50 overflow-hidden zoom"><img src="img/thumbnail/' . $row['CODIGO'] . '/' . $row2['NOMBRE'] . '" ' . $img_style . '></div>';
                                    } else {
                                        mkdir("../img/thumbnail/" .  $row['CODIGO']);
                                        $Schema->create_file("../img/thumbnail/" .  $row['CODIGO'] . "/" . $row2['NOMBRE'], $row2['PARTES'], $row2['SUFIJO'], $row2['CLAVE']);
                                        $html .= '<div class="thumbnail-50 overflow-hidden zoom"><img src="img/thumbnail/' . $row['CODIGO'] . '/' . $row2['NOMBRE'] . '" ' . $img_style . '></div>';
                                    }
                                } else {
                                    $html .= '<div class="text-center"><i class="far fa-image fa-3x text-muted"></i></div>';
                                }
                            }
                        $html .= '</a></td>';
                        $html .= '<td class="' . $td_style . '"><div class="mt-3 text-left">' . $row['MARCAS'] . '</div></td>';
                        $html .= '<td class="' . $td_style . '"><div class="mt-3 text-left">' . $row['MODELOS'] . '</div></td>';
                        $html .= '<td class="' . $td_style . ' d-none d-md-table-cell"><div class="mt-3 text-left">' . $row['ANO_FAB'] . '</div></td>';
                        $html .= '<td class="' . $td_style . ' d-none d-md-table-cell"><div class="mt-3 text-left">' . $row['MATRICULA'] . '</div></td>';
                        $km = !empty($row['KM']) ? $row['KM'] : 0;
                        $html .= '<td class="' . $td_style . ' d-none d-md-table-cell"><div class="mt-3 text-left">' . $km . '</div></td>';
                        $html .= '<td class="' . $td_style . ' d-none d-md-table-cell"><div class="mt-3 text-left">' . $row['DESCRIPCION_LG1'] . '</div></td>';
                        $html .= '<td class="' . $td_style . ' d-none d-md-table-cell"><div class="mt-3 text-left">' . $row['DESCRIPCION_LG2'] . '</div></td>';
                        $html .= '<td class="' . $td_style . '"><div class="mt-3 text-left">' . number_format($row['VENTA_TOTAL'], 2, ',', ',') . '</div></td>';
                        $html .= '<td class="' . $td_style . '">';
                            $html .= '<div class="d-flex mt-3 text-muted">';
                                $ubicacion = $row['UBIC_DIRECCION'] ? $row['UBIC_DIRECCION'] : $sin_asignar_lg;
                                $html .= '<span class="d-none">' . $row['IDCAR'] . '</span>';
                                $html .= "<span class='" . $color_type . "'>" . Statics::DateDiff($row['ALTA']) . '</span>';
                            $html .= '</div>';
                        $html .= '</td>';
                    $html .= '</tr>';
                }
                
            $html .= '</tbody>';
        $html .= '</table>';
    $html .= '</div>';

    echo $html;

    function url_exists($url) {
        return curl_init($url) !== false;
    } 

    
?>
<script>


$('#table-listado-vehiculos tbody').on('click', 'tr', function() {
    var hrefs = $(this).data('href');
    window.location.href= hrefs;
})


</script>
