<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Dashboard extends MY_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
    function __construct() {
        parent::__construct();
		$this->load->library('googlemaps');
		$this->load->model('tracking_model', 'tracking');
		$this->load->model('Sync_model', 'sync');
    }
    public function index()
	{
		$res = $this->tracking->get_user_last_location();
		if($res['success']){
			$first = $res['data'][0];
			$config['center'] = "{$first['lat']}, {$first['lng']}";
		}else{
			$config['center'] = '24.566368, 80.809889';
		}
        
        $config['zoom'] = '14';
        $config['apiKey'] = 'AIzaSyA5os-lLvgVneN1434lMNcupgoI8vhA9Gw';
        $config['map_height'] = '500px';
        $this->googlemaps->initialize($config);

		foreach($res['data'] as $item){
            $marker = array();
            $marker['position'] = "{$item["lat"]}, {$item["lng"]}";
			$marker['onmouseover'] = "iw_map.setContent(this.get('content'));iw_map.open(map, this);";
			$marker['onmouseout'] = "iw_map.close();";

			$last_time = $this->sync->get_user_last_synch($item["user_id"]);
			$marker['infowindow_content'] = "<b>Name:</b>{$item['user_name']}<br/><br/><b>Last Sync</b>: {$last_time} ";
			if($last_time != "") {
				$now  = time();
				$date = strtotime($last_time);
				$duration = ($now - $date)/(60 * 60);
				if($duration > 1) {
					$marker['icon'] = "http://maps.google.com/mapfiles/ms/icons/red-dot.png";
				}else{
					$marker['icon'] = "http://labs.google.com/ridefinder/images/mm_20_purple.png";
				}
			}else{
				$marker['icon'] = "http://maps.google.com/mapfiles/ms/icons/red-dot.png";
			}
			$marker['icon_scaledSize'] = '48 , 42';
            $this->googlemaps->add_marker($marker);
        }
		
		$data['map'] = $this->googlemaps->create_map();
        $res["view"] = 'pages/track';
        $res["data"] = $data;
		$this->load->view('layout', $res);
    }
}
