<?php
    class Statics {
        public function SafeInput($con, $item) {
            $item = mysqli_real_escape_string($con, $item);
            $item = htmlspecialchars($item);
            return $item;
        }


        //SQLSRV dosen´t support mysqli function for sanitize, so use this
        public static function safe($input) {
            $input = strip_tags($input);
            $input = htmlspecialchars($input);
            $input = filter_var($input, FILTER_SANITIZE_STRING);
            return $input;
        }

        public static function delete_files($folder) {

            $files = glob($folder . '*', GLOB_MARK);

            foreach($files as $file) {
                unlink($file);
            }
            rmdir($folder);
            
        }

        public static function get_id_unico(){
            return date( "YmdHis" ) . sprintf( "%04d", rand( 0, 9999 ) );
        }

        public static function get_contadores($con, $codigo) {
            $sql = "SELECT PREFIJO,CONTADORSIG,SUFIJO,MASCARA FROM CONTADORES WHERE CODIGO = '$codigo'";
            $res = $con->query($sql);
            $fila = $res->fetch_array();
            $mascara = str_pad($fila['CONTADORSIG'],strlen($fila['MASCARA']),0,STR_PAD_LEFT);
            $contador = $fila['PREFIJO'].$mascara;
            $contsig = $fila['CONTADORSIG'] + 1;
            $sql = "UPDATE CONTADORES SET CONTADORSIG = $contsig WHERE CODIGO = '$codigo'";
            $con->query($sql);

            return $contador;
        }

        public static function add_trace_history ($con, $usuario, $codigo_vehiculo, $accion, $detalle = NULL, $documento = NULL, $contacto = NULL) {
            date_default_timezone_set('Europe/Madrid');
            $date = date('Y-m-d H:i:s');

            $web = 1;
            $ordenador = gethostname() . "(WEB)";
            $detalle = $detalle ? $detalle : '';
            $documento = $documento ? $documento : '';
            $contacto = $contacto ? $contacto : 0;
            
            $stmt = $con->prepare('SELECT FECHA FROM VEHICULOS_HISTORIAL WHERE VEHICULO = ? AND FECHA = ?');
            $stmt->bind_param('is', $codigo_vehiculo, $date);
            $stmt->execute();
            $res = $stmt->get_result();
            if($res->num_rows > 0) {
                $fecha = $res->fetch_array();
                $date = date('Y-m-d H:i:s', strtotime('+1 seconds'));
            }

            $sql = 'INSERT INTO VEHICULOS_HISTORIAL(VEHICULO, USUARIO, FECHA, ACCION, DETALLE, DOCUMENTO, CONTACTO, WEB, ORDENADOR) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)';
            $stmt = $con->prepare($sql);
            $stmt->bind_param('ississiis', $codigo_vehiculo, $usuario, $date, $accion, $detalle, $documento, $contacto, $web, $ordenador);
            $stmt->execute();
        }


        

    
    }


    class Schema {
        private $con;

        public function __construct($con, $database = FALSE) {
            $this->con = $con;
            if($database) {
                $this->database = $database;
            }
        }

        public function executeQuery($sql, $types = null, $params = null) {
            $stmt = $this->con->prepare($sql);
            $stmt->bind_param($types, ...$params);

            if(!$stmt->execute()) return false;
            return $stmt->get_result();
        }

        public function select_esquema_o_esquema_estructura ($codigo_esquema = FALSE) {
            $sqlEsq = "SELECT CODIGO FROM ESQUEMAS WHERE ALIAS = 'DOC_VEHICULO'";
            $resEsq = $this->con->query($sqlEsq);
            $filaEsq = $resEsq->fetch_array();
            $sqlEsq2 = "SELECT CODIGO FROM ESQUEMAS_ESTRUCTURA WHERE ESQUEMA = " . $filaEsq['CODIGO'] . " AND ALIAS = 'VEHICULO'";
            $resEsq2 = $this->con->query($sqlEsq2);
            $filaEsq2 = $resEsq2->fetch_array();

            return $codigo_esquema ? $filaEsq['CODIGO'] : $filaEsq2['CODIGO'];
        }
        
        public function select_esquema_estructura_valores ($alias, $esquema, $campo = FALSE) {
            $sql = "SELECT * FROM ESQUEMAS_ESTRUCTURA WHERE ESQUEMA = $esquema AND ALIAS = '$alias'";
            $res = $this->con->query($sql);
            $fila = $res->fetch_array();
            $campo = $campo ? $campo : 'CODIGO';

            return $fila[$campo];
        }

        public function create_file ($tmp_file, $values, $sufijo, $clave) {
            //$tmp_file = archivo temporal
            //$values = son las partes que se reciben de fuera
            //$sufijo = el codigo que de la tabla
            if(file_exists($tmp_file))
            {
                unlink($tmp_file);
            }
            $create_img = fopen($tmp_file,'a');
            for($i = 1; $i <= $values; $i++)
            {
                $sqlPartes = "SELECT FICHERO
                            FROM FICHEROS_$sufijo 
                            WHERE CLAVE = " . $clave . " 
                            AND PARTE = $i
                            AND VERSION = '0'";
                $resPartes = $this->con->query($sqlPartes);
                $filaPartes = $resPartes->fetch_array();
                $img = fwrite($create_img,$filaPartes['FICHERO']);
            }
            fclose($create_img);
            
            return TRUE; 
        }
    }

    class Bibliotecas {

        private $con; 

        public function __construct($con) {
            $this->con = $con;
        }

        public function select_campo_tabla_parametros ($codigo, $campo) {
            $Schema = new Schema($this->con);
            $sql = "SELECT $campo FROM PARAMETROS WHERE CODIGO = ?"; 
            $res = $Schema->executeQuery($sql, 's', [$codigo]);
            $row = $res->fetch_array();


            return $row[$campo];
        }

    }


    class MotherCar {
        private $con;
        private $nr_1 = 1;
        private $nr_2 = 2;
        private $tipo = 'VO';

        private $codigo_vehiculo_tabla_vehiculos;
        private $usuario_session;
        private $id_car;
        private $marca_tabla_vehiculos;
        private $modelo_tabla_vehiculos;
        private $version_tabla_vehiculos;
        private $mostrar_tabla_vehiculos;
        private $matricula_tabla_vehiculos;
        private $bastidor_tabla_vehiculos;
        private $activo_tabla_vehiculos = 1;
        private $combustible;
        private $carroceria;
        private $km;
        private $cajacambios;
        private $matriculacion;
        private $color_principal_literal;
        private $color_principal;
        private $color_comercial;
        private $ano_fabricacion ;
        private $papelera = 0;
        private $garantia;
        private $itv_ultima;
        private $precio_venta;
        private $venta_total_sin_dto;
        private $venta_total;
        private $venta_dto_imp;
        private $venta_dto_prc;
        private $venta_base;
        private $venta_tipo_iva;
        private $venta_minimo;
        private $precio_compra;
        private $precio_compra_total;
        private $precio_compra_base;
        private $compra_tipo_iva;
        private $potencia;
        private $estado;
        private $itv_proxima;
        private $velocidades;
        private $llaves;
        private $codigo_radio;
        private $codigo_navegador;
        private $importacion;
        private $otros_equip;
        private $reserva;
        private $distintivo_ambiental;
        private $num_not;
        private $mantenimiento_sellado;
        private $tipo_seguro;
        private $rebu;
        private $motor_cc;
        private $alta;
        private $baja;
        private $destacado_venta_vo;
        private $ubic_direccion;
        private $eurotax;
        private $stock;
        private $ubic_poblacion;
        private $ubic_provincia;
        private $procedencia;
        private $notas;
        private $importacion_excel;
        private $manual;
        private $libro_mant;
        private $gastos_gestion;
        private $tipo_precios_extra;
        private $base_precios_extra;
        private $dto_imp_precios_extra;
        private $dto_prc_precios_extra;
        private $total_sin_dto_precios_extra;
        private $total_precios_extra;
        private $limite_precios_extra;
        private $code_ext;

        public function __construct($con) {
            $this->con = $con;
        }

        public function set_codigo_vehiculo_tabla_vehiculos ($codigo_vehiculo_tabla_vehiculos) {
            $this->codigo_vehiculo_tabla_vehiculos = $codigo_vehiculo_tabla_vehiculos;
            return $this;
        }
        public function get_codigo_vehiculo_tabla_vehiculos () {
            return $this->codigo_vehiculo_tabla_vehiculos;
        }
        public function set_usuario_session ($usuario_session) {
            $this->usuario_session = $usuario_session;
            return $this;
        }
        public function get_usuario_session () {
            return $this->usuario_session;
        }
        public function set_tipo ($tipo) {
            $this->tipo = $tipo;
            return $this;
        }
        public function get_tipo () {
            return $this->tipo;
        }
        public function set_id_car ($id_car) {
            $this->id_car = $id_car;
            return $this;
        }
        public function get_id_car () {
            return $this->id_car;
        }
        public function set_marca ($marca_tabla_vehiculos) {
            $this->marca_tabla_vehiculos = $marca_tabla_vehiculos;
            return $this;
        }
        public function get_marca () {
            return $this->marca_tabla_vehiculos;
        }
        public function set_modelo ($modelo_tabla_vehiculos) {
            $this->modelo_tabla_vehiculos = $modelo_tabla_vehiculos;
            return $this;
        }
        public function get_modelo () {
            return $this->modelo_tabla_vehiculos;
        }
        public function set_version ($version_tabla_vehiculos) {
            $this->version_tabla_vehiculos = $version_tabla_vehiculos;
            return $this;
        }
        public function get_version () {
            return $this->version_tabla_vehiculos;
        }
        public function set_mostrar ($mostrar_tabla_vehiculos) {
            $this->mostrar_tabla_vehiculos = $mostrar_tabla_vehiculos;
            return $this;
        }
        public function get_mostrar () {
            return $this->mostrar_tabla_vehiculos;
        }
        public function set_matricula ($matricula_tabla_vehiculos) {
            $this->matricula_tabla_vehiculos = $matricula_tabla_vehiculos;
            return $this;
        }
        public function get_matricula () {
            return $this->matricula_tabla_vehiculos;
        }
        public function set_bastidor ($bastidor_tabla_vehiculos) {
            $this->bastidor_tabla_vehiculos = $bastidor_tabla_vehiculos;
            return $this;
        }
        public function get_bastidor () {
            return $this->bastidor_tabla_vehiculos;
        }
        public function set_activo ($activo_tabla_vehiculos) {
            $this->activo_tabla_vehiculos = $activo_tabla_vehiculos;
            return $this;
        }
        public function get_activo () {
            return $this->activo_tabla_vehiculos;
        }
        public function set_combustible ($combustible) {
            $this->combustible = $combustible;
            return $this;
        }
        public function get_combustible () {
            return $this->combustible;
        }
        public function set_carroceria ($carroceria) {
            $this->carroceria = $carroceria;
            return $this;
        }
        public function get_carroceria () {
            return $this->carroceria;
        }
        public function set_km ($km) {
            $this->km = $km;
            return $this;
        }
        public function get_km () {
            return $this->km;
        }
        public function set_cajacambios ($cajacambios) {
            $this->cajacambios = $cajacambios;
            return $this;
        }
        public function get_cajacambios () {
            return $this->cajacambios;
        }
        public function set_matriculacion ($matriculacion) {
            $this->matriculacion = $matriculacion;
            return $this;
        }
        public function get_matriculacion () {
            return $this->matriculacion;
        }
        public function set_color_principal ($color_principal) {
            $this->color_principal = $color_principal;
            return $this;
        }
        public function get_color_principal () {
            return $this->color_principal;
        }
        public function set_color_comercial ($color_comercial) {
            $this->color_comercial = $color_comercial;
            return $this;
        }
        public function get_color_comercial () {
            return $this->color_comercial;
        }
        public function set_color_principal_literal ($color_principal_literal) {
            $this->color_principal_literal = $color_principal_literal;
            return $this;
        }
        public function get_color_principal_literal () {
            return $this->color_principal_literal;
        }
        public function set_ano_fabricacion ($ano_fabricacion) {
            $this->ano_fabricacion = $ano_fabricacion;
            return $this;
        }
        public function get_ano_fabricacion () {
            return $this->ano_fabricacion;
        }
        public function set_papelera ($papelera) {
            $this->papelera = $papelera;
            return $this;
        }
        public function get_papelera () {
            return $this->papelera;
        }
        public function set_garantia ($garantia) {
            $this->garantia = $garantia;
            return $this;
        }
        public function get_garantia () {
            return $this->garantia;
        }
        public function set_itv_ultima ($itv_ultima) {
            $this->itv_ultima = $itv_ultima;
            return $this;
        }
        public function get_itv_ultima () {
            return $this->itv_ultima;
        }
        public function set_precio_venta ($precio_venta) {
            $this->precio_venta = $precio_venta;
            return $this;
        }
        public function get_precio_venta () {
            return $this->precio_venta;
        }
        public function set_venta_total_sin_dto ($venta_total_sin_dto) {
            $this->venta_total_sin_dto = $venta_total_sin_dto;
            return $this;
        }
        public function get_venta_total_sin_dto () {
            return $this->venta_total_sin_dto;
        }
        public function set_venta_total ($venta_total) {
            $this->venta_total = $venta_total;
            return $this;
        }
        public function get_venta_total () {
            return $this->venta_total;
        }
        public function set_venta_dto_imp ($venta_dto_imp) {
            $this->venta_dto_imp = $venta_dto_imp;
            return $this;
        }
        public function get_venta_dto_imp () {
            return $this->venta_dto_imp;
        }
        public function set_venta_dto_prc ($venta_dto_prc) {
            $this->venta_dto_prc = $venta_dto_prc;
            return $this;
        }
        public function get_venta_dto_prc () {
            return $this->venta_dto_prc;
        }
        public function set_venta_base ($venta_base) {
            $this->venta_base = $venta_base;
            return $this;
        }
        public function get_venta_base () {
            return $this->venta_base;
        }
        public function set_venta_financiado ($venta_financiado) {
            $this->venta_financiado = $venta_financiado;
            return $this;
        }
        public function set_venta_tipo_iva ($venta_tipo_iva) {
            $this->venta_tipo_iva = $venta_tipo_iva;
            return $this;
        }
        public function get_venta_tipo_iva () {
            return $this->venta_tipo_iva;
        }
        public function set_venta_minimo ($venta_minimo) {
            $this->venta_minimo = $venta_minimo;
            return $this;
        }
        public function get_venta_minimo () {
            return $this->venta_minimo;
        }
        public function set_precio_compra ($precio_compra) {
            $this->precio_compra = $precio_compra;
            return $this;
        }
        public function get_precio_compra () {
            return $this->precio_compra;
        }
        public function set_precio_compra_total ($precio_compra_total) {
            $this->precio_compra_total = $precio_compra_total;
            return $this;
        }
        public function get_precio_compra_total () {
            return $this->precio_compra_total;
        }
        public function set_precio_compra_base ($precio_compra_base) {
            $this->precio_compra_base = $precio_compra_base;
            return $this;
        }
        public function get_precio_compra_base () {
            return $this->precio_compra_base;
        }
        public function set_compra_tipo_iva ($compra_tipo_iva) {
            $this->compra_tipo_iva = $compra_tipo_iva;
            return $this;
        }
        public function get_compra_tipo_iva () {
            return $this->compra_tipo_iva;
        }
        public function set_potencia ($potencia) {
            $this->potencia = $potencia;
            return $this;
        }
        public function get_potencia () {
            return $this->potencia;
        }
        public function set_estado ($estado) {
            $this->estado = $estado;
            return $this;
        }
        public function get_estado () {
            return $this->estado;
        }
        public function set_itv_proxima ($itv_proxima) {
            $this->itv_proxima = $itv_proxima;
            return $this;
        }
        public function get_itv_proxima () {
            return $this->itv_proxima;
        }
        public function set_velocidades ($velocidades) {
            $this->velocidades = $velocidades;
            return $this;
        }
        public function get_velocidades () {
            return $this->velocidades;
        }
        public function set_llaves ($llaves) {
            $this->llaves = $llaves;
            return $this;
        }
        public function get_llaves () {
            return $this->llaves;
        }
        public function set_codigo_radio ($codigo_radio) {
            $this->codigo_radio = $codigo_radio;
            return $this;
        }
        public function get_codigo_radio () {
            return $this->codigo_radio;
        }
        public function set_codigo_navegador ($codigo_navegador) {
            $this->codigo_navegador = $codigo_navegador;
            return $this;
        }
        public function get_codigo_navegador () {
            return $this->codigo_navegador;
        }
        public function set_importacion ($importacion) {
            $this->importacion = $importacion;
            return $this;
        }
        public function get_importacion () {
            return $this->importacion;
        }
        public function set_otros_equip ($otros_equip) {
            $this->otros_equip = $otros_equip;
            return $this;
        }
        public function get_otros_equip () {
            return $this->otros_equip;
        }
        public function set_reserva ($reserva) {
            $this->reserva = $reserva;
            return $this;
        }
        public function get_reserva () {
            return $this->reserva;
        }
        public function set_distintivo_ambiental ($distintivo_ambiental) {
            $this->distintivo_ambiental = $distintivo_ambiental;
            return $this;
        }
        public function get_distintivo_ambiental () {
            return $this->distintivo_ambiental;
        }
        public function set_num_not ($num_not) {
            $this->num_not = $num_not;
            return $this;
        }
        public function get_num_not () {
            return $this->num_not;
        }
        public function set_mantenimiento_sellado ($mantenimiento_sellado) {
            $this->mantenimiento_sellado = $mantenimiento_sellado;
            return $this;
        }
        public function get_mantenimiento_sellado () {
            return $this->mantenimiento_sellado;
        }
        public function set_tipo_seguro ($tipo_seguro) {
            $this->tipo_seguro = $tipo_seguro;
            return $this;
        }
        public function get_tipo_seguro () {
            return $this->tipo_seguro;
        }
        public function set_rebu ($rebu) {
            $this->rebu = $rebu;
            return $this;
        }
        public function get_rebu () {
            return $this->rebu;
        }
        public function set_motor_cc ($motor_cc) {
            $this->motor_cc = $motor_cc;
            return $this;
        }
        public function get_motor_cc () {
            return $this->motor_cc;
        }
        public function set_alta ($alta) {
            $this->alta = $alta;
            return $this;
        }
        public function get_alta () {
            return $this->alta;
        }
        public function set_baja ($baja) {
            $this->baja = $baja;
            return $this;
        }
        public function get_baja () {
            return $this->baja;
        }
        public function set_destacado_venta_vo ($destacado_venta_vo) {
            $this->destacado_venta_vo = $destacado_venta_vo;
            return $this;
        }
        public function get_destacado_venta_vo () {
            return $this->destacado_venta_vo;
        }
        public function set_ubic_direccion ($ubic_direccion) {
            $this->ubic_direccion = $ubic_direccion;
            return $this;
        }
        public function get_ubic_direccion () {
            return $this->ubic_direccion;
        }
        public function set_eurotax ($eurotax) {
            $this->eurotax = $eurotax;
            return $this;
        }
        public function get_eurotax () {
            return $this->eurotax;
        }
        public function set_stock ($stock) {
            $this->stock = $stock;
            return $this;
        }
        public function get_stock () {
            return $this->stock;
        }
        public function set_ubic_poblacion ($ubic_poblacion) {
            $this->ubic_poblacion = $ubic_poblacion;
            return $this;
        }
        public function get_ubic_poblacion () {
            return $this->ubic_poblacion;
        }
        public function set_ubic_provincia ($ubic_provincia) {
            $this->ubic_provincia = $ubic_provincia;
            return $this;
        }
        public function get_ubic_provincia () {
            return $this->ubic_provincia;
        }
        public function set_procedencia ($procedencia) {
            $this->procedencia = $procedencia;
            return $this;
        }
        public function get_procedencia () {
            return $this->procedencia;
        }
        public function set_notas ($notas) {
            $this->notas = $notas;
            return $this;
        }
        public function get_notas () {
            return $this->notas;
        }
        public function set_importacion_excel ($importacion_excel) {
            $this->importacion_excel = $importacion_excel;
            return $this;
        }
        public function get_importacion_excel () {
            return $this->importacion_excel;
        }
        public function set_manual ($manual) {
            $this->manual = $manual;
            return $this;
        }
        public function get_manual () {
            return $this->manual;
        }
        public function set_libro_mant ($libro_mant) {
            $this->libro_mant = $libro_mant;
            return $this;
        }
        public function get_libro_mant () {
            return $this->libro_mant;
        }
        public function set_gastos_gestion ($gastos_gestion) {
            $this->gastos_gestion = $gastos_gestion;
            return $this;
        }
        public function get_gastos_gestion () {
            return $this->gastos_gestion;
        }
        public function set_tipo_precios_extra ($tipo_precios_extra) {
            $this->tipo_precios_extra = $tipo_precios_extra;
            return $this;
        }
        public function get_tipo_precios_extra () {
            return $this->tipo_precios_extra;
        }
        public function set_base_precios_extra ($base_precios_extra) {
            $this->base_precios_extra = $base_precios_extra;
            return $this;
        }
        public function get_base_precios_extra () {
            return $this->base_precios_extra;
        }
        public function set_dto_imp_precios_extra ($dto_imp_precios_extra) {
            $this->dto_imp_precios_extra = $dto_imp_precios_extra;
            return $this;
        }
        public function get_dto_imp_precios_extra () {
            return $this->dto_imp_precios_extra;
        }
        public function set_dto_prc_precios_extra ($dto_prc_precios_extra) {
            $this->dto_prc_precios_extra = $dto_prc_precios_extra;
            return $this;
        }
        public function get_dto_prc_precios_extra () {
            return $this->dto_prc_precios_extra;
        }
        public function set_total_sin_dto_precios_extra ($total_sin_dto_precios_extra) {
            $this->total_sin_dto_precios_extra = $total_sin_dto_precios_extra;
            return $this;
        }
        public function get_total_sin_dto_precios_extra () {
            return $this->total_sin_dto_precios_extra;
        }
        public function set_total_precios_extra ($total_precios_extra) {
            $this->total_precios_extra = $total_precios_extra;
            return $this;
        }
        public function get_total_precios_extra () {
            return $this->total_precios_extra;
        }
        public function set_limite_precios_extra ($limite_precios_extra) {
            $this->limite_precios_extra = $limite_precios_extra;
            return $this;
        }
        public function get_limite_precios_extra () {
            return $this->limite_precios_extra;
        }
        public function set_code_ext ($code_ext) {
            $this->code_ext = $code_ext;
            return $this;
        }
        public function get_code_ext () {
            return $this->code_ext;
        }


        //LINKS
        private $codigo_link;
        public function set_codigo_link ($codigo_link) {
            $this->codigo_link = $codigo_link;
            return $this;
        }
        public function get_codigo_link () {
            return $this->codigo_link;
        }
        private $orden_link;
        public function set_orden_link ($orden_link) {
            $this->orden_link = $orden_link;
            return $this;
        }
        public function get_orden_link () {
            return $this->orden_link;
        }
        private $tipo_link;
        public function set_tipo_link ($tipo_link) {
            $this->tipo_link = $tipo_link;
            return $this;
        }
        public function get_tipo_link () {
            return $this->tipo_link;
        }
        private $link;
        public function set_link ($link) {
            $this->link = $link;
            return $this;
        }
        public function get_link () {
            return $this->link;
        }
        private $origen_link;
        public function set_origen_link ($origen_link) {
            $this->origen_link = $origen_link;
            return $this;
        }
        public function get_origen_link () {
            return $this->origen_link;
        }
        private $activo_link;
        public function set_activo_link ($activo_link) {
            $this->activo_link = $activo_link;
            return $this;
        }
        public function get_activo_link () {
            return $this->activo_link;
        }
        //Portals
        private $portal;
        public function set_portal ($portal) {
            $this->portal = $portal;
            return $this;
        }
        public function get_portal () {
            return $this->portal;
        }


        

        public function carId() {
            $Schema = new Schema($this->con);
            $res = $this->con->query('SELECT CODIGO FROM VEHICULOS ORDER BY CODIGO DESC');
            if($res->num_rows) {
                $row = $res->fetch_array();
                $carId = $row['CODIGO'] + 1;
            } else {
                $carId = 5000001;
            }

            return $carId;
        }
        public function insert_vehiculo () {
            $Schema = new Schema($this->con);
            date_default_timezone_set('Europe/Madrid');

            $codigo_vehiculo = $this->get_codigo_vehiculo_tabla_vehiculos();
            $usuario_session = $this->get_usuario_session();
            $tipo = $this->get_tipo();
            $id_car = $this->get_id_car();
            $marca = $this->get_marca();
            $modelo = $this->get_modelo();
            $version = $this->get_version();
            $mostrar = $this->get_mostrar();
            $matricula = $this->get_matricula();
            $bastidor = $this->get_bastidor();
            $activo = $this->get_activo();
            $combustible = $this->get_combustible();
            $carroceria = $this->get_carroceria();
            $km = $this->get_km();
            $cajacambios = $this->get_cajacambios();
            $matriculacion = $this->get_matriculacion();
            $color_principal = $this->get_color_principal();
            $color_comercial = $this->get_color_comercial();
            $ano_fabricacion = $this->get_ano_fabricacion();
            $papelera = $this->get_papelera();
            $garantia = $this->get_garantia();
            $itv_ultima = $this->get_itv_ultima();
            $precio_venta = $this->get_precio_venta();
            $venta_total_sin_dto = $this->get_venta_total_sin_dto();
            $venta_total = $this->get_venta_total();
            $venta_dto_imp = $this->get_venta_dto_imp();
            $venta_dto_prc = $this->get_venta_dto_prc();
            $venta_base = $this->get_venta_base();
            $venta_tipo_iva = $this->get_venta_tipo_iva();
            $venta_minimo = $this->get_venta_minimo();
            $precio_compra = $this->get_precio_compra();
            $precio_compra_total = $this->get_precio_compra_total();
            $precio_compra_base = $this->get_precio_compra_base();
            $compra_tipo_iva = $this->get_compra_tipo_iva();
            $potencia = $this->get_potencia();
            $estado = $this->get_estado();
            $itv_proxima = $this->get_itv_proxima();
            $color_principal_literal = $this->get_color_principal_literal();
            $llaves = $this->get_llaves();
            $velocidades = $this->get_velocidades();
            $codigo_radio = $this->get_codigo_radio();
            $codigo_navegador = $this->get_codigo_navegador();
            $otros_equip = $this->get_otros_equip();
            $importacion = $this->get_importacion();
            $distintivo_ambiental = $this->get_distintivo_ambiental();
            $reserva = $this->get_reserva();
            $num_not = $this->get_num_not();
            $mantenimiento_sellado = $this->get_mantenimiento_sellado();
            $tipo_seguro = $this->get_tipo_seguro();
            $rebu = $this->get_rebu();
            $motor_cc = $this->get_motor_cc();
            $eurotax = $this->get_eurotax();
            $notas = $this->get_notas();
            $importacion_excel = $this->get_importacion_excel();
            $manual = $this->get_manual();
            $libro_mant = $this->get_libro_mant();
            $gastos_gestion = $this->get_gastos_gestion();
            $stock = $this->get_stock();
            $code_ext = $this->get_stock();
            $now = date('Y-m-d H:i:s');
            $valores_obligatorios = [$codigo_vehiculo, $usuario_session, $tipo, $id_car];

            if (in_array(NULL, $valores_obligatorios)) {
                return false;
            } else {
                $sql = 'INSERT INTO VEHICULOS(CODIGO, USUARIO, TIPO, IDCAR, MARCA, MODELO, VERSION, MOSTRAR, MATRICULA, BASTIDOR, ACTIVO, ALTA, COMBUSTIBLE, CARROCERIA, KM, CAJACAMBIOS, MATRICULACION, COLOR_PRINCIPAL, COLOR_COMERCIAL, ANO_FAB, PAPELERA, GARANTIA, ITV_ULTIMA, PRECIO_VENTA, VENTA_TOTALSINDTO, VENTA_TOTAL, VENTA_DTOIMP, VENTA_DTOPRC, VENTA_BASE, VENTA_TIPOIVA, VENTA_MINIMO, PRECIO_COMPRA, COMPRA_TOTAL, COMPRA_BASE, COMPRA_TIPOIVA, POTENCIA, ESTADO, ITV_PROXIMA, COLORPRI_LIT, VELOCIDADES, LLAVES, CODIGO_RAD, CODIGO_NAV, IMPORTACION, OTROS_EQUIP, RESERVA, DISTINTIVO_AMB, NUMNOT, MANT_SELLADO, TIPO_SEGURO, REBU, MOTOR, EUROTAX, NOTAS, IMPORTACION_EXCEL, MANUAL, LIBRO_MANT, GASTOS_GESTION, STOCK ,CODE_EXT) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';
                
                $Schema->executeQuery($sql, 'isssiissssisiiiisiiiiisdddddddddddiisssiiisissiiiiisssiiiiis', [$codigo_vehiculo, $usuario_session, $tipo, $id_car, $marca, $modelo, $version, $mostrar, $matricula, $bastidor, $activo, $now, $combustible, $carroceria, $km, $cajacambios, $matriculacion, $color_principal, $color_comercial, $ano_fabricacion, $papelera, $garantia, $itv_ultima, $precio_venta, $venta_total_sin_dto, $venta_total, $venta_dto_imp, $venta_dto_prc, $venta_base, $venta_tipo_iva, $venta_minimo, $precio_compra, $precio_compra_total, $precio_compra_base, $compra_tipo_iva, $potencia, $estado, $itv_proxima, $color_principal_literal, $velocidades, $llaves, $codigo_radio, $codigo_navegador, $importacion, $otros_equip, $reserva, $distintivo_ambiental, $num_not, $mantenimiento_sellado, $tipo_seguro, $rebu, $motor_cc, $eurotax, $notas, $importacion_excel, $manual, $libro_mant, $gastos_gestion, $stock, $code_ext]);


                return true;  
            }

            

        }
        public function update_vehiculo () {
            $Schema = new Schema($this->con);
            date_default_timezone_set('Europe/Madrid');
            $codigo_vehiculo = $this->get_codigo_vehiculo_tabla_vehiculos();

            $condition = ' CODIGO = ? ';
            $type = 'i';
            $variables = [$this->get_codigo_vehiculo_tabla_vehiculos()];
            
            if(isset($this->marca_tabla_vehiculos)) {
                $condition .= ',MARCA = ? ';
                $type .= 'i';
                array_push($variables, $this->get_marca());
            }
            if(isset($this->modelo_tabla_vehiculos)) {
                $condition .= ',MODELO = ? ';
                $type .= 'i';
                array_push($variables, $this->get_modelo());
            }
            if(isset($this->version_tabla_vehiculos)) {
                $condition .= ',VERSION = ? ';
                $type .= 's';
                array_push($variables, $this->get_version());
            }
            if(isset($this->mostrar_tabla_vehiculos)) {
                $condition .= ',MOSTRAR = ? ';
                $type .= 's';
                array_push($variables, $this->get_mostrar());
            }
            if(isset($this->matricula_tabla_vehiculos)) {
                $condition .= ',MATRICULA = ? ';
                $type .= 's';
                array_push($variables, $this->get_matricula());
            }
            if(isset($this->bastidor_tabla_vehiculos)) {
                $condition .= ',BASTIDOR = ? ';
                $type .= 's';
                array_push($variables, $this->get_bastidor());
            }
            if(isset($this->activo_tabla_vehiculos)) {
                $condition .= ',ACTIVO = ? ';
                $type .= 'i';
                array_push($variables, $this->get_activo());
            }
            if(isset($this->combustible)) {
                $condition .= ',COMBUSTIBLE = ? ';
                $type .= 'i';
                array_push($variables, $this->get_combustible());
            }
            if(isset($this->carroceria)) {
                $condition .= ',CARROCERIA = ? ';
                $type .= 'i';
                array_push($variables, $this->get_carroceria());
            }
            if(isset($this->km)) {
                $condition .= ',KM = ? ';
                $type .= 'i';
                array_push($variables, $this->get_km());
            }
            if(isset($this->cajacambios)) {
                $condition .= ',CAJACAMBIOS = ? ';
                $type .= 'i';
                array_push($variables, $this->get_cajacambios());
            }
            if(isset($this->matriculacion)) {
                $condition .= ',MATRICULACION = ? ';
                $type .= 's';
                array_push($variables, $this->get_matriculacion());
            }
            if(isset($this->color_principal)) {
                $condition .= ',COLOR_PRINCIPAL = ? ';
                $type .= 'i';
                array_push($variables, $this->get_color_principal());
            }
            if(isset($this->color_comercial)) {
                $condition .= ',COLOR_COMERCIAL = ? ';
                $type .= 'i';
                array_push($variables, $this->get_color_comercial());
            }
            if(isset($this->ano_fabricacion)) {
                $condition .= ',ANO_FAB = ? ';
                $type .= 'i';
                array_push($variables, $this->get_ano_fabricacion());
            }
            if(isset($this->papelera)) {
                $condition .= ',PAPELERA = ? ';
                $type .= 'i';
                array_push($variables, $this->get_papelera());
            }
            if(isset($this->garantia)) {
                $condition .= ',GARANTIA = ? ';
                $type .= 'i';
                array_push($variables, $this->get_garantia());
            }
            if(isset($this->itv_ultima)) {
                $condition .= ',ITV_ULTIMA = ? ';
                $type .= 's';
                array_push($variables, $this->get_itv_ultima());
            }
            if(isset($this->precio_venta)) {
                $condition .= ',PRECIO_VENTA = ? ';
                $type .= 'd';
                array_push($variables, $this->get_precio_venta());
            }
            if(isset($this->venta_total_sin_dto)) {
                $condition .= ',VENTA_TOTALSINDTO = ? ';
                $type .= 'd';
                array_push($variables, $this->get_venta_total_sin_dto());
            }
            if(isset($this->venta_total)) {
                $condition .= ',VENTA_TOTAL = ? ';
                $type .= 'd';
                array_push($variables, $this->get_venta_total());
            }
            if(isset($this->venta_dto_imp)) {
                $condition .= ',VENTA_DTOIMP = ? ';
                $type .= 'd';
                array_push($variables, $this->get_venta_dto_imp());
            }
            if(isset($this->venta_dto_prc)) {
                $condition .= ',VENTA_DTOPRC = ? ';
                $type .= 'd';
                array_push($variables, $this->get_venta_dto_prc());
            }
            if(isset($this->venta_base)) {
                $condition .= ',VENTA_BASE = ? ';
                $type .= 'd';
                array_push($variables, $this->get_venta_base());
            }
            if(isset($this->venta_tipo_iva)) {
                $condition .= ',VENTA_TIPOIVA = ? ';
                $type .= 'd';
                array_push($variables, $this->get_venta_tipo_iva());
            }
            if(isset($this->venta_minimo)) {
                $condition .= ',VENTA_MINIMO = ? ';
                $type .= 'd';
                array_push($variables, $this->get_venta_minimo());
            }
            if(isset($this->precio_compra)) {
                $condition .= ',PRECIO_COMPRA = ? ';
                $type .= 'd';
                array_push($variables, $this->get_precio_compra());
            }
            if(isset($this->precio_compra_total)) {
                $condition .= ',COMPRA_TOTAL = ? ';
                $type .= 'd';
                array_push($variables, $this->get_precio_compra_total());
            }
            if(isset($this->precio_compra_base)) {
                $condition .= ',COMPRA_BASE = ? ';
                $type .= 'd';
                array_push($variables, $this->get_precio_compra_base());
            }
            if(isset($this->compra_tipo_iva)) {
                $condition .= ',COMPRA_TIPOIVA = ? ';
                $type .= 'i';
                array_push($variables, $this->get_compra_tipo_iva());
            }
            if(isset($this->potencia)) {
                $condition .= ',POTENCIA = ? ';
                $type .= 'i';
                array_push($variables, $this->get_potencia());
            }
            if(isset($this->estado)) {
                $condition .= ', ESTADO = ? ';
                $type .= 's';
                array_push($variables, $this->get_estado());
            }
            if(isset($this->itv_proxima)) {
                $condition .= ',ITV_PROXIMA = ? ';
                $type .= 's';
                array_push($variables, $this->get_itv_proxima());
            }
            if(isset($this->color_principal_literal)) {
                $condition .= ',COLORPRI_LIT = ? ';
                $type .= 's';
                array_push($variables, $this->get_color_principal_literal());
            }
            if(isset($this->llaves)) {
                $condition .= ',LLAVES = ? ';
                $type .= 'i';
                array_push($variables, $this->get_llaves());
            }
            if(isset($this->velocidades)) {
                $condition .= ',VELOCIDADES = ? ';
                $type .= 'i';
                array_push($variables, $this->get_velocidades());
            }
            if(isset($this->codigo_radio)) {
                $condition .= ',CODIGO_RAD = ? ';
                $type .= 'i';
                array_push($variables, $this->get_codigo_radio());
            }
            if(isset($this->codigo_navegador)) {
                $condition .= ',CODIGO_NAV = ? ';
                $type .= 's';
                array_push($variables, $this->get_codigo_navegador());
            }
            if(isset($this->otros_equip)) {
                $condition .= ',OTROS_EQUIP = ? ';
                $type .= 's';
                array_push($variables, $this->get_otros_equip());
            }
            if(isset($this->importacion)) {
                $condition .= ',IMPORTACION = ? ';
                $type .= 'i';
                array_push($variables, $this->get_importacion());
            }
            if(isset($this->distintivo_ambiental)) {
                $condition .= ',DISTINTIVO_AMB = ? ';
                $type .= 'i';
                array_push($variables, $this->get_distintivo_ambiental());
            }
            if(isset($this->reserva)) {
                if(empty($this->reserva)) {
                    $condition .= ', RESERVA = NULL ';
                } else {
                    $condition .= ', RESERVA = ? ';
                    $type .= 's';
                    array_push($variables, $this->get_reserva());
                }
            }
            if(isset($this->num_not)) {
                $condition .= ',NUMNOT = ? ';
                $type .= 'i';
                array_push($variables, $this->get_num_not());
            }
            if(isset($this->mantenimiento_sellado)) {
                $condition .= ',MANT_SELLADO = ? ';
                $type .= 'i';
                array_push($variables, $this->get_mantenimiento_sellado());
            }
            if(isset($this->tipo_seguro)) {
                $condition .= ',TIPO_SEGURO = ? ';
                $type .= 'i';
                array_push($variables, $this->get_tipo_seguro());
            }
            if(isset($this->rebu)) {
                $condition .= ',REBU = ? ';
                $type .= 'i';
                array_push($variables, $this->get_rebu());
            }
            if(isset($this->motor_cc)) {
                $condition .= ',MOTOR = ? ';
                $type .= 's';
                array_push($variables, $this->get_motor_cc());
            }
            if(isset($this->alta)) {
                $condition .= ',ALTA = ? ';
                $type .= 's';
                array_push($variables, $this->get_alta());
            }
            if(isset($this->baja)) {
                $condition .= ',BAJA = ? ';
                $type .= 's';
                array_push($variables, $this->get_baja());
            }
            if(isset($this->destacado_venta_vo)) {
                $condition .= ',DESTACADO_VENTA_VO = ? ';
                $type .= 'i';
                array_push($variables, $this->get_baja());
            }
            if(isset($this->ubic_direccion)) {
                $condition .= ', UBIC_DIRECCION = ? ';
                $type .= 's';
                array_push($variables, $this->get_ubic_direccion());
            }
            if(isset($this->eurotax)) {
                $condition .= ', EUROTAX = ? ';
                $type .= 's';
                array_push($variables, $this->get_eurotax());
            }
            if(isset($this->stock)) {
                $condition .= ', STOCK = ? ';
                $type .= 'i';
                array_push($variables, $this->get_stock());
            }
            if(isset($this->ubic_poblacion)) {
                $condition .= ', UBIC_POBLACION = ? ';
                $type .= 'i';
                array_push($variables, $this->get_ubic_poblacion());
            }
            if(isset($this->ubic_provincia)) {
                $condition .= ', UBIC_PROVINCIA = ? ';
                $type .= 'i';
                array_push($variables, $this->get_ubic_provincia());
            }
            if(isset($this->procedencia)) {
                $condition .= ', PROCEDENCIA = ? ';
                $type .= 'i';
                array_push($variables, $this->get_procedencia());
            }
            if(isset($this->notas)) {
                $condition .= ', NOTAS = ? ';
                $type .= 's';
                array_push($variables, $this->get_notas());
            }
            if(isset($this->manual)) {
                $condition .= ', MANUAL = ? ';
                $type .= 'i';
                array_push($variables, $this->get_manual());
            }
            if(isset($this->libro_mant)) {
                $condition .= ', LIBRO_MANT = ? ';
                $type .= 'i';
                array_push($variables, $this->get_libro_mant());
            }
            if(isset($this->gastos_gestion)) {
                $condition .= ', GASTOS_GESTION = ? ';
                $type .= 'i';
                array_push($variables, $this->get_gastos_gestion());
            }
            if(isset($this->importacion_excel)) {
                $condition .= ', IMPORTACION_EXCEL = ? ';
                $type .= 'i';
                array_push($variables, $this->get_importacion_excel());
            }
            if(isset($this->code_ext)) {
                $condition .= ', CODE_EXT = ? ';
                $type .= 's';
                array_push($variables, $this->get_code_ext());
            }

            $condition .= 'WHERE CODIGO = ?';
            $type .= 'i';
            array_push($variables, $codigo_vehiculo);
            $Schema->executeQuery('UPDATE VEHICULOS SET ' . $condition, $type, $variables); 

            return true;
        }
        public function nombre_vehiculo($marca, $modelo, $separador = FALSE) {
            $separador = $separador ? $separador : " - ";
            $sql = "SELECT M.DESCRIPCION AS M_DESC, MO.DESCRIPCION AS MO_DESC
            FROM VEHICULOS_MARCAS M
            INNER JOIN VEHICULOS_MODELOS MO ON M.CODIGO = MO.MARCA
            WHERE M.CODIGO = ? AND MO.CODIGO = ?";
            $stmt = $this->con->prepare($sql);
            $stmt->bind_param('ii',$marca,$modelo);
            $stmt->execute();
            $res = $stmt->get_result();
            $fila = $res->fetch_array();
            $mostrar = strtoupper($fila['M_DESC']) . $separador . strtoupper($fila['MO_DESC']);
            return $mostrar;
        }
        public function insert_precios_extra () {
            $Schema = new Schema($this->con);

            $codigo_vehiculo = $this->get_codigo_vehiculo_tabla_vehiculos();
            $tipo_precios_extra = $this->get_tipo_precios_extra();
            $base_precios_extra = $this->get_base_precios_extra();
            $dto_imp_precios_extra = $this->get_dto_imp_precios_extra();
            $dto_prc_precios_extra = $this->get_dto_prc_precios_extra();
            $total_sin_dto_precios_extra = $this->get_total_sin_dto_precios_extra();
            $total_precios_extra = $this->get_total_precios_extra();
            $limite_precios_extra = $this->get_limite_precios_extra();

            $sql = 'INSERT INTO VEHICULOS_PRECIOSEXTRAS(CODIGO, TIPO, BASE, DTOIMP, DTOPRC, TOTALSINDTO, TOTAL, LIMITE) VALUES(?, ?, ?, ?, ?, ?, ?, ?)';
            $Schema->executeQuery($sql, 'iiddddds', [$codigo_vehiculo, $tipo_precios_extra, $base_precios_extra, $dto_imp_precios_extra, $dto_prc_precios_extra, $total_sin_dto_precios_extra, $total_precios_extra, $limite_precios_extra]);
        }
        public function update_precios_extra () {
            $Schema = new Schema($this->con);

            $condition = ' CODIGO = ? ';
            $type = 'i';
            $variables = [$this->get_codigo_vehiculo_tabla_vehiculos()];

            if(isset($this->base_precios_extra)) {
                $condition .= ',BASE = ? ';
                $type .= 'd';
                array_push($variables, $this->get_base_precios_extra());
            }
            if(isset($this->dto_imp_precios_extra)) {
                $condition .= ',DTOIMP = ? ';
                $type .= 'd';
                array_push($variables, $this->get_dto_imp_precios_extra());
            }
            if(isset($this->dto_prc_precios_extra)) {
                $condition .= ',DTOPRC = ? ';
                $type .= 'd';
                array_push($variables, $this->get_dto_prc_precios_extra());
            }
            if(isset($this->total_sin_dto_precios_extra)) {
                $condition .= ',TOTALSINDTO = ? ';
                $type .= 'd';
                array_push($variables, $this->get_total_sin_dto_precios_extra());
            }
            if(isset($this->total_precios_extra)) {
                $condition .= ',TOTAL = ? ';
                $type .= 'd';
                array_push($variables, $this->get_total_precios_extra());
            }
            if(isset($this->limite_precios_extra)) {
                $condition .= ',LIMITE = ? ';
                $type .= 's';
                array_push($variables, $this->get_limite_precios_extra());
            }
            $condition .= 'WHERE CODIGO = ? AND TIPO = ?';
            $type .= 'ii';
            array_push($variables, $this->get_codigo_vehiculo_tabla_vehiculos());
            array_push($variables, $this->get_tipo_precios_extra());


            $Schema->executeQuery('UPDATE VEHICULOS_PRECIOSEXTRAS SET ' . $condition, $type, $variables);
        }
        public function insert_links() {
            $Schema = new Schema($this->con);
            $values = [
                $this->get_codigo_link(),
                $this->get_orden_link(),
                $this->get_codigo_vehiculo_tabla_vehiculos(),
                $this->get_tipo_link(),
                $this->get_link(),
                date('Y-m-d H:i:s'),
                $this->get_origen_link()
            ];
            $Schema->executeQuery('INSERT INTO VEHICULOS_MULTIMEDIA_LINKS(CODIGO, ORDEN, VEHICULO, TIPO, LINK, FECHA, ORIGEN) VALUES(?, ?, ?, ?, ?, ?, ?)', 'siiisss', $values);

        }
        public function update_links() {
            $Schema = new Schema($this->con);
            $sql = 'UPDATE VEHICULOS_MULTIMEDIA_LINKS SET FECHA = ?';
            $type = 's';
            $values = [date('Y-m-d H:i:s')];
            if(isset($this->orden_link)) {
                $sql .= ',ORDEN = ? ';
                $type .= 'i';
                array_push($values, $this->get_orden_link());
            }
            if(isset($this->link)) {
                $sql .= ',LINK = ? ';
                $type .= 's';
                array_push($values, $this->get_link());
            }
            if(isset($this->activo_link)) {
                $sql .= ',ACTIVO = ? ';
                $type .= 'i';
                array_push($values, $this->get_activo_link());
            }
            $sql .= 'WHERE VEHICULO = ?';
            $type .= 'i';
            array_push($values, $this->get_codigo_vehiculo_tabla_vehiculos());
            $Schema->executeQuery($sql, $type, $values);

        }
        public function delete_links() {
            $Schema = new Schema($this->con);

            $Schema->executeQuery('DELETE FROM VEHICULOS_MULTIMEDIA_LINKS WHERE VEHICULO = ?', 'i', [$this->get_codigo_vehiculo_tabla_vehiculos()]);
        }
        public function select_portal($alias) {
            $Schema = new Schema($this->con);

            $res = $Schema->executeQuery('SELECT CODIGO, DESCRIPCION FROM VEHICULOS_PORTALES WHERE ALIAS = ? AND ACTIVO = ?', 'si', [$alias, 1]);
            if($res->num_rows) {
                $row = $res->fetch_array();

                $key = ['key' => $row['CODIGO'], 'title' => $row['DESCRIPCION']];
            } else {
                $key = false;
            }


            return $key;
        }
        public function update_portal($all = false) {
            $Schema = new Schema($this->con);
            if($all) {
                $values = [
                    date('Y-m-d H:i:s'),
                    0,
                    $this->get_codigo_vehiculo_tabla_vehiculos()
                ];
                $Schema->executeQuery('UPDATE VEHICULOS_PUBLICACIONES SET FIN = ?, ACTIVO = ? WHERE VEHICULO = ?', 'sii', $values);
            } else {
                $values = [
                    date('Y-m-d H:i:s'),
                    0,
                    $this->get_portal(),
                    $this->get_codigo_vehiculo_tabla_vehiculos()
                ];
                $Schema->executeQuery('UPDATE VEHICULOS_PUBLICACIONES SET FIN = ?, ACTIVO = ? WHERE PORTAL = ? AND VEHICULO = ?', 'siii', $values);
            }
        }
        public function insert_portal() {
            $Schema = new Schema($this->con);
            $res = $Schema->executeQuery('SELECT * FROM VEHICULOS_PUBLICACIONES WHERE VEHICULO = ? AND PORTAL = ? AND ACTIVO = ?', 'iis', [$this->get_codigo_vehiculo_tabla_vehiculos(), $this->get_portal(), 1]);
            if($res->num_rows) {
                $this->update_portal();
            }
            $values = [
                $this->get_codigo_vehiculo_tabla_vehiculos(),
                $this->get_portal(),
                date('Y-m-d H:i:s')
            ];
            $Schema->executeQuery('INSERT INTO VEHICULOS_PUBLICACIONES(VEHICULO, PORTAL, INICIO) VALUES(?, ?, ?)', 'iis', $values);
        }



        public function StringsScore($str1, $str2) {
            similar_text($str1, $str2, $firstScore);//get a first comparation between strings 
            if($firstScore >= 80) {// if is almost a perfect match return this score
                $score = strlen($str1) == strlen($str2) ? 100 : $firstScore;
            } else {
                
                $new = [];//new array
                $str = preg_replace('/[^a-zA-Z0-9]/', ' ', $str1);//Get rid of non alphanumeric caracters
                $origin = explode(' ', $str);//Convert first string into array to compare, in case string contains more than 1 word
                $str2 = strtoupper($str2);//Convert second string to uppercase
                $str2 = str_replace('NUEVO', '', $str2);//Get rid of this word
                $str2 = preg_replace('/[^a-zA-Z0-9]/', ' ', $str2);//Get rid of non alphanumeric caracters
                $str2 = preg_replace('/\s+/', ' ', $str2);//Remain with only one space between words
                $str2 = $str2 == 'MB' ? 'MERCEDES BENZ' : $str2;//Check if string is mb and change to Mercedes benz
                $explode = explode(' ', $str2);//Convert second string into array to compare
                for($i = 0; $i <= count($explode) - 1; $i++) {
                    for($j = 0; $j <= count($origin) - 1; $j++) {
                        similar_text($explode[$i], $origin[$j], $score);//Get score of words comparation
                        if($score >= 70) {
                            array_push($new, $explode[$i]);//Create a new array for all words that score more than 70%
                        }
                    }
                }
                sort($origin);//Order to increment the score
                sort($new);//Order to increment the score
                similar_text(implode(' ', $origin), implode(' ', $new), $score);//Get the final score

                $score = $score;
            }

            return $score;
        }
        public function smart_score($str1, $str2) {
            $str1 = strtoupper($str1);
            $str2 = strtoupper($str2);
            $str2 = trim($str2); // Remove spaces from start and end
            $str2 = $str2 == 'MB' ? 'MERCEDES-BENZ' : $str2;
            $str2 = $str2 == 'ELECTRICO ENCHUFABLE' ? 'ELÉCTRICO ENCHUFABLE' : $str2;
            $str2 = $str2 == 'CITROEN' ? 'CITROËN' : $str2;
            $str2 = $str2 == 'CITROEN' ? 'CITROËN' : $str2;
            $str2 = str_replace('NEW', '', $str2);
            $str2 = str_replace('NUEVO', '', $str2);
            $str2 = preg_replace('/[^a-zA-Z0-9]/', ' ', $str2);
            $str2 = preg_replace('/\s+/', ' ', $str2);
            $str1 = preg_replace('/[^a-zA-Z0-9]/', ' ', $str1);
    
            $firstString = explode(' ', $str1);
            sort($firstString);
            $secondString = explode(' ', $str2);
            sort($secondString);
            $show = '';
            $new = [];
            for($i = 0; $i <= count($secondString) - 1; $i++) {
                if(isset($firstString[$i])) {
                    similar_text($secondString[$i],$firstString[$i], $score);
                    if($score >= 88) {
                        array_push($new, $firstString[$i]);
                        $show .= $secondString[$i] . " = " . $firstString[$i] . " " . $score . " <br>";
                    }
                }
    
            }
    
            $a = implode(' ', $firstString);
            $b = implode(' ', $new);
            similar_text($a, $b, $s);
    
    
    
           /*  return ['score' => $s, 'title' => $new]; */
            return ['score' => $s, 'title' => $b, 'old_title' => $a];
        }
        public function find_my_code($query, $string, $literales = false) {
            $x = [];

            if(!$literales) {
                while($row = $query->fetch_array()) {
                    $smartSearch = $this->smart_score($row['D'], $string);
                    if($smartSearch['score'] >= 85) {
                        similar_text($string, $smartSearch['title'], $r);
                        $x["$r"] = $row['CODIGO'];
                    }
                }
                if(!empty($x)) {
                    $result = $x[max(array_keys($x))];
                } else {
                    $result = null;
                }
            } else {
                $i = 0;
                $score = 0;
                while($row = $query->fetch_array()) {
                    $i++;
                    $search = $this->StringsScore($row['D'], $string);
                    $lengthUser = strlen($string);
                    if($score <= $search) {
                        $score = $search;
                        $x[0]['id'] = $row['CODIGO'];
                    }
                    
                }
                $result = $x[0]['id'];
            }



            

            return $result;
        }


        
    }
?>