<?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/Bibliotecas.php');
include('../class/Tasaciones.php');
include('../class/Static.php');
include('../class/WebServices.php');
include('../lg/config_vo.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');
}
require_once __DIR__ . '../../vendor/autoload.php';
$Schema = new Schema($con, $database);
$MotherCar = new MotherCar($con);
$Expediente = new Expediente($con);
$Tasaciones = new Tasaciones($con);
$Bibliotecas = new Bibliotecas($con);
$json = [];
$request = Statics::SafeInput($con, $_POST['request']);
$json['request'] = $request;
switch($request) {
    case 1:
        
        $car_key = Statics::SafeInput($con, $_POST['car_key']);
        $total_compra = Statics::SafeInput($con, $_POST['compra']);
        $total_venta = Statics::SafeInput($con, $_POST['base']);
        $marca = Statics::SafeInput($con, $_POST['marca']);
        $modelo = Statics::SafeInput($con, $_POST['modelo']);
        $eurotax = isset($_POST['eurotax']) ? Statics::SafeInput($con, $_POST['eurotax']) : false;
        $rebu = Statics::SafeInput($con, $_POST['rebu']);
        $stock = Statics::SafeInput($con, $_POST['stock']);
        if($rebu == 1) {
            $MotherCar->set_compra_tipo_iva(1);
            $MotherCar->set_venta_tipo_iva(1);
            $compra = $total_compra / 1.21;
            $venta = $total_venta  / 1.21;
        } else {
            $MotherCar->set_compra_tipo_iva(3);
            $MotherCar->set_venta_tipo_iva(3);
            $compra = $total_compra;
            $venta = $total_venta;
        }
        $ano_matriculacion = Statics::SafeInput($con, $_POST['ano_matriculacion']);
        $version = Statics::SafeInput($con, $_POST['version']);
        $km = Statics::SafeInput($con, $_POST['km']);
        $fecha_matriculacion = Statics::SafeInput($con, $_POST['fecha_matriculacion']);
        $procedencia = Statics::SafeInput($con, $_POST['procedencia']);
        $MotherCar->set_precio_compra_pff($compra);
        $MotherCar->set_precio_compra_base($compra);
        $MotherCar->set_precio_compra_total($total_compra);
        $MotherCar->set_precio_venta_pff($venta);
        $MotherCar->set_venta_base($venta);
        $MotherCar->set_venta_total($total_venta);
        $MotherCar->set_version($version);
        $MotherCar->set_ano_fabricacion($ano_matriculacion);
        $MotherCar->set_matriculacion($fecha_matriculacion);
        $MotherCar->set_km($km);
        $MotherCar->set_procedencia($procedencia);
        $MotherCar->set_estado('STK');
        $MotherCar->set_stock($stock);
        $MotherCar->set_eurotax($eurotax);
        $MotherCar->set_rebu($rebu);


        if($car_key) {
            $res = $Schema->executeQuery('SELECT CODIGO, IDCAR FROM VEHICULOS WHERE CODIGO = ?', 'i', [$car_key]);
            if($res->num_rows) {
                $row = $res->fetch_array();
                $MotherCar->set_codigo_vehiculo_tabla_vehiculos($car_key);
                $MotherCar->set_id_car($row['IDCAR']);
                $MotherCar->update_vehiculo();
                $json['car_key'] = $car_key;
                $json['status'] = true;
                $json['message'] = 'Success update';

            } else {
                $json['status'] = false;
                $json['message'] = 'Invalid update';
            }
        } else {
            $bastidor = Statics::SafeInput($con, $_POST['bastidor']);
            $matricula = Statics::SafeInput($con, $_POST['matricula']);
            $MotherCar->set_bastidor($bastidor);
            $MotherCar->set_matricula($matricula);
            $mostrarMatricula = !empty($matricula) ? ' - ' . $matricula : '';

            $res = $Schema->executeQuery('SELECT CODIGO FROM VEHICULOS WHERE BASTIDOR = ? OR MATRICULA = ?', 'ss', [$bastidor, $matricula]);
            if($res->num_rows) {
                $json['status'] = false;
                $json['message'] = 'Invalid chassis';
            } else {
                $car_key = Statics::max_codigo($con, 'VEHICULOS');
                $idcar = Statics::get_contadores($con,'IDCAR0000000000000');
                $MotherCar->set_codigo_vehiculo_tabla_vehiculos($car_key);
                $MotherCar->set_usuario_session($usuarioSession);
                $MotherCar->set_id_car($idcar);
                $MotherCar->set_marca($marca);
                $MotherCar->set_modelo($modelo);
                $MotherCar->set_activo(1);
                $MotherCar->set_mostrar($idcar . ' - ' . $MotherCar->nombre_vehiculo($marca, $modelo) . $mostrarMatricula);
                $save = $MotherCar->insert_vehiculo();
                if($save) {
                    $json['car_key'] = $car_key;
                    $json['status'] = true;
                    $json['message'] = 'Success insert';
                } else {
                    $json['status'] = false;
                    $json['message'] = 'Invalid insert';
                }
            }
        }
    break;
    case 2:
        if(!empty($_FILES)) {
            $target_dir = "../tmp_img/";
            $codigo_vehiculo = Statics::SafeInput($con, $_POST['codigo_vehiculo']);
            $res = $Schema->executeQuery('SELECT MARCA, MODELO, MOSTRAR, IDCAR FROM VEHICULOS WHERE CODIGO = ?', 'i', [$codigo_vehiculo]);
            $row = $res->fetch_array();
            $mostrar = $row['MOSTRAR'];

            $Schema->set_ubicacion_archivos($target_dir)->get_ubicacion_archivos();
            $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'); 
            } 
            
            $sql_pos = 'SELECT MAX(E.POS) AS MAX_POS
            FROM BIBLIOTECA_ELEMENTOS E 
            INNER JOIN BIBLIOTECA_ETIQUETAS T ON T.CLAVE = E.CLAVE
            WHERE T.ETIQUETA = ? AND E.PAPELERA = ?';
            $res_pos = $Schema->executeQuery($sql_pos, 'ii', [$codigo_vehiculo, 0]);
            $row_pos = $res_pos->fetch_array();
            $posicion = $row_pos['MAX_POS'] + 1;
            $clave = $Schema->set_clave_elemento(get_id_unico())->get_clave_elemento();
            $name = $_FILES['file']['name'];
            $tmp = $_FILES['file']['tmp_name'];
            $size = $_FILES['file']['size'];
            $part = pathinfo($name);
            $extension = $part['extension'];
            $name = Statics::rename($extension, $posicion, $con, $row['IDCAR']);
            if($part['extension'] != 'pdf') {
                $Schema->set_resize_img(TRUE);
            } else {
                $posicion = 0;
            }
            $Schema->upload_doc($tmp, $name, $size, $claveEXP, $acceso, $ubicacion, $usuarioSession, $codigo_vehiculo, $posicion);

            $codigo_biblioteca_etiquetas = get_id_unico();
            $Schema->asignar_etiquetas_nuevo_expediente($codigo_biblioteca_etiquetas, $codigo_vehiculo, $mostrar, TRUE, TRUE);
            
            
            
            $json['status'] = true;
            $json['car_key'] = $codigo_vehiculo;
            $json['message'] = 'Successful';
            $json['explicit'] = 'Successful upload img';
            $json['file_key'] = $clave;
        } else {
            $json['status'] = false;
            $json['message'] = 'Fail';
            $json['explicit'] = 'Invalid request for upload';
        }
    break;
    case 3:
        $key = Statics::SafeInput($con, $_POST['key']);
        $Schema->executeQuery('UPDATE BIBLIOTECA_ELEMENTOS SET PAPELERA = ? WHERE CLAVE = ?', 'is', [1, $key]);
        $json['status'] = true;
        $json['message'] = 'Successful';
        $json['explicit'] = 'Successful removed file';

    break;

    // Request 4: se utiliza para actualizar mediante ajax los formularios de vehículo en caso de modificar los desplegables de marca o modelo.
    case 4:
        $ws = new WebServices();
        $subrequest = Statics::SafeInput($con, $_POST['subrequest']);
        $dataMAIN = [
            'grant_type'        =>      'client_credentials',
            'client_secret'     =>      $client_secret_api_p0,
            'client_id'         =>      $client_id_api_p0,
            'service'           =>      'servToken',
            'code'              =>      '8356e8922cdccb82gh538fu2'
        ];
        $token = $ws->curlPost($url_api_p0, $dataMAIN);
        switch($subrequest) {
            
            // Subrequest 4.1: es llamado cuando se cambia la marca
            case 1:
                $json['model'][0]['key'] = '';
                $json['model'][0]['title'] = $modelo_lg;
                $json['model'][0]['eurotax'] = '';
                $json['type']['key'] = '';
                $json['type']['name'] = $version_lg;
                if(!empty($_POST['make'])) {
                    $make = Statics::SafeInput($con, $_POST['make']);
                    $json['x'] = $make;
                    $res = $Schema->executeQuery('SELECT CODIGO, DESCRIPCION, EUROTAX  FROM VEHICULOS_MODELOS WHERE MARCA = ? ORDER BY DESCRIPCION ASC', 'i', [$make]);
                    if($res->num_rows) {
                        $i = 1;
                        while($row = $res->fetch_array()) {
                            $json['model'][$i]['key'] = $row['CODIGO'];
                            $json['model'][$i]['title'] = $row['DESCRIPCION'];
                            $json['model'][$i]['eurotax'] = $row['EUROTAX'];
                            $i++;
                        }
                    }
                }
            break;
            
            // Subrequest 4.2: es llamado cuando se cambia el modelo
            case 2:
                if(isset($_POST['model'])) {
                    $make = Statics::SafeInput($con, $_POST['make']);
                    $model = Statics::SafeInput($con, $_POST['model']);
                    $headers = [
                        'authorization-token: Bearer ' . $token->servToken->client_token,
                        'client-id: ' . $client_id_api_p0,
                        'p0-api-key: 928efda211f31bdf649e31c48bcf5ab2f65'
                    ];
                    $body = [
                        'service'   =>  'servType',
                        'make'      =>  $make,
                        'model'     =>  $model
                    ];
                    $type = $ws->curlPost($url_api_p0, $body, $headers);
                    $json['type'] = $type->cars_type;
                }
            break;
            default:
                $json['status'] = false;
                $json['message'] = 'Invalid request';
        }
    break;
    case 'price_up':
        if(isset($_SESSION['CODIGO_COCHE'])) {
            $subrequest = Statics::SafeInput($con, $_POST['subrequest']);
            $rebu = Statics::SafeInput($con, $_POST['rebu']);
            $pff = Statics::SafeInput($con, $_POST['pff']);
            $main_iva = Statics::SafeInput($con, $_POST['main_iva']);
            $total = Statics::SafeInput($con, $_POST['total']);
            $MotherCar->set_codigo_vehiculo_tabla_vehiculos($_SESSION['CODIGO_COCHE']);
            if(isset($_POST['base'])) {
                $json['y'] = 'base yes';
                $expenses = Statics::SafeInput($con, $_POST['expenses']);
                $amount = Statics::SafeInput($con, $_POST['amount']);
                $percent = Statics::SafeInput($con, $_POST['percent']);
                $base = Statics::SafeInput($con, $_POST['base']);
                $iva = Statics::SafeInput($con, $_POST['iva']);
                $MotherCar->set_tipo_precios_extra($subrequest);
                $MotherCar->set_base_precios_extra($base);
                $MotherCar->set_dto_imp_precios_extra($amount);
                $MotherCar->set_dto_prc_precios_extra($percent);
                $MotherCar->set_total_precios_extra($total);
                $res = $Schema->executeQuery('SELECT CODIGO FROM VEHICULOS_PRECIOSEXTRAS WHERE CODIGO = ? AND TIPO = ?', 'ii', [ $_SESSION['CODIGO_COCHE'], $subrequest])->num_rows;//para insertar o actualizar en la tabla preciosextras
            } else {
                $json['y'] = 'base no';

            }
            switch($subrequest) {
                case -1:
                    $MotherCar->set_compra_tipo_iva($main_iva);
                    $MotherCar->set_precio_compra_pff($pff);
                    $MotherCar->set_precio_compra_base($pff);
                    $MotherCar->set_precio_compra_total($total);
                    $MotherCar->set_rebu($rebu);
                    $MotherCar->update_vehiculo();
                break;
                case 3:
                    $MotherCar->set_venta_tipo_iva($main_iva);
                    $MotherCar->set_precio_venta_pff($pff);
                    $MotherCar->set_venta_base($base);
                    $MotherCar->set_venta_total($total);
                    $MotherCar->set_rebu($rebu);
                    $MotherCar->set_venta_dto_imp($amount);
                    $MotherCar->set_venta_dto_prc($percent);
                    $MotherCar->set_gastos_gestion($expenses);
                    $MotherCar->update_vehiculo();
                break;
                case 1:
                    $res ? $MotherCar->update_precios_extra() : $MotherCar->insert_precios_extra();
                break;
                case 2:
                    $res ? $MotherCar->update_precios_extra() : $MotherCar->insert_precios_extra();
                break;
            }
            $json['status'] = true;
        } else {
            $json['status'] = false;
            $json['message'] = 'Invalid request';
        }
    break;
    case 'eurotaxRequest':
        /* 
        *   @param string $client_secret_api_p0 => se encuentra en el archivo '../lg/config_vo.php'
        *   @param string $client_id_api_p0 => se encuentra en el archivo '../lg/config_vo.php'
        *   @param string $url_api_p0 => se encuentra en el archivo '../lg/config_vo.php'
        *   @param string $token->servToken->client_token es el token de validación
        */
        $ws = new WebServices();
        $token = $ws->curlPost($url_api_p0, [
            'grant_type'        =>      'client_credentials',
            'client_secret'     =>      $client_secret_api_p0,
            'client_id'         =>      $client_id_api_p0,
            'service'           =>      'servToken',
            'code'              =>      '8356e8922cdccb82gh538fu2'
        ], false);
        if($token->servToken->client_token) {
            $gear = $ws->curlPost($url_api_p0, [
                "service"       =>      'servEquipment',
                "eurotax_code"  =>      Statics::SafeInput($con, $_POST['eurotaxCode'])
            ], [
                'authorization-token: Bearer ' . $token->servToken->client_token,
                'client-id: ' . $client_id_api_p0,
                'p0-api-key: c05207b51c09baf6323a34487acf9b63'
            ]);
            $json['status'] = true;
            $json['message'] = 'Successful';
            $json['gear'] = !empty($gear->equipment) ? $gear->equipment : false;
        } else {
            $json['status'] = false;
            $json['message'] = 'Fail request';
        }
    break;
    default:
        $json['status'] = false;
        $json['message'] = 'Invalid request';
}

echo json_encode($json);

?>

