<?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/functions.php');
include('../includes/esquemas.php');
include('../class/Schema.php');
include('../class/MotherCar.php');
include('../class/Expediente.php');
include('../class/Static.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');
}
$Schema = new Schema($con);
$MotherCar = new MotherCar($con);
$Expediente = new Expediente($con);



$contacto_tasacion = Statics::SafeInput($con, $_POST['contacto_tasacion']);
$marca = Statics::SafeInput($con, $_POST['marca']);
$modelo = Statics::SafeInput($con, $_POST['modelo']);
$version = empty($_POST['version']) ? '' : Statics::SafeInput($con, $_POST['version']);
$motor_cc = empty($_POST['motor_cc']) ? '' : Statics::SafeInput($con, $_POST['motor_cc']);
$potencia = empty($_POST['potencia']) ? '' : Statics::SafeInput($con, $_POST['potencia']);
$matricula = Statics::SafeInput($con, $_POST['matricula']);
$bastidor = empty($_POST['bastidor']) ? '' : Statics::SafeInput($con, $_POST['bastidor']);
$fecha_matriculacion = empty($_POST['fecha_matriculacion']) ? '' : Statics::SafeInput($con, $_POST['fecha_matriculacion']);
$itv_proxima = empty($_POST['itv_proxima']) ? '' : Statics::SafeInput($con, $_POST['itv_proxima']);
$combustible = empty($_POST['combustible']) ? 0 : Statics::SafeInput($con, $_POST['combustible']);
$km = empty($_POST['km']) ? 0 : Statics::SafeInput($con, $_POST['km']);
$color = empty($_POST['color']) ? 0 : Statics::SafeInput($con, $_POST['color']);
$cajacambio = empty($_POST['cajacambio']) ? 0 : Statics::SafeInput($con, $_POST['cajacambio']);
$velocidades = empty($_POST['velocidades']) ? 0 : Statics::SafeInput($con, $_POST['velocidades']);
$llaves = empty($_POST['llaves']) ? 0 : Statics::SafeInput($con, $_POST['llaves']);
$procedencia = empty($_POST['procedencia']) ? 0 : Statics::SafeInput($con, $_POST['procedencia']);
$manual = empty($_POST['manual']) ? 0 : Statics::SafeInput($con, $_POST['manual']);
$libro = empty($_POST['libro']) ? 0 : Statics::SafeInput($con, $_POST['libro']);
$ultimo_mant = empty($_POST['ultimo_mant']) ? 0 : Statics::SafeInput($con, $_POST['ultimo_mant']);
$franquicia = empty($_POST['franquicia']) ? 0 : Statics::SafeInput($con, $_POST['franquicia']);
$aseguradora = empty($_POST['aseguradora']) ? 0 : Statics::SafeInput($con, $_POST['aseguradora']);
$nro_partes = empty($_POST['nro_partes']) ? 0 : Statics::SafeInput($con, $_POST['nro_partes']);
$codigo_radio = empty($_POST['codigo_radio']) ? 0 : Statics::SafeInput($con, $_POST['codigo_radio']);
$codigo_nav = empty($_POST['codigo_nav']) ? 0 : Statics::SafeInput($con, $_POST['codigo_nav']);
$importacion = empty($_POST['importacion']) ? 0 : Statics::SafeInput($con, $_POST['importacion']);

$MotherCar->set_marca($marca);
$MotherCar->set_modelo($modelo);
$MotherCar->set_matricula($matricula);
$MotherCar->set_bastidor($bastidor);
$MotherCar->set_color_principal($color);
$MotherCar->set_cajacambios($cajacambio);
$MotherCar->set_activo(1);
$MotherCar->set_combustible($combustible);
$MotherCar->set_estado('PRS');
$MotherCar->set_version($version);
$MotherCar->set_motor_cc($motor_cc);
$MotherCar->set_potencia($potencia);
$MotherCar->set_matriculacion($fecha_matriculacion);
$MotherCar->set_importacion($importacion);
$MotherCar->set_manual($manual);
$MotherCar->set_libro_mant($libro);
$MotherCar->set_velocidades($velocidades);
$MotherCar->set_itv_proxima($itv_proxima);
$MotherCar->set_km($km);
$MotherCar->set_llaves($llaves);
$MotherCar->set_procedencia($procedencia);
$MotherCar->set_codigo_radio($codigo_radio);
$MotherCar->set_codigo_navegador($codigo_nav);


$res = $Schema->executeQuery('SELECT CODIGO, IDCAR FROM VEHICULOS WHERE MATRICULA = ?', 's', [$matricula]);
if(!$res->num_rows) {
    $codigo_vehiculo = Statics::max_codigo($con, 'VEHICULOS');
    $idcar = Statics::get_contadores($con,'IDCAR0000000000000');
    $MotherCar->set_codigo_vehiculo_tabla_vehiculos($codigo_vehiculo);
    $MotherCar->set_usuario_session($usuarioSession);
    $MotherCar->set_id_car($idcar);
    $mostrar = $idcar . ' - ' . $MotherCar->nombre_vehiculo($marca, $modelo) . ' - ' . $matricula;
    $MotherCar->set_mostrar($mostrar);
    $MotherCar->insert_vehiculo();
} else {
    $row = $res->fetch_array();
    $codigo_vehiculo = $row['CODIGO'];
    $MotherCar->set_codigo_vehiculo_tabla_vehiculos($codigo_vehiculo);
    $mostrar = $row['IDCAR'] . ' - ' . $MotherCar->nombre_vehiculo($marca, $modelo) . ' - ' . $matricula;
    $MotherCar->set_mostrar($mostrar);
    $MotherCar->update_vehiculo();
}

if($_POST['control_tasacion']) {
    $codigo_tasacion = Statics::SafeInput($con, $_POST['control_tasacion']);
} else {
    $EXP0 = 'EXP000000000000000';
    $codigo_exp_tipo = $Schema->select_expediente_tipos_valores('VEHICULO_STOCK');
    $descripcion_exp_tipo = $Schema->select_expediente_tipos_valores('VEHICULO_STOCK', 'DESCRIPCION');
    $codigo_esq_estr = $Schema->select_esquema_estructura_valores('VEHICULO', -1);
    $str_replace = substr_replace($EXP0,$codigo_exp_tipo,-strlen($codigo_exp_tipo));
    $contadores = $Expediente->check_contador_expediente($codigo_vehiculo) ? $Expediente->check_contador_expediente($codigo_vehiculo) : Statics::get_contadores($con,$str_replace);
    
    if($Expediente->check_expediente($codigo_esq_estr, $contadores)) {
        $claveXT = "XT$codigo_exp_tipo";
        $nombreXT = $descripcion_exp_tipo; 
        $padreXT = "##EXPEDIENTES##";
        $iconoXT = "expediente";
        $ubicacionXT = "##PUBLICO##/##EXPEDIENTES##/";
        $ano = date('Y');
        $fechahoy = date('d/m/Y');
    
        $claveXA = "XA$codigo_exp_tipo".".$ano";
        $nombreXA = $descripcion_exp_tipo; 
        $padreXA = "##EXPEDIENTES##";
        $iconoXA = "fecha";
        $ubicacionXA = "##PUBLICO##/##EXPEDIENTES##/" . $claveXT . "/";
    
        $Expediente->insert_biblioteca_expedientes_valores($contadores,1,$codigo_exp_tipo,0,$contadores);
        $Expediente->insert_biblioteca_expedientes_valores($contadores,2,$codigo_exp_tipo,1,$fechahoy,0,"NOW()");
        $Expediente->insert_biblioteca_expedientes_valores($contadores,3,$codigo_exp_tipo,2,$descripcion_exp_tipo,false,false,$codigo_exp_tipo);
        $Expediente->insert_biblioteca_expedientes_valores($contadores,$codigo_esq_estr,$codigo_exp_tipo,3,$mostrar,false,false,$codigo_vehiculo);
    
        if ($Expediente->check_expediente_carpeta($claveXT) == 0) {
            $Expediente->crear_carpeta_expediente($claveXT, $nombreXT, $padreXT, $usuarioSession, $iconoXT, $ubicacionXT);
        } 
        if ($Expediente->check_expediente_carpeta($claveXA) == 0) {
            $acceso = $Expediente->select_acceso_biblioteca_elementos($claveXT);
            $Expediente->crear_carpeta_expediente($claveXA, $ano, $claveXT, $usuarioSession, $iconoXA, $ubicacionXA, $acceso);
        } else {
            $acceso = $Expediente->select_acceso_biblioteca_elementos($claveXA);
        }
    
        $claveEXP = get_id_unico();
        $padre = $claveXA;
        $ubicacion = $ubicacionXA . "$claveXA/";
        $Expediente->crear_carpeta_expediente($claveEXP,$mostrar,$padre,$usuarioSession,$iconoXT,$ubicacion,$acceso,$contadores);
        $Expediente->insert_biblioteca_etiquetas_expediente(get_id_unico(),$claveEXP,$contadores,1,-1);
    } else {
        $claveEXP = $Expediente->select_clave_padre_acceso_ubicacion_expediente($codigo_vehiculo);
        $acceso = $Expediente->select_clave_padre_acceso_ubicacion_expediente($codigo_vehiculo, 'ACCESO');
        $ubicacion = $Expediente->select_clave_padre_acceso_ubicacion_expediente($codigo_vehiculo, 'UBICACION');  
    
    }
    $codigo_tasacion = Statics::get_id_unico();
    $values = [$codigo_tasacion, $codigo_vehiculo, $matricula, $contacto_tasacion, $km, date('Y-m-d H:i:s'), Statics::get_contadores($con,'TAS000000000000000'), $usuarioSession, $nro_partes, $ultimo_mant, $franquicia, 1];
    $Schema->executeQuery('INSERT INTO VEHICULOS_TASACIONES(CODIGO, VEHICULO, MATRICULA, CONTACTO, KM, FECHA, TASACION, USUARIO, NUM_PARTES, ULT_MANT, FRANQUICIA, ACTIVO) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', 'sisiisssisdi', $values);
}

header('Location:../tasacion-abierta.php?c=' . $codigo_tasacion);

?>