<?php
include_once ('auth.php'); 
include_once ('functions.php');

if ($auth == 1) {
    if (isset($_POST["car_id_ext"]) AND isset($_POST["app_cod_ext"]) AND ( $_POST["car_tipo"] == "VN" OR $_POST["car_tipo"] == "VO" )) {
        $car_id_ext_exist = validaCarIdExt($bd_conn, $_POST["car_id_ext"], $_POST["app_cod_ext"]);
        if ($car_id_ext_exist == 1) {
            $ipo_update = 1;
            include ('includes/includeUpdateCar.php');            
        }else {
            if (isset($_POST["car_bastidor"])) {
                $car_bastidor_exist = validaCarBastidor($bd_conn, $_POST["car_bastidor"]);
                if ($car_bastidor_exist == 1) {
                    $ipo_update = 2;
                    include ('includes/includeUpdateCar.php');
                }else{
                    include ('includes/includeCreateCar.php');//
                }
            }else {
                include ('includes/includeCreateCar.php');
            }
        }
    }elseif (isset($_POST["car_bastidor"]) AND ( $_POST["car_tipo"] == "VN" OR $_POST["car_tipo"] == "VO" )) {
        $car_bastidor_exist = validaCarBastidor($bd_conn, $_POST["car_bastidor"]);
        if ($car_bastidor_exist == 1) {
            $ipo_update = 2;
            include ('includes/includeUpdateCar.php');
        }else{
            include ('includes/includeCreateCar.php');
        }
    }else {
        $data[] = array ( 
            "status" => "NOT OK",
            "message" => "error : Debe suministrar identificadores válidos"
        );
    }
    mysqli_close($bd_conn);
    header("Content-type: application/json; charset=utf-8");
    echo json_encode($data);   
}elseif ($auth == 0) {
    $data = array();
    $data[] = array ( 
        "code" => "unauthorized_client",
        "message" => "Invalid authorization token"
    );
    mysqli_close($bd_conn);
    header("Content-type: application/json; charset=utf-8");
    echo json_encode($data);
}
function validaCarIdExt($bd, $car_id_ext, $app_cod_ext)
{
    $sql =  "   SELECT COUNT(V.ID_EXT) AS TOTAL
                FROM VEHICULOS V
                WHERE V.ID_EXT = '$car_id_ext' AND V.CODE_EXT = '$app_cod_ext'";
    $base = $bd->query($sql);
    $row = mysqli_fetch_array($base);
    $result = $row['TOTAL'];
    return $result;
}
function validaCarBastidor($bd, $car_bastidor)
{
    $sql =  "   SELECT COUNT(V.BASTIDOR) AS TOTAL
                FROM VEHICULOS V
                WHERE V.BASTIDOR = '$car_bastidor'";
    $base = $bd->query($sql);
    $row = mysqli_fetch_array($base);
    $result = $row['TOTAL'];
    return $result;
}
?>