<?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/historial.php');
include('../includes/esquemas.php');
include('../includes/functions.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');
}


$key = "";
$variable = "";

$key2 = "";
$variable2 = "";

$key3 = "";


$matricula = $_SESSION['matricula_search'];
$marca = htmlspecialchars(mysqli_real_escape_string($con,$_POST['marca']));
$modelo = htmlspecialchars(mysqli_real_escape_string($con,$_POST['modelo']));
$cambio = htmlspecialchars(mysqli_real_escape_string($con,$_POST['cambio']));
$carroceria = htmlspecialchars(mysqli_real_escape_string($con,$_POST['carroceria']));
$km = htmlspecialchars(mysqli_real_escape_string($con,$_POST['km']));
$combustible = htmlspecialchars(mysqli_real_escape_string($con,$_POST['combustible']));
$color = htmlspecialchars(mysqli_real_escape_string($con,$_POST['color']));
$mant_sellado = htmlspecialchars(mysqli_real_escape_string($con,$_POST['mant_sellado']));
$tipo_seguro = !empty($_POST['tipo_seguro']) ? htmlspecialchars(mysqli_real_escape_string($con,$_POST['tipo_seguro'])) : 0;




$nombre = $_SESSION['nombre'];
$apellido = $_SESSION['apellido'];
$email =  $_SESSION['email'];
$telefono =  $_SESSION['telefono'];
$sqlNIF = "SELECT CODIGO FROM CONTACTOS WHERE EMAIL1 = ?";
$stmt = $con->prepare($sqlNIF);
$stmt->bind_param('s',$email);
$stmt->execute();
$resNIF = $stmt->get_result();
if($resNIF->num_rows)
{

    $filaNIF = $resNIF->fetch_array();
    $next = $filaNIF['CODIGO'];
    $key .= "NOMBRE = '$nombre',"; 
    $key .= "APELLIDO1 = '$apellido',";
    if(empty($_SESSION['segundo_apellido']))
    {
        $_SESSION['segundo_apellido'] = "Sin asignar";
        $mostrar = $nombre . " " . $apellido;
    }
    else
    {
        $apellido2 = $_SESSION['segundo_apellido'];
        $key .= "APELLIDO2 = '$apellido2',";
        $mostrar = $nombre . " " . $apellido . " " . $apellido2;
    }
    if(!empty($_SESSION['otros_datos']))
    {
        $otros_datos =  $_SESSION['otros_datos'];
        $key .= "NOTAS = '$otros_datos',";
        $otro = "$otro_lg: $otros_datos";
    }
    else
    {
        $otro = "";
    }
    if(isset($_SESSION['nif']))
    {
        $nif =  $_SESSION['nif'];
        $key .= "NIF = '$nif',";
    }
    $key .= "MOSTRAR = '$mostrar',";
    $key .= "EMAIL1 = '$email',";
    $key .= "TLFNO1 = '$telefono'";

    $sql = "UPDATE CONTACTOS SET $key WHERE CODIGO = ?";
    $stmt = $con->prepare($sql);
    $stmt->bind_param('i',$next);
    $stmt->execute();
    if(!empty($_SESSION['rgpd']))
    {
        $cero = 0;
        $sql = "UPDATE CONTACTOS SET RGPD_1 = ?, RGPD_2 = ?, RGPD_3 = ?, RGPD_4 = ? WHERE CODIGO = ?";
        $stmt = $con->prepare($sql);
        $stmt->bind_param('iiiii',$cero,$cero,$cero,$cero,$codigoAgenda);
        $stmt->execute();
        for($i = 0; $i < count($_SESSION['rgpd']); $i++)
        {
            if($_SESSION['rgpd'][$i] == 1)
            {
                $variable .= "RGPD_1 = " . 1 . ",";
            }
            if($_SESSION['rgpd'][$i] == 2)
            {
                $variable .= "RGPD_2 = " . 2 . ",";
            }
            if($_SESSION['rgpd'][$i] == 3)
            {
                $variable .= "RGPD_3 = " . 3 . ",";
            }
            if($_SESSION['rgpd'][$i] == 4)
            {
                $variable .= "RGPD_4 = " . 4 . ",";
            }
        }
    }
    elseif(empty($_SESSION['rgpd']))
    {
        $cero = 0;
        $sql = "UPDATE CONTACTOS SET RGPD_1 = ?, RGPD_2 = ?, RGPD_3 = ?, RGPD_4 = ? WHERE CODIGO = ?";
        $stmt = $con->prepare($sql);
        $stmt->bind_param('iiiii',$cero,$cero,$cero,$cero,$codigoAgenda);
        $stmt->execute();
    }
}
else
{

    $uno = 1;
    $key .= "NOMBRE,";
    $variable .= "'$nombre',";
    $key .= "APELLIDO1,";
    $variable .= "'$apellido',";
    $key .= "EMAIL1,";
    $variable .= "'$email',";
    if(empty($_SESSION['segundo_apellido']))
    {
        $mostrar = $nombre . " " . $apellido;
    }
    else
    {
        $apellido2 = $_SESSION['segundo_apellido'];
        $key .= "APELLIDO2,";
        $variable .= "'$apellido2',";
        $mostrar = $nombre . " " . $apellido . " " . $apellido2;
    }
    if(isset($_SESSION['nif']))
    {
        $nif =  $_SESSION['nif'];
        $key .= "NIF,";
        $variable .= "'$nif',";
    }
    
    $key .= "TLFNO1,";
    $variable .= "'$telefono',";
    if(!empty($_SESSION['otros_datos']))
    {
        $otros_datos =  $_SESSION['otros_datos'];
        $key .= "NOTAS,";
        $variable .= "'$otros_datos',";
    }
    $next = max_codigo($con,'CONTACTOS') + 1;
    if(isset($_SESSION['rgpd']))
    {
        foreach($_SESSION['rgpd'] as $p)
        {
            $p = htmlspecialchars(mysqli_real_escape_string($con,$p));
            switch($p)
            {
                case 1:
                    $key .= "RGPD_1,";
                    $variable .= "$p,";
                break;
                case 2:
                    $key .= "RGPD_2,";
                    $variable .= "$p,";
                break;
                case 3:
                    $key .= "RGPD_3,";
                    $variable .= "$p,";
                break;
                case 4:
                    $key .= "RGPD_4,";
                    $variable .= "$p,";
                break;
            }
        }
    }
    $key .= "MOSTRAR,";
    $variable .= "'$mostrar',";
    $key .= "ACTIVO,";
    $variable .= "$uno,";
    $key .= "CONTACTO";
    $variable .= "$uno";
    $sql = "INSERT INTO CONTACTOS(CODIGO,USUARIO,$key) VALUES($next,'$usuarioSession',$variable)";
    $con->query($sql);

    if(file_exists('../tmp_img/firma.jpg'))
    {
        $clave = get_id_unico();
        $entrada = get_id_unico();
        $parte = 1;
        $versionDOC = 0;
        $extension = 'JPG';
        $nombreDOC = $mostrar . "-rgpd" . ".jpg";
        $item = '../tmp_img/firma.jpg';

        $size = filesize($item);
        $clave_elemento_padre = get_id_unico();
        $clave_elemento_carpeta_contacto = get_id_unico();

        if(!alias_biblioteca_elementos($con,'##CN_DOCS##'))
        {
            crear_elemento($con,$clave_elemento_padre,utf8_decode($carpeta_contacto_doc_lg),NULL,'##PUBLICO##',NULL,'##PUBLICO##/','C',0,'PUB',$usuarioSession,'WEB',1,NULL,NULL,'##CN_DOCS##');
        }
        else 
        {
            $clave_elemento_padre = alias_biblioteca_elementos($con,'##CN_DOCS##'); 
        }
        if(!alias_biblioteca_elementos($con,"##CN_DOCS_$next##"))
        {
            crear_elemento($con,$clave_elemento_carpeta_contacto,utf8_decode($carpeta_contacto_doc_codigo_lg.$next),NULL,$clave_elemento_padre,NULL,"##PUBLICO##/$clave_elemento_padre",'C',0,'PUB',$usuarioSession,'WEB',1,NULL,NULL,"##CN_DOCS_$next##");
            $clavePAU = $clave_elemento_carpeta_contacto;
        }
        else
        {
            $clavePAU = alias_biblioteca_elementos($con,"##CN_DOCS_$next##");
        }

        $paramGb = valorParametros($con);
        $padre = $clavePAU;
        $acceso = getPAU($con,$clavePAU)['ACCESO'];
        $ubicacion = getPAU($con,$clavePAU)['UBICACION']. "/" . $clavePAU;

        $tipo = 'D';
        $ambito = 'PUB';
        $ordenador = selectOrdenador($con,$usuarioSession); 

        $fopen = fopen($item,'r');
        $fread = fread($fopen,filesize($item));
        fclose($fopen);

        if(selectTable($con,$database_cnx,$size,$paramGb))
        {
            $sufijo = selectTable($con,$database_cnx,$size,$paramGb)['SUFIJO'];
            $table_name = selectTable($con,$database_cnx,$size,$paramGb)['TABLE_NAME'];
        }
        else
        {
            $sufijo = substr(get_id_unico(),0, 14);
            $table_name = createTable($con,$sufijo);
        }

        insertDocInTable($con,$table_name,$clave,$parte,$versionDOC,$fread,$size,$entrada);
        crear_elemento($con,$clave,$nombreDOC,$extension,$padre,$acceso,$ubicacion,$tipo,$size,$ambito,$usuarioSession,$ordenador,$parte,$entrada,$sufijo);

        


        unlink('tmp_img/firma.jpg');
        
    }
    else
    {
        $clave_elemento_padre = get_id_unico();
        $clave_elemento_carpeta_contacto = get_id_unico();

        if(!alias_biblioteca_elementos($con,'##CN_DOCS##'))
        {
            crear_elemento($con,$clave_elemento_padre,utf8_decode($carpeta_contacto_doc_lg),NULL,'##PUBLICO##',NULL,'##PUBLICO##/','C',0,'PUB',$usuarioSession,'WEB',1,NULL,NULL,'##CN_DOCS##');
        }
        else 
        {
            $clave_elemento_padre = alias_biblioteca_elementos($con,'##CN_DOCS##'); 
        }
        if(!alias_biblioteca_elementos($con,"##CN_DOCS_$next##"))
        {
            crear_elemento($con,$clave_elemento_carpeta_contacto,utf8_decode($carpeta_contacto_doc_codigo_lg.$next),NULL,$clave_elemento_padre,NULL,"##PUBLICO##/$clave_elemento_padre",'C',0,'PUB',$usuarioSession,'WEB',1,NULL,NULL,"##CN_DOCS_$next##");
            $clavePAU = $clave_elemento_carpeta_contacto;
        }
        else
        {
            $clavePAU = alias_biblioteca_elementos($con,"##CN_DOCS_$next##");
        }

    }
}
if(isset($_SESSION['rgpd']))
{
    unset($_SESSION['rgpd']);
}
if(isset($_SESSION['segundo_apellido']))
{
    unset($_SESSION['segundo_apellido']);
}
if(isset($_SESSION['otros_datos']))
{
    unset($_SESSION['otros_datos']);
}
if(isset($_SESSION['nif']))
{
    unset($_SESSION['nif']);
}
unset($_SESSION['nombre']);
unset($_SESSION['apellido']);
unset($_SESSION['email']);
unset($_SESSION['telefono']);



if(empty($matricula))
{
    $_SESSION['msg'] = 99;
    header('Location:../tasacion-elegir.php');
    exit;
}
else
{
    $sqlMatricula = "SELECT MATRICULA FROM VEHICULOS WHERE MATRICULA = ?";
    $stmt = $con->prepare($sqlMatricula);
    $stmt->bind_param('s',$matricula);
    $stmt->execute();
    $res = $stmt->get_result();
    if($res->num_rows)
    {
        $key3 .= "MARCA = $marca, ";
        $key3 .= "MODELO = $modelo, "; 
        $key3 .= "CAJACAMBIOS = $cambio, ";
        if(!empty($_POST['version']))
        {
            $version = htmlspecialchars(mysqli_real_escape_string($con,$_POST['version']));
            $key3 .= "VERSION = '$version', ";
        }
        if(!empty($_POST['motor_cc']))
        {
            $motor_cc = htmlspecialchars(mysqli_real_escape_string($con,$_POST['motor_cc']));
            $key3 .= "MOTOR = '$motor_cc', ";
        }
        if(!empty($_POST['potencia']))
        {
            $potencia = htmlspecialchars(mysqli_real_escape_string($con,$_POST['potencia']));
            $key2 .= "POTENCIA = $potencia, ";  
        }
        if(!empty($_POST['bastidor']))
        {
            $bastidor = htmlspecialchars(mysqli_real_escape_string($con,$_POST['bastidor']));
            $key2 .= "BASTIDOR = '$bastidor', ";  
        }
        $key3 .= "CARROCERIA = $carroceria, ";
        $key3 .= "KM = $km,";
        $key3 .= "COLOR_CODIGO = $color, ";
        if(!empty($_POST['fechaMatric']))
        {
            $fecha_matriculacion = htmlspecialchars(mysqli_real_escape_string($con,$_POST['fechaMatric']));
            $key3 .= "MATRICULACION = '$fecha_matriculacion', ";
        }
        $key3 .= "COMBUSTIBLE = $combustible, ";
        if(!empty($_POST['fechaItv']))
        {
            $fecha_itv = htmlspecialchars(mysqli_real_escape_string($con,$_POST['fechaItv']));
            $key3 .= "ITV_ULTIMA = '$fecha_itv', ";
        }
        if(!empty($_POST['otro_equip']))
        {
            $otro_equip = htmlspecialchars(mysqli_real_escape_string($con,$_POST['otro_equip']));
            $key3 .= "OTRO_EQUIP = '$otro_equip', ";
        }
        if(!empty($_POST['velocidades']))
        {
            $velocidades = htmlspecialchars(mysqli_real_escape_string($con,$_POST['velocidades']));
            $key3 .= "VELOCIDADES = $velocidades, ";
        }
        if(isset($_POST['ultmant']))
        {
            $ult_mant = htmlspecialchars(mysqli_real_escape_string($con,$_POST['ultmant']));
            $key3 .= "ULT_MANT = '$ult_mant', ";
        }
        if(!empty($_POST['manual']))
        {
            $manual = htmlspecialchars(mysqli_real_escape_string($con,$_POST['manual']));
            $key3 .= "MANUAL = '$manual', "; 
        }
        if(!empty($_POST['manual']))
        {
            $libro_mantenimiento = htmlspecialchars(mysqli_real_escape_string($con,$_POST['libro_mantenimiento']));
            $key3 .= "LIBRO_MANT = '$libro_mantenimiento',";
        }
        if(!empty($_POST['manual']))
        {
            $importacion = htmlspecialchars(mysqli_real_escape_string($con,$_POST['importacion']));
            $key3 .= "IMPORTACION = '$importacion',";
        }
        
    
        $key3 .= "MANT_SELLADO = $mant_sellado, ";
        $key3 .= "TIPO_SEGURO = $tipo_seguro, ";
        
        
    
        if(!empty($_POST['manual']))
        {
            $matricula = $_SESSION['matricula_search'];
            $key3 .= "MATRICULA = '$matricula'";
        }


        $sql = "UPDATE VEHICULOS SET $key3 WHERE MATRICULA = '$matricula'";
        $con->query($sql);
        $sqlCar = "SELECT CODIGO FROM VEHICULOS WHERE MATRICULA = '$matricula'";
        $resCar = $con->query($sqlCar);
        $filaCar = $resCar->fetch_array();
        $nr = $filaCar['CODIGO'];
    } 
    else
    {
        
        
        $key2 .= "MARCA, ";
        $variable2 .= "$marca, ";
        $key2 .= "MODELO, ";
        $variable2 .= "$modelo, "; 
        $key2 .= "MATRICULA, ";
        $variable2 .= "'$matricula', "; 
        $key2 .= "CAJACAMBIOS, ";
        $variable2 .= "$cambio, "; 
        $key2 .= "CARROCERIA, ";
        $variable2 .= "$carroceria, "; 
        $key2 .= "KM, ";
        $variable2 .= "$km, ";
        $key2 .= "COMBUSTIBLE, ";
        $variable2 .= "$combustible, ";
        $key2 .= "COLOR_CODIGO, ";
        $variable2 .= "$color, ";
        
        
        
        if(!empty($_POST['version']))
        {
            $version = htmlspecialchars(mysqli_real_escape_string($con,$_POST['version']));
            $key2 .= "VERSION, ";
            $variable2 .= "'$version', ";
        }
        if(!empty($_POST['motor_cc']))
        {
            $motor_cc = htmlspecialchars(mysqli_real_escape_string($con,$_POST['motor_cc']));
            $key2 .= "MOTOR, ";
            $variable2 .= "'$motor_cc', ";
        }
        if(!empty($_POST['potencia']))
        {
            $potencia = htmlspecialchars(mysqli_real_escape_string($con,$_POST['potencia']));
            $key2 .= "POTENCIA, ";
            $variable2 .= "$potencia, ";
        }
        if(!empty($_POST['bastidor']))
        {
            $bastidor = htmlspecialchars(mysqli_real_escape_string($con,$_POST['bastidor']));
            $key2 .= "BASTIDOR, ";
            $variable2 .= "'$bastidor', ";
        }
        if(!empty($_POST['fechaMatric']))
        {
            $fecha_matriculacion = htmlspecialchars(mysqli_real_escape_string($con,$_POST['fechaMatric']));
            $key2 .= "MATRICULACION, ";
            $variable2 .= "'$fecha_matriculacion', ";
        }
        if(!empty($_POST['fechaItv']))
        {
            $fecha_itv = htmlspecialchars(mysqli_real_escape_string($con,$_POST['fechaItv']));
            $key2 .= "ITV_ULTIMA, ";
            $variable2 .= "'$fecha_itv', ";
        }
        if(!empty($_POST['velocidades']))
        {
            $velocidades = htmlspecialchars(mysqli_real_escape_string($con,$_POST['velocidades']));
            $key2 .= "VELOCIDADES, ";
            $variable2 .= "$velocidades, ";
        }
        if(!empty($_POST['llaves']))
        {
            $llaves = htmlspecialchars(mysqli_real_escape_string($con,$_POST['llaves']));
            $key2 .= "LLAVES,";
            $variable2 .= "$llaves,";
        }
        if(!empty($_POST['codigo_radio']))
        {
            $codigo_radio = htmlspecialchars(mysqli_real_escape_string($con,$_POST['codigo_radio']));
            $key2 .= "CODIGO_RAD,";
            $variable2 .= "$codigo_radio,";
        }
        if(!empty($_POST['codigo_radio']))
        {
            $codigo_nav = htmlspecialchars(mysqli_real_escape_string($con,$_POST['codigo_nav']));
            $key2 .= "CODIGO_NAV,";
            $variable2 .= "'$codigo_nav',";
        }
        if(!empty($_POST['ultmant']))
        {
            $ult_mant = htmlspecialchars(mysqli_real_escape_string($con,$_POST['ultmant']));
            $key2 .= "ULT_MANT, ";
            $variable2 .= "'$ult_mant', ";
        }
        

        
        
        $key2 .= "MANT_SELLADO, ";
        $variable2 .= "$mant_sellado, ";
        
        $key2 .= "TIPO_SEGURO, ";
        $variable2 .= "$tipo_seguro, ";
        
        
        
        
        
        $manual = htmlspecialchars(mysqli_real_escape_string($con,$_POST['manual']));
        $key2 .= "MANUAL,";
        $variable2 .= "'$manual',"; 
        $libro_mantenimiento = htmlspecialchars(mysqli_real_escape_string($con,$_POST['libro_mantenimiento']));
        $key2 .= "LIBRO_MANT,";
        $variable2 .= "'$libro_mantenimiento',"; 
        $importacion = htmlspecialchars(mysqli_real_escape_string($con,$_POST['importacion']));
        $key2 .= "IMPORTACION,";
        $variable2 .= "'$importacion',"; 
        if(!empty($_POST['otro_equip']))
        {
            $otro_equip = htmlspecialchars(mysqli_real_escape_string($con,$_POST['otro_equip']));
            $key2 .= "OTRO_EQUIP,";
            $variable2 .= "'$otro_equip',";
        }
        $key2 .= 'ESTADO';
        $variable2 .= "'PRS'"; 
        
        
        $nr = max_codigo($con,'VEHICULOS');
        $ano = date('Y');
        $fechahoy = date('d/m/Y');
        $EXP0 = 'EXP000000000000000';

        $idcar = get_contadores($con,'IDCAR0000000000000');
        $mostrar = setMostrarVehiculo($con,$idcar,$marca,$modelo,$matricula);
        $codigo_exp_tipo =  expediente_tipo($con,'VEHICULO_STOCK')[0];
        $descripcion_exp_tipo = expediente_tipo($con,'VEHICULO_STOCK')[1];
        $codigo_esq_estr = esquemas_estructura($con,'VEHICULO');
        $str_replace = substr_replace($EXP0,$codigo_exp_tipo,-strlen($codigo_exp_tipo));
        $contadores = get_contadores($con,$str_replace);
        if(check_expediente($con,$codigo_esq_estr,$contadores) == 0)
        {
            $claveXT = "XT$codigo_exp_tipo";
            $nombreXT = "$descripcion_exp_tipo"; 
            $padreXT = "##EXPEDIENTES##";
            $iconoXT = "expediente";
            $ubicacionXT = "##PUBLICO##/##EXPEDIENTES##/";
    
            $claveXA = "XA$codigo_exp_tipo".".$ano";
            $nombreXA = "$descripcion_exp_tipo"; 
            $padreXA = "##EXPEDIENTES##";
            $iconoXA = "fecha";
            $ubicacionXA = "##PUBLICO##/##EXPEDIENTES##/" . $claveXT . "/";
    
            
            insert_biblioteca_expedientes($con,$contadores,1,$codigo_exp_tipo,0,$contadores);
            insert_biblioteca_expedientes($con,$contadores,2,$codigo_exp_tipo,1,$fechahoy,0,"NOW()");
            insert_biblioteca_expedientes($con,$contadores,3,$codigo_exp_tipo,2,$descripcion_exp_tipo,false,false,$codigo_exp_tipo);
            insert_biblioteca_expedientes($con,$contadores,$codigo_esq_estr,$codigo_exp_tipo,3,$mostrar,false,false,$nr);
    
            if(check_xta($con,"XT$codigo_exp_tipo") == 0)
            {
                crear_xta($con,$claveXT,$nombreXT,$padreXT,$usuarioSession,$iconoXT,$ubicacionXT);
            }
            else
            {
                if(check_xta($con,$claveXA) == 0)
                {
                    $acceso = check_acceso($con,$claveXT);
                    crear_xta($con,$claveXA,$ano,$claveXT,$usuarioSession,$iconoXA,$ubicacionXA,$acceso);
                }
                else
                {
                    $claveEXP = get_id_unico();
                    $padre = $claveXA;
                    $ubicacion = $ubicacionXA . "$claveXA/";
                    $acceso = check_acceso($con,$claveXA);
                    crear_xta($con,$claveEXP,$mostrar,$padre,$usuarioSession,$iconoXT,$ubicacion,$acceso,$contadores);
                    insert_biblioteca_etiquetas($con,get_id_unico(),$claveEXP,$contadores,1,-1);
    
    
                    $sql = "INSERT INTO VEHICULOS(CODIGO,USUARIO,TIPO,ACTIVO,IDCAR,ALTA,MOSTRAR,$key2) VALUES($nr,'$usuarioSession','VO',1,'$idcar',NOW(),'$mostrar',$variable2)";
                    $con->query($sql);
                    if(isset($_POST['equipamiento']))
                    {
                        foreach($_POST['equipamiento'] as $e)
                        {
                            $e = htmlspecialchars(mysqli_real_escape_string($con,$e));
                            $sqle = "INSERT INTO VEHICULOS_OPCIONES(VEHICULO,OPCION) VALUES(?,?)";
                            $stmt = $con->prepare($sqle);
                            $stmt->bind_param('ii',$nr,$e);
                            $stmt->execute();
                        }
                    }

                }
            }
        }
        
        
    
        
    }
    
    $tas = get_contadores($con,'TAS000000000000000'); 
    $codigo_tas = get_id_unico();
    $activo = 0;
    $franquicia = !empty($_POST['franquicia']) ? htmlspecialchars(mysqli_real_escape_string($con,$_POST['franquicia'])) : 0;
    $aseguradora = !empty($_POST['aseguradora']) ? htmlspecialchars(mysqli_real_escape_string($con,$_POST['aseguradora'])) : 0;
    $procedencia = !empty($_POST['procedencia']) ? htmlspecialchars(mysqli_real_escape_string($con,$_POST['procedencia'])) : 0;
    $nro_partes = !empty($_POST['nro_partes']) ? htmlspecialchars(mysqli_real_escape_string($con,$_POST['nro_partes'])) : 0;
    $sql = "INSERT INTO VEHICULOS_TASACIONES(CODIGO,VEHICULO,MATRICULA,CONTACTO,KM,FECHA,TASACION,USUARIO,ACTIVO,TIPO_SEGURO,MANT_SELLADO,FRANQUICIA,ASEGURADORA,PROCEDENCIA,NUM_PARTES) VALUES(?,?,?,?,?,NOW(),?,?,?,?,?,?,?,?,?)";
    $stmt = $con->prepare($sql);
    $stmt->bind_param('sisiissiiiiiii',$codigo_tas,$nr,$matricula,$next,$km,$tas,$usuarioSession,$activo,$tipo_seguro,$mant_sellado,$franquicia,$aseguradora,$procedencia,$nro_partes);
    $stmt->execute();

    if(!empty($_POST['notasOtras']))
    {   
        $max = getMaxCod($con,'POS','VEHICULOS_NOTAS');
        $obs = htmlspecialchars(mysqli_real_escape_string($con,$_POST['notasOtras']));
        $variableTas = 'EXPVEH';

        $sql = "INSERT INTO VEHICULOS_NOTAS(CLAVE,POS,FECHA,USUARIO,NOTA,CODIGO_TAS,VARIABLE_TAS) VALUES(?,?,NOW(),?,?,?,?)";
        $stmt = $con->prepare($sql);
        $stmt->bind_param('iissss',$nr,$max,$usuarioSession,$obs,$codigo_tas,$variableTas);
        $stmt->execute();
    }


    historial($con,7,$nr,$email);
    $_SESSION['msg'] = 1;
    $_SESSION['TAS'] = $tas;
    if(isset($_POST['guardar']))
    {
        header('Location:../tasacion-elegir.php');
        exit;
    }
    else
    {
        header("Location:../tasacion-revision-documental.php?matricula=$matricula&codigo_inactivo=$codigo_tas");
         exit;
    }
 
}




?>