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

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

// Open connection
$ch = curl_init();

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

    $vehicle_status = $_GET['status'];

    $result = $db->getRows("SELECT * FROM gps_vehicle");

    if (count($result) > 0) {

        foreach ($result as $row){
            //$row['location_info'] = getData($ch, $row['vehicle_number']);
            //$data[] = $row;

            $live_location = get_live_location($ch, $row['vehicle_number']);
            if (is_array($live_location)){

                $is_status_matched = false;

                switch ($vehicle_status) {
                    case 0 : $is_status_matched = ($live_location['Status'] == 'RUNNING');
                    break;

                    case 1 : $is_status_matched = ($live_location['Status'] == 'STOP');
                    break;

                    case 2 : $is_status_matched = ($live_location['Status'] != 'RUNNING') && ($live_location['Status'] != 'STOP');
                    break;
                }

                if ($is_status_matched){
                    $data[] = $live_location;
                    $status = 1;
                    $msg = "Request successful";
                }

            }else{
                $msg = 'Data not found or time limit exceeded...! Please try again later.';
            }
        }

    }else{
        $msg = "Data not found...!";
    }

}

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;
}