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

class Track 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->model('Tracking_model', "track");
		$this->load->model("Pins_model", "pins");
		$this->load->library('googlemaps');
	}
	public function index()
	{
        $config['center'] = '37.4419, -122.1419';
        $config['zoom'] = '12';
        $config['apiKey'] = 'AIzaSyA5os-lLvgVneN1434lMNcupgoI8vhA9Gw';
        $config['map_height'] = '100%';
        $this->googlemaps->initialize($config);

        $marker = array();
        $marker['position'] = '37.429, -122.1419';
        $this->googlemaps->add_marker($marker);
        $data['map'] = $this->googlemaps->create_map();
		$res['view'] = 'pages/track';
		$res['data'] = $data;
		$this->load->view('layout', $res);
	}

	public function show_track($user_id, $date) {
		$start = $date." 00:00:00";
		$end = $date." 23:59:59";
		$res = $this->track->get_data_between($user_id, $start, $end);
		$res_pins = $this->pins->get_pins_of_period($user_id, $start, $end);
		if($res["success"]){
			$data = $res["data"];
			$first = $data[0];
			$config['center'] = "{$first["lat"]}, {$first["lng"]}";
			$config['zoom'] = '12';
			$config['apiKey'] = 'AIzaSyA5os-lLvgVneN1434lMNcupgoI8vhA9Gw';
			$config['map_height'] = '100%';
			$this->googlemaps->initialize($config);
			$points = array();
			foreach($data as $row){
				$loc = "{$row["lat"]}, {$row["lng"]}";
				array_push($points, $loc);
			}

			$polyline = array();
			$polyline['points'] = $points;
			$this->googlemaps->add_polyline($polyline);

			foreach($res_pins['data'] as $item){
				$marker = array();
				$marker['position'] = "{$item["lat"]}, {$item["lng"]}";
				$marker['infowindow_content'] = "<b>Comment:</b> {$item["description"]} <br/><br/><b>Date Time:</b> {$item["created_date"]}";
				$marker['onmouseover'] = "iw_map.setContent(this.get('content'));iw_map.open(map, this);";
				$marker['onmouseout'] = "iw_map.close();";
				$this->googlemaps->add_marker($marker);
			}

			$data['map'] = $this->googlemaps->create_map();
			$res['view'] = 'pages/track';
			$res['data'] = $data;
			$this->load->view('layout', $res);
		}else{
		    $res['view'] = 'pages/no_data';
			$this->load->view('layout', $res);
		}
	}
}
