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

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

// Open connection
$ch = curl_init();

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

$running = 0;
$stopped = 0;
$idle = 0;
$inactive = 0;
$no_data = 0;

$total = 0;

$running_vehicle_list  = array();
$stopped_vehicle_list  = array();
$idle_vehicle_list     = array();
$inactive_vehicle_list = array();
$no_data_vehicle_list  = array();

if (count($result) > 0) {

    foreach ($result as $row){

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

        if (is_array($live_location) && count($live_location) > 0){

            $status = 1;
            $msg = "Request successful";

            if ($live_location['Status'] == 'RUNNING'){
                $running = $running + 1;
                $running_vehicle_list[] = $live_location;
            }elseif ($live_location['Status'] == 'STOP'){
                $stopped = $stopped+1;
                $stopped_vehicle_list[] = $live_location;
            }else{
                $idle = $idle+1;
                $idle_vehicle_list[] = $live_location;
            }
        }else{
            $msg = 'Data not found or time limit exceeded...! Please try again later.';
        }

    }

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

$total = $running + $stopped + $idle + $inactive + $no_data;

echo json_encode(array('status' => $status, 'data' => array(
    array('count' => $running, 'text' => 'Running : '.$running, 'vehicle_list' => $running_vehicle_list),
    array('count' => $stopped, 'text' => 'Stop : '.$stopped, 'vehicle_list' => $stopped_vehicle_list),
    array('count' => $idle, 'text' => 'Idle : '.$idle, 'vehicle_list' => $idle_vehicle_list),
    array('count' => $inactive, 'text' => 'Inactive : '.$inactive, 'vehicle_list' => $inactive_vehicle_list),
    array('count' => $no_data, 'text' => 'No Data : '.$no_data, 'vehicle_list' => $no_data_vehicle_list),
), 'total' => $total, '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;
}