<?php
$brand_id = $MotherCar->find_my_code($bd_conn->query('SELECT CODIGO, DESCRIPCION AS D FROM VEHICULOS_MARCAS'), $brand, true);

if($brand_id) {
    $model_id = $MotherCar->find_my_code($Schema->executeQuery('SELECT CODIGO, DESCRIPCION AS D FROM VEHICULOS_MODELOS WHERE MARCA = ?', 'i', [$brand_id]), $model);

    if($model_id) {

        $car_fuel_id = $MotherCar->find_my_code( $Schema->executeQuery('SELECT CODIGO, DESCRIPCION_SP AS D FROM VEHICULOS_LITERALES WHERE TIPO = ?', 's', ['TIP_COM']), $car_fuel, true);
        $MotherCar->set_combustible($car_fuel_id);

        $car_gearbox_id = $MotherCar->find_my_code( $Schema->executeQuery('SELECT CODIGO, DESCRIPCION_SP AS D FROM VEHICULOS_LITERALES WHERE TIPO = ?', 's', ['TIP_CAJ']), $car_gearbox, true);
        $MotherCar->set_cajacambios($car_gearbox_id);


        $car_emissions_id = $MotherCar->find_my_code( $Schema->executeQuery('SELECT CODIGO, DESCRIPCION_SP AS D FROM VEHICULOS_LITERALES WHERE TIPO = ?', 's', ['DIS_AMB']), $car_emissions, true);
        $MotherCar->set_distintivo_ambiental($car_emissions_id);


        $MotherCar->set_marca($brand_id);
        $MotherCar->set_modelo($model_id);
        $MotherCar->set_activo(1);
        $MotherCar->set_estado('STK');
        $MotherCar->set_matricula($enrollment);
        $MotherCar->set_version($car_version);
        $MotherCar->set_color_principal_literal($car_color);
        $MotherCar->set_matriculacion($enrollment_date);
        $MotherCar->set_ano_fabricacion($car_year);
        $MotherCar->set_eurotax($eurotax);
        $MotherCar->set_km($car_km);
        $MotherCar->set_venta_total_sin_dto($price);
        $MotherCar->set_venta_total($special_price);
        $MotherCar->set_notas($car_note);
        $MotherCar->set_code_ext($stock);

        //Other prices
        $MotherCar->set_tipo_precios_extra(1);
        $MotherCar->set_total_sin_dto_precios_extra($financed_price);
        $MotherCar->set_total_precios_extra($special_financed_price);

        


        $wsCar = $Schema->executeQuery('SELECT CODIGO, IDCAR, MOSTRAR, BASTIDOR FROM VEHICULOS WHERE STOCK = ? AND BASTIDOR = ?', 'is', [$stockID['CODIGO'], $chassis])->fetch_assoc();
        if($wsCar['CODIGO']) {//Actualizar
            $status_query = 1;
            $MotherCar->set_codigo_vehiculo_tabla_vehiculos($wsCar['CODIGO']);
            $MotherCar->set_mostrar($wsCar['IDCAR'] . ' - ' . $MotherCar->nombre_vehiculo($brand_id, $model_id, ' - ') . $enrollmentTitle);
            $save = $MotherCar->update_vehiculo();
        } else {//Insertar
            $status_query = 0;
            $MotherCar->set_codigo_vehiculo_tabla_vehiculos($MotherCar->carId());
            $carId = Statics::get_contadores($bd_conn, 'IDCAR0000000000000');
            $MotherCar->set_usuario_session($headers['Client-Id']);
            $MotherCar->set_id_car($carId);
            $MotherCar->set_mostrar($carId . ' - ' . $MotherCar->nombre_vehiculo($brand_id, $model_id, ' - ') . $enrollmentTitle);
            $MotherCar->set_bastidor($chassis);
            $MotherCar->set_stock($stockID['CODIGO']);
            $save = $MotherCar->insert_vehiculo();
        }

        if($save) {
            if($status_query) {
                $data['message'] = 'Car updated';
                !empty($financed_price) ? $MotherCar->update_precios_extra() : false;
                Statics::add_trace_history($bd_conn, $headers['Client-Id'], $wsCar['CODIGO'], 2, 'WS - servMultiPost');
            } else {
                $data['message'] = 'Car inserted';
                !empty($financed_price) ? $MotherCar->insert_precios_extra() : false;
                Statics::add_trace_history($bd_conn, $headers['Client-Id'], $MotherCar->get_codigo_vehiculo_tabla_vehiculos(), 1,  'WS - servMultiPost');
            }


            //Imgs
            if(isset($_POST['imgs'])) {
                $orden = 1;
                $data['images_bucket'] = ['images_message' => '', 'bucket' => []];
                $res = $Schema->executeQuery('SELECT * FROM VEHICULOS_MULTIMEDIA_LINKS WHERE VEHICULO = ? AND ACTIVO = ?', 'ii', [$MotherCar->get_codigo_vehiculo_tabla_vehiculos(), 1]);
                if($res->num_rows) { //Desactivar las imagenes antiguas
                    $MotherCar->set_activo_link(0);
                    $MotherCar->update_links();
                }
                $data['images_bucket']['images_message'] = 'Images uploaded';
                foreach($_POST['imgs'] as $link) { //Meter las nuevas imagenes
                    $link = Statics::SafeInput($bd_conn, $link);
                    $MotherCar->set_codigo_link(Statics::get_id_unico());
                    $MotherCar->set_orden_link($orden++);
                    $MotherCar->set_tipo_link(1);
                    $MotherCar->set_link($link);
                    $MotherCar->set_origen_link($stock);
                    array_push($data['images_bucket']['bucket'], $link);
                    $MotherCar->insert_links();
                }
            }
            
            //Multipost section
            $MotherCar->set_portal($portal_info['key']);
            $MotherCar->insert_portal();
            $dev['devs']['portal_key'] =  $MotherCar->get_portal();
            $data['portal'] = $portal_info['title'];
            Statics::add_trace_history($bd_conn, $headers['Client-Id'], $MotherCar->get_codigo_vehiculo_tabla_vehiculos(), 17,  'WS - servMultiPost update post: ' . $portal_info['title']);


            //Response
            $data['car']['car_chassis'] = $chassis;
            $data['car']['brand'] = $brand;
            $data['car']['model'] = $model;
            $data['car']['car_enrollment'] = $MotherCar->get_matricula();
            $data['car']['car_price'] = $MotherCar->get_venta_total_sin_dto();
            $data['car']['car_special_price'] = $MotherCar->get_venta_total();
            $data['car']['financed_price'] = $MotherCar->get_total_sin_dto_precios_extra();
            $data['car']['special_financed_price'] = $MotherCar->get_total_precios_extra();
            $data['car']['emissions'] = $car_emissions;
            $data['car']['gearbox'] = $car_gearbox;
            $data['car']['fuel'] = $car_fuel;
    
            $dev['devs']['car_key'] = $MotherCar->get_codigo_vehiculo_tabla_vehiculos();
            $dev['devs']['car_brand_key'] = $brand_id;
            $dev['devs']['car_model_key'] = $model_id;
            $dev['devs']['car_fuel_key'] = $car_fuel_id;
            $dev['devs']['car_gearbox_key'] = $car_gearbox_id;
            $dev['devs']['car_emissions_key'] = $car_emissions_id;
        } else {
            $data['status'] = 'Fail';
            $data['message'] = 'Unable to write log';
        }


    } else {
        $data['status'] = 'Fail';
        $data['message'] = 'Unable to find model car id, check string again';
    }


} else {
    $data['status'] = 'Fail';
    $data['message'] = 'Unable to find brand id, check string again';
}












?>