<?php

session_start();
ini_set("auto_detect_line_endings", "1");
include_once '/home/ronnie/ranger/v2/include/db.php';

function handlePost() {
	$response=array("status"=>false, "message"=>false);
	if (isset($_POST['login'])) {
		$response = login($_POST);
	} else if (isset($_POST['pin'])) {
		$pin=trim($_POST['pin']);
		if ($_POST['action'] == "set") {
			$_SESSION[$pin.'_pin_active']	=true;
			$response['status']				=true;
		} elseif ($_POST['action'] == "remove") {
			if (isset($_SESSION[$pin.'_pin_active'])) {
				unset($_SESSION[$pin.'_pin_active']);
			}
			$response['status']=true;
		}
	} else if (isset($_POST['stats'])) {
		$stats=trim($_POST['stats']);
		if ($_POST['action'] == "set") {
			$_SESSION[$stats.'_stats_active']	=true;
			$response['status']					=true;
		} elseif ($_POST['action'] == "remove") {
			if (isset($_SESSION[$stats.'_stats_active'])) {
				unset($_SESSION[$stats.'_stats_active']);
			}
			$response['status']=true;
		}
	} else if (isset($_POST['upload-contacts'])) {
		$fileName	='contacts-'.date("Y-m-d-H-i-s", time()).'.csv';
		$path		=$_SERVER['DOCUMENT_ROOT']."/v2/uploads/";
		if (move_uploaded_file($_FILES['csv']['tmp_name'], $path.$fileName)) {
			$csv=csv_to_array($path.$fileName);
			if (count($csv) > 0 && false !== $csv) {

				$response['html']		="";
				$response['filename']	=$fileName;
				$error					=array();
				$success				=array();
				foreach ($csv as $row) {
					if (isset($row['first name']) && isset($row['surname']) && isset($row['vehicle registration'])) {
						$fiestname				=trim($row['first name']);
						$surname				=trim($row['surname']);
						$vehicle_registration	=trim($row['vehicle registration']);

						if (!isValid($fiestname) || !isValid($surname) || !isValid($vehicle_registration)) {
							$error[]=$row;
						} else{
							$success[] = $row;
						}
					}
				}

				if(count($error)> 0){
					$sortarray = array();
				    foreach ($error as $key => $row) {
				        $sortarray[$key] = $row[$subfield];
				    }
				    array_multisort($sortarray, SORT_ASC, $error);

				    foreach ($error as $row) {
						if (isset($row['first name']) && isset($row['surname']) && isset($row['vehicle registration'])) {
							$fiestname				=trim($row['first name']);
							$surname				=trim($row['surname']);
							$vehicle_registration	=trim($row['vehicle registration']);

							$uid=rand(1, 1000);
							$response['html'] .= '<a data-uid="'.$uid.'" data-name="'.$fiestname.'" data-surname="'.$surname.'" data-vehiclenumber="'.$vehicle_registration.'"  href="#" class="c-namesError">'.$fiestname.' '.$surname.' <span href="#" class="c-contact-delete icon-cross c-circle"></span></a>';
							$response['assing_html'] .= '<div class="c-AssignContact-Box-Contacts-Item ui-draggable ui-draggable-handle"><a data-uid="'.$uid.'" data-name="'.$fiestname.'" data-surname="'.$surname.'" data-vehiclenumber="'.$vehicle_registration.'" data-group="" href="#" data-group="" data-uid="1">'.$fiestname.' '.$surname.' </a><span class="c-AssignContact-Clear icon-cross" href="#"></span></div>';
						}
					}

				}

				if(count($success)> 0){
				    foreach ($success as $row) {
				    	
						if (isset($row['first name']) && isset($row['surname']) && isset($row['vehicle registration'])) {
							$fiestname				=trim($row['first name']);
							$surname				=trim($row['surname']);
							$vehicle_registration	=trim($row['vehicle registration']);

							$uid=rand(1, 1000);
							$response['html'] .= '<a data-uid="'.$uid.'" data-name="'.$fiestname.'" data-surname="'.$surname.'" data-vehiclenumber="'.$vehicle_registration.'"  href="#" class="">'.$fiestname.' '.$surname.' <span href="#" class="c-contact-delete icon-cross c-circle"></span></a>';
							$response['assing_html'] .= '<div class="c-AssignContact-Box-Contacts-Item ui-draggable ui-draggable-handle"><a data-uid="'.$uid.'" data-name="'.$fiestname.'" data-surname="'.$surname.'" data-vehiclenumber="'.$vehicle_registration.'" data-group="" href="#" data-group="" data-uid="1">'.$fiestname.' '.$surname.' </a><span class="c-AssignContact-Clear icon-cross" href="#"></span></div>';
						}
					}

				}

				if ("" !== $response['html']) {
					$response['status']="success";
				} else {
					$response['message']="Invalid csv format found. Please try header format like first name, surname and vehicle registration";
				}
			} else {
				$response['message']="Invalid csv format found. Please try header format like first name, surname and vehicle registration";
			}
		} else {
			$response['message']="Error while uploading file! Please tr again.";
		}
	} else if (isset($_POST['group-pin'])) {
		$action				=isset($_POST['action']) ? $_POST['action'] : false;
		$pin				=isset($_POST['password']) ? $_POST['password'] : false;
		$editPin			="1111";
		$masterPin			="0000";
		$response['review']	=false;
		$response['master']	=false;
		switch ($action) {
			case "master":
				if ($masterPin === $pin) {
					$_SESSION['review-group-pin']	=true;
					$response['review']				=true;
					$_SESSION['master-group-pin']	=true;
					$response['master']				=true;
					$response['status']				=true;
				}
				break;
			case "review":
				if (in_array($pin, array($masterPin, $editPin))) {
					$_SESSION['review-group-pin']	=true;
					$response['review']				=true;
					if ($masterPin == $pin) {
						$_SESSION['master-group-pin']	=true;
						$response['master']				=true;
					}
					$response['status']=true;
				}
				break;
			case "logout":
				if (isset($_SESSION['review-group-pin'])) {
					unset($_SESSION['review-group-pin']);
				}
				if (isset($_SESSION['master-group-pin'])) {
					unset($_SESSION['master-group-pin']);
				}
				$response['status']=true;
				break;
		}
	} else if (isset($_POST['get-report'])) {
		$id=false;
		if (isset($_POST['report-id'])) {
			$id=(int) $_POST['report-id'];
		}
		include_once 'include/reports/details.php';

		exit;
	} else if (isset($_POST['vrm_action'])) {
		$response = vrmActions($_POST['vrm_action']);
	}
	die(json_encode($response));
}

function login($data=array()) {
	$response=array("status"=>false);
	if (is_array($data)) {
		$username = isset($data['username'])?:false;
		$password = isset($data['password'])?:false;

		if($username == "moto" && $password == "1234"){
			#$_SESSION['review-group-pin'] =true;
			#$_SESSION['master-group-pin'] =true;
			$_SESSION['user_loggedin']	  =true;
			$response['status']			  =true;
			$response['message']		  ="Yay! Access granted!";
		} else {
			$response['message']="Oops! We can't recognize you!";	
		}
	} else {
		$response['message']="Oops! Please supply valid data!";
	}
	return $response;
}

function csv_to_array($filename='', $delimiter=',') {
	if (!file_exists($filename) || !is_readable($filename))
		return FALSE;

	$header	=false;
	$data	=array();
	if (($handle	=fopen($filename, 'r')) !== FALSE) {
		while (($row=fgetcsv($handle, 1000, $delimiter)) !== FALSE) {
			if (!$header) {
				$header=$row;
			} else {
				$data[]=@array_combine($header, $row);
			}
		}
		fclose($handle);
	}
	return $data;
}

function isValid($text=''){
	$response = true;
	if('' == trim($text)){
		$response = false;
	} else {
		preg_match_all('/[\/~`\!@#\$%\^&\*\(\)_\-\+=\{\}\[\]\|;:"\<\>,\.\?\/]/', $text, $res);
		#echo "<pre> $text => ";var_dump(isset($res[0][0]));
		#print_r($res);
		if(isset($res[0][0])){
			$response = false;
		}
	}
	return $response;
}

function vrmActions($action=false){
	$response = array("status" => false);

	switch ($action) {
		case 'getfeed':
			$search = isset($_POST['search'])?trim($_POST['search']):false;
			$last   = isset($_POST['last'])?(int)($_POST['last']):false;
			if($search){
				$arrVehicles = vehicle_movement::getBySearch($search, $last);
			} else if($last > 0) {
				$arrVehicles = vehicle_movement::getAfterIDs($last);
			} else {
				$arrVehicles = vehicle_movement::getLatest();
			}

			if(count($arrVehicles) > 0){
				$response['status'] = true;
				$response['html']   = vehicle_movement::makeList($arrVehicles, $last);
			}
			break;

		case 'getlatest':
			$response['item'] = array();
			$response['latest'] = 0;

			$id   = isset($_POST['id'])?(int)($_POST['id']):0;
			$arrVehicles = vehicle_movement::getBeforeIDs($id, 50);
			if(count($arrVehicles) > 0){
				$response['status'] = true;
				foreach($arrVehicles as $vehicle){
					if($response['latest'] == 0){
						$response['latest'] = $vehicle['VehicleMovementID'];
					}
					$response['item'][$vehicle['VehicleMovementID']] = vehicle_movement::getItem($vehicle);
				}
			}
			break;
		default:
			
			break;
	}

	return $response;
}

if ($_POST) {
	handlePost();
}
?>