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

class Summary extends MY_Controller {

	public $data = array();

	public function __construct() {

		parent::__construct();

		if(!$this->session->userdata('IsLogin')) {
			redirect($this->globalUrl.'main');	
		}

		$this->load->model('summary_model');
		$this->load->library('pagination');
		
	}

	public function index($linkId = null)
	{	

		// Date Settings 
		$todayDate 			= date('d-m-Y');
		$yesterdayDate 		= date('d-m-Y',strtotime("-1 days"));
		$currentWeekRange 	= $this->_current_week_range();
		$lastWeekRange 		= $this->_last_week_range();
		$currentMonthRange 	= $this->_current_month_range();
		$lastMonthRange 	= $this->_last_month_range();


		$this->data['todayLink'] = '?fromDate='.$todayDate.'&toDate='.$todayDate.'&search=search';
		$this->data['yesterdayLink'] = '?fromDate='.$yesterdayDate.'&toDate='.$yesterdayDate.'&search=search';
		$this->data['currentWeekLink'] = '?fromDate='.$currentWeekRange[0].'&toDate='.$currentWeekRange[1].'&search=search';
		$this->data['lastWeekLink'] = '?fromDate='.$lastWeekRange[0].'&toDate='.$lastWeekRange[1].'&search=search';
		$this->data['currentMonthLink'] = '?fromDate='.$currentMonthRange[0].'&toDate='.$currentMonthRange[1].'&search=search';
		$this->data['lastMonthLink'] = '?fromDate='.$lastMonthRange[0].'&toDate='.$lastMonthRange[1].'&search=search';

		if(isset($_GET['fromDate']) && isset($_GET['toDate'])) {

			if($_GET['fromDate'] === $todayDate && $_GET['toDate'] === $todayDate) {
				$this->data['shouldRed'] = 1;
			} else if ($_GET['fromDate'] === $yesterdayDate && $_GET['toDate'] === $yesterdayDate) {
				$this->data['shouldRed'] = 2;
			} else if ($_GET['fromDate'] === $currentWeekRange[0] && $_GET['toDate'] === $currentWeekRange[1]) {
				$this->data['shouldRed'] = 3;
			} else if ($_GET['fromDate'] === $lastWeekRange[0] && $_GET['toDate'] === $lastWeekRange[1]) {
				$this->data['shouldRed'] = 4;
			} else if ($_GET['fromDate'] === $currentMonthRange[0] && $_GET['toDate'] === $currentMonthRange[1]) {
				$this->data['shouldRed'] = 5;
			} else if ($_GET['fromDate'] === $lastMonthRange[0] && $_GET['toDate'] === $lastMonthRange[1]) {
				$this->data['shouldRed'] = 6;
			} else {
				$this->data['shouldRed'] = 0;
			}
		} else {
			$this->data['shouldRed'] = 0;
		}

		$fromDate = isset($_GET['fromDate']) ? date('Y-m-d 00:00:00', strtotime($this->input->get('fromDate'))) : '2018-01-01 00:00:00';
		$toDate = isset($_GET['toDate']) ? date('Y-m-d 23:59:59', strtotime($this->input->get('toDate'))) : date('Y-m-d 23:59:59');

		if($this->input->post('search')) {
			
			$fromDate = date('Y-m-d 00:00:00', strtotime($this->input->get('fromDate')));
			$toDate = date('Y-m-d 23:59:59', strtotime($this->input->get('toDate')));

		}

		// If no like ID is provided, go back to dashboard
		if($linkId === null) {
			redirect($this->globalUrl."dashboard");
		}

		// Query for locations
		$locationResult = $this->summary_model->get_location_summary($linkId, $fromDate, $toDate);

		// Query for OS
		$osResult = $this->summary_model->get_os_summary($linkId, $fromDate, $toDate);

		// Query for referrers
		$refResult = $this->summary_model->get_referrers_summary($linkId, $fromDate, $toDate);

		if($locationResult && $osResult && $refResult) {

			// Convert to JSON (location)
			$locationArray = array();
			foreach ($locationResult as $value) {

				$tempArray = array(
					"y" => $value->City,
					"a" => $value->CityCount
				);

				array_push($locationArray, $tempArray);
			}

			// Convert to JSON (OS)
			$osArray = array();
			foreach ($osResult as $value) {
				
				$tempArray = array(
					'label' => $value->OperatingSystem != null ? strtoupper($value->OperatingSystem) : 'UNKNOWN',
					'value' => $value->OSCount
				);

				array_push($osArray, $tempArray);
			}

			// Convert to JSON (Ref)
			$refArray = array();
			foreach ($refResult as $value) {
				
				$tempArray = array(
					'label' => $value->ReferrersList != null ? $value->ReferrersList : 'OTHERS',
					'value' => $value->Count
				);

				array_push($refArray, $tempArray);
			}

			if($this->uri->segment(3)){
				$page = $this->uri->segment(3);
			} else { 
				$page = 1;
			}

			$paginationConfig = array();
			$paginationConfig["base_url"] = "http://kiosk.soccerking128.com/summary/".$linkId;
			$total_row = $this->summary_model->record_count($linkId, $fromDate, $toDate);
			$paginationConfig["total_rows"] = $total_row;
			$paginationConfig['per_page'] = 100;
			$paginationConfig['use_page_numbers'] = TRUE;
			$paginationConfig['num_links'] = $total_row;
			$paginationConfig['cur_tag_open'] = '&nbsp;<a class="current">';
			$paginationConfig['cur_tag_close'] = '</a>';
			$paginationConfig['next_link'] = 'Next';
			$paginationConfig['prev_link'] = 'Previous';
			$paginationConfig['first_url'] = "http://kiosk.soccerking128.com/summary/".$linkId."?fromDate=05-02-2018&toDate=05-02-2018&search=search";
			$paginationConfig['uri_segment'] = 3;
			$paginationConfig['num_links'] = 8;
			$paginationConfig['reuse_query_string'] = true;

			$this->pagination->initialize($paginationConfig);

			
			$this->data['summaryResult'] = $this->summary_model->get_link_details($linkId ,$paginationConfig['per_page'], $page, $fromDate, $toDate);
			$str_links = $this->pagination->create_links();
			$this->data['links'] = explode('&nbsp;',$str_links);
			$this->data['locationResult'] = json_encode($locationArray);
			$this->data['osResult'] = json_encode($osArray);
			$this->data['refResult'] = json_encode($refArray);
			
		} else {
			
			// Convert to JSON (location)
			$locationArray = array();

			// Convert to JSON (OS)
			$osArray = array();
		
			// Convert to JSON (Ref)
			$refArray = array();

			$this->data['locationResult'] = json_encode($locationArray);
			$this->data['osResult'] = json_encode($osArray);
			$this->data['refResult'] = json_encode($refArray);
			$this->data['linkId'] = $linkId;
		}

		$this->data['fromDate'] = date('d-m-Y', strtotime($fromDate));
		$this->data['toDate'] = date('d-m-Y', strtotime($toDate));
		$this->load->template('summary', $this->data);
		
	}

	function _current_week_range() {
	    $startDate = date("d-m-Y",strtotime( date('o-\\WW')));
		$endDate = strtotime( date('o-\\WW').' +6 days' );
		$lastDate = strtotime("today");

		if($lastDate <= $endDate) {
			$endDate = date("d-m-Y", $lastDate);
		} else {
			$endDate = date("d-m-Y", $endDate);
		}

		return array($startDate, $endDate);	
	}

	function _last_week_range() {
		$startDate = date("d-m-Y", strtotime("last week monday"));
		$endDate = date("d-m-Y", strtotime("last week sunday"));
		return array($startDate, $endDate);
	}

	function _current_month_range() {
		$startDate 	= date("d-m-Y", strtotime("first day of this month"));
		$endDate	= strtotime("last day of this month");
		$lastDate	= strtotime("today");

		if($lastDate <= $endDate) {
			$endDate = date("d-m-Y", $lastDate);
		} else {
			$endDate = date("d-m-Y", $endDate);
		}

		return array($startDate, $endDate);
	}

	function _last_month_range() {
		$startDate	= date("d-m-Y", strtotime("first day of last month"));
		$endDate	= date("d-m-Y", strtotime("last day of last month"));

		return array($startDate, $endDate);	
	}
}
