<?php
/*+*******************************************************************************
 * The content of this file is subject to the CRMTiger Pro license.
 * ("License"); You may not use this file except in compliance with the License
 * The Initial Developer of the Original Code is vTiger
 * The Modified Code of the Original Code owned by https://crmtiger.com/
 * Portions created by CRMTiger.com are Copyright(C) CRMTiger.com
 * All Rights Reserved.
  ***************************************************************************** */
class CTMobileSettings_getLoginHistory_Action extends Vtiger_Save_Action {

	public function process(Vtiger_Request $request) {
		global $adb;
		$mode = $request->get('mode');
		if($mode == 'ExportData'){
			$usersFilter = $request->get('usersFilter');
			$daterange = $request->get('daterange');
			if($daterange != ''){
				$date = explode(' - ',$daterange);
				$startdate = date("Y-m-d", strtotime($date[0]));
				$enddate = date("Y-m-d", strtotime($date[1]));
			}
			$SQL = "SELECT login_id,user_name,user_ip,logout_time,login_time,status FROM ctmobile_loginhistory WHERE 1=1";
			if($usersFilter){
				$SQL.=" AND user_name = '$usersFilter'";
				//$totalSQL = $SQL;
			}
			if($startdate != '' && $enddate != ''){
	 			$SQL.=" AND DATE(login_time) BETWEEN '$startdate' AND '$enddate' ";
	 		}
	 		
			$type = 'csv';
			$fileName = 'LoginHistory-'.date('Y-m-d-H-i-s').'.csv';
			$entries = array();
			$headers = array('User Name','User IP Address','Sign-in Time','Sign-out Time','Status');
			$result = $adb->pquery($SQL,array());
			for ($i=0; $i < $adb->num_rows($result); $i++) { 
				$row = $adb->query_result_rowdata($result,$i);
				$UserRecordModel = Users_Record_Model::getInstanceByName($row['user_name']);
				$row['user_name'] = decode_html(decode_html($UserRecordModel->get('first_name').' '.$UserRecordModel->get('last_name')));
				$row['login_time'] = Vtiger_Datetime_UIType::getDisplayValue($row['login_time']);
				$row['logout_time'] = Vtiger_Datetime_UIType::getDisplayValue($row['logout_time']);
				$entries[] = array($row['user_name'],$row['user_ip'],$row['login_time'],$row['logout_time'],$row['status']);
			}
			$this->output($headers,$entries,$type,$fileName);
		}else if($mode == 'getCount'){
			$daterange = $request->get('daterange');
			$searchKey = $request->get('search_key');
			$searchValue = $request->get('search_value');
			if($daterange != ''){
				$date = explode(' - ',$daterange);
				$startdate = date("Y-m-d", strtotime($date[0]));
				$enddate = date("Y-m-d", strtotime($date[1]));
			}

			$SQL = "SELECT login_id,user_name,user_ip,logout_time,login_time,status FROM ctmobile_loginhistory WHERE 1=1 ";
			if($searchKey && $searchValue){
				$SQL.=" AND $searchKey = '$searchValue'";
				$totalSQL = $SQL; 
			}else{
				$totalSQL = $SQL;
			}

			if($startdate != '' && $enddate != ''){
	 			$SQL.=" AND DATE(login_time) BETWEEN '$startdate' AND '$enddate' ";
	 			$totalSQL = $SQL;
	 		}

			$totalResult = $adb->pquery($totalSQL,array());
			$totalCount = $adb->num_rows($totalResult);

			$result = array('recordsTotal'=>$totalCount);
			$response = new Vtiger_Response();
			$response->setEmitType(Vtiger_Response::$EMIT_JSON);
			$response->setResult($result);
			$response->emit();
			exit;
		}else{
			$listViewEntries = array();
			$draw = $_POST['draw'];
			$start = $_POST['start'];
			$length = $_POST['length'];

			$searchKey = $request->get('search_key');
			$searchValue = $request->get('search_value');
			$daterange = $request->get('daterange');
			if($daterange != ''){
				$date = explode(' - ',$daterange);
				$startdate = date("Y-m-d", strtotime($date[0]));
				$enddate = date("Y-m-d", strtotime($date[1]));
			}

			$SQL = "SELECT login_id,user_name,user_ip,logout_time,login_time,status FROM ctmobile_loginhistory WHERE 1=1";
			if($searchKey && $searchValue){
				$SQL.=" AND $searchKey = '$searchValue'";
				$totalSQL = $SQL; 
			}else{
				$totalSQL = $SQL;
			}

			if($startdate != '' && $enddate != ''){
	 			$SQL.=" AND DATE(login_time) BETWEEN '$startdate' AND '$enddate' ";
	 			$totalSQL = $SQL;
	 		}

			if($start != '' && $length != ''){
				$SQL.= " LIMIT $start, $length";
			}

			$result = $adb->pquery($SQL,array());
			for ($i=0; $i < $adb->num_rows($result); $i++) { 
				$row = $adb->query_result_rowdata($result,$i);
				$UserRecordModel = Users_Record_Model::getInstanceByName($row['user_name']);
				$row['user_name'] = decode_html(decode_html($UserRecordModel->get('first_name').' '.$UserRecordModel->get('last_name')));
				$row['login_time'] = Vtiger_Datetime_UIType::getDisplayValue($row['login_time']);
				$row['logout_time'] = Vtiger_Datetime_UIType::getDisplayValue($row['logout_time']);
				$listViewEntries[] = array('user_name'=>$row['user_name'],'user_ip'=>$row['user_ip'],'login_time'=>$row['login_time'],'logout_time'=>$row['logout_time'],'status'=>$row['status']);
			}

			$totalResult = $adb->pquery($totalSQL,array());
			$totalCount = $adb->num_rows($totalResult);

			$result = array('draw'=>(int)$draw,'recordsTotal'=>$totalCount,'recordsFiltered'=>$totalCount,'data'=>$listViewEntries);
			echo json_encode($result);
			exit;
		}
	}

	function output($headers, $entries,$type,$fileName) {
		// for content disposition header comma should not be there in filename 
		if($type == 'csv'){
			$exportType = 'text/csv';
		}else{
			$exportType = 'application/x-msexcel';
		}
		header("Content-Disposition:attachment;filename=$fileName");
		header("Content-Type:$exportType;charset=UTF-8");
		header("Expires: Mon, 31 Dec 2000 00:00:00 GMT" );
		header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT" );
		header("Cache-Control: post-check=0, pre-check=0", false );

		if($type == 'csv'){
			$header =  implode("\t", $headers) . "\n";
			echo $header;
			foreach($entries as $row) {
				foreach ($row as $key => $value) {
					/* To support double quotations in CSV format
					 * To review: http://creativyst.com/Doc/Articles/CSV/CSV01.htm#EmbedBRs
					 */
					$row[$key] = str_replace('"', '""', $value);
				}
				echo implode("\t", array_values($row)) . "\n";
			}
		}else{
			$header =  implode("\t", $headers) . "\n";
			echo $header;
			foreach($entries as $row) {
				echo implode("\t", array_values($row)) . "\n";
			}

		}
	}

}