<?php
include("../db.php");
header('Content-Type: application/json');

$status = 0;
$data = new stdClass();
$msg = "Unable to process request";

// Open connection
$ch = curl_init();

if (isset($_GET['vehicle_number']) && !empty($_GET['vehicle_number'])){

    $live_location = get_live_location($ch, $_GET['vehicle_number']);

    if (is_array($live_location)){
        $data = $live_location;
        $status = 1;
        $msg = "Request successful";
    }else{
        $msg = 'Data not found or time limit exceeded...! Please try again later.';
    }

}

echo json_encode(array('status' => $status, 'data' => $data, 'message' => $msg));

// Close connection
curl_close($ch);

function get_live_location($curl_object, $vehicle_number)
{
    $location_data = new stdClass();

    $url = "http://marksgps.com/webservice?token=getLiveData&user=mountlitera&pass=012012&vehicle_no=$vehicle_number&format=json";

    // Set the url, number of POST vars, POST data
    curl_setopt($curl_object, CURLOPT_URL, $url);
    curl_setopt($curl_object, CURLOPT_RETURNTRANSFER, true);

    // Execute post
    $result = curl_exec($curl_object);

    if (!empty($result)) {
        $json_res = json_decode($result, true);
        if (array_key_exists("root", $json_res) && array_key_exists("VehicleData", $json_res["root"])) {
            $location_data = $json_res['root']['VehicleData'][0];
        }
    }
    return $location_data;
}