<?php
    //require_once ('settings.php');
    $login= trim($_POST['login']);
    $password = trim($_POST['password']);
   
    require_once("scripts/ClassLibs/ClassMessageAndLogs.php");
    $ObjLogs=new MessageAndLogs();
    //$ObjLogs->WriteLogAttendance(" dddd ".$_POST['inp_language'],'My','logs');
    //print_r($_POST); exit;
    if ($_POST['lang'])
    {
        //$lng=$_POST['inp_language'];
        if ($_POST['lang'] == 1) {
        	$lang = 'ru';
        } elseif ($_POST['lang'] == 2) {
        	$lang = 'en';
        } elseif ($_POST['lang'] == 3)  {
        	$lang = 'ua';
        } elseif ($_POST['lang'] == 4) {
        	$lang = 'pl';
        } elseif ($_POST['lang'] == 5) {
        	$lang = 'kz';
        } elseif ($_POST['lang'] == 0) {
        	$lang = 0;
        }
    }
    else
    {
        $lang=0;
    }
    
    $is_bloked = "";
    if ($login!='')
    if (($login || $login!='') && ($password || $password!='')) {
    //connecting to db
        if (!get_magic_quotes_gpc()){
            $login = addslashes($login);
            $password = addslashes ($password);
        }
        
        //$db = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME,$DB_PORT);
		$db = new mysqli ($DB_HOST,$DB_USER,$DB_PASS,$DB_NAME);
        $db->query("SET CHARSET SET utf8");
        $db->query("SET NAMES 'utf8'");
        if (mysqli_connect_errno()) {
            //echo "Error connecting to DB";
            exit;
        }
       //echo $login.' - '.$password;
        $query = "SELECT COUNT(*),u.role_id, u.client_id, u.id, u.frequency, u.locale, s.milestone,
IF((u.`MapCenter_longitude` IS NULL OR u.`MapCenter_longitude` = ''),s.`MapCenter_longitude`,u.MapCenter_longitude) AS lon,
IF((u.`MapCenter_latitude` IS NULL OR u.`MapCenter_latitude` = ''),s.`MapCenter_latitude`,u.MapCenter_latitude) AS lat,
		s.defaultMap_scale,s.gmt,s.use_fixed_data,c.is_blocked,b.balance,s.time_track,s.dist_track, s.car_name_format, c.`client_type`, s.`lost_signal`, u.`theme`, s.monit_from, s.groupmarker, s.smoothmarker, s.`dimension`,u.location FROM wm_users AS u LEFT JOIN wm_settings AS s ON u.client_id = s.client_id LEFT JOIN wm_clients c on u.client_id=c.id LEFT JOIN wm_balances b ON b.client_id=c.id WHERE (u.login=? AND u.password=?)";
        //$query = "SELECT COUNT(*),u.role_id, u.client_id, u.id, u.frequency, u.locale, s.milestone,s.MapCenter_longitude,s.MapCenter_latitude,".        "s.defaultMap_scale,s.gmt,s.use_fixed_data,c.is_blocked,b.balance,s.time_track,s.dist_track, s.car_name_format, c.`client_type`, s.`lost_signal`, u.`theme` FROM wm_users AS u LEFT JOIN wm_settings AS s ON u.client_id = s.client_id LEFT JOIN wm_clients c on u.client_id=c.id LEFT JOIN wm_balances b ON b.client_id=c.id WHERE (u.login=".$login." AND u.password=".md5($password).")";
		//echo  $query;
        $stmt = $db->prepare($query);
        $stmt->bind_param('ss',$login,md5($password));
        $stmt->execute();
        $stmt->bind_result($result,$role_id,$client_id, $id, $frequency, $locale, $milestone, $MapCenter_longitude, $MapCenter_latitude,$defaultMap_scale,$gmt,$fixed_data,$bloked,$balance,$time_track,$dist_track,$car_name_format,$client_type,$lost_signal,$theme, $monit_from, $murkercluster, $smoothmarker, $dimension,$location);
        $stmt->fetch(); // Get a result row as an enumerated array
        $stmt->close();
		$is_bloked = $bloked;		
		if ($role_id == 0 || $role_id == 5) {
			$isAdmin = true;
		} else {
			$isAdmin = false;
		}
		if ($result > 0 && $is_bloked != 1  && $isAdmin === false) {
            $ObjLogs->WriteLogAttendance("Вход в систему; client_id:".$client_id,'AttendanceLog','logs');
            $ObjLogs->WriteLogsToDB(1,"client_id:".$client_id,1,$login);
            $_SESSION['id'] = $id;
            $_SESSION['role_id'] = $role_id;
            $_SESSION['client_id'] = $client_id;
            $_SESSION['frequency'] = $frequency;
			
			if($client_id == 74){
				$URL = 'location.php';
				uf_redirect($URL);
				exit;
			}else{
			
            if (isset($_COOKIE['monit'])) {
            	setcookie('monit', $lang, time() + 31536000, '/');
				$_SESSION['locale'] = $lang;
            } else {
            	setcookie('monit', $locale, time() + 31536000, '/');
            	$_SESSION['locale'] = $locale;
            }
            
			
			setcookie('MapCenter_latitude', $MapCenter_latitude, time() + 31536000, '/');
			setcookie('MapCenter_longitude', $MapCenter_longitude, time() + 31536000, '/');
            
			$_SESSION['milestone'] = $milestone;
            $_SESSION['click_zone_monitoring'] = 0;
            $_SESSION['click_favor_zone_monitoring'] = 0;
            $_SESSION['lng']=$lng;
            $_SESSION['login']=$login;
            $_SESSION['password']=$password;
            $_SESSION['MapCenter_latitude'] = $MapCenter_latitude;
            $_SESSION['MapCenter_longitude'] = $MapCenter_longitude;
            $_SESSION['defaultMap_scale'] = $defaultMap_scale;
            $_SESSION['gmt'] = $gmt;
            $_SESSION['fixed_data'] = $fixed_data;
            $_SESSION['balance'] = $balance;
            $_SESSION['show_bal_mess'] = '0';
            $_SESSION['time_track'] = $time_track;
            $_SESSION['dist_track'] = $dist_track;
            $_SESSION['car_name_format'] =$car_name_format;
			
			$_SESSION['client_type'] = $client_type;
			$_SESSION['lost_signal'] = $lost_signal;	
			$_SESSION['theme'] = $theme;
			
			$_SESSION['startTime'] = date('Y-m-d', time()).' '.$monit_from.':00';
			$_SESSION['murkercluster'] = $murkercluster;
            $_SESSION['smoothmarker'] = $smoothmarker;
			
			$_SESSION['dimension'] = $dimension;
			$_SESSION['location'] = $location;
			
			//$query = "SELECT `nameApp`,`settings` FROM `clientApp` WHERE `id_client`=".$client_id.";";
			$query = "SELECT c.`nameApp`,c.`settings`,`name`, s.`geoX_start`, s.`geoY_start` FROM `clientapp` c 
					INNER JOIN `clientappfiles` f ON f.`id_clientapp`=c.`id`
					LEFT JOIN  `toir_settings` s ON s.`client_id`=c.`id_client` 
					WHERE c.`id_client`=".$client_id." AND f.`permission`=1;";
			if($stmt = $db->prepare($query)){
			$stmt->bind_param('i',$client_id);
			$stmt->execute();
			$stmt->bind_result($nameApp,$settings,$name, $geoX, $geoY);
			$resApp = array();
			while($stmt->fetch()){
				array_push($resApp,$name);
			}
			if(!empty($resApp)){
				$_SESSION['nameApp'] = $nameApp;
				$_SESSION['settingsApp'] = $settings;
				$_SESSION['namefilesApp'] = $resApp;
				$_SESSION['goeX'] = $geoX;
				$_SESSION['goeY'] = $geoY;				
			}else{
				$_SESSION['nameApp'] = "";
				$_SESSION['settingsApp'] = "";
				$_SESSION['namefilesApp'] = array();
				$_SESSION['goeX'] = "";
				$_SESSION['goeY'] = "";
			}
			$stmt->close();
			}
			
			//поддержка по пратнерам с телофрнами партеров с БД
			$query = "SELECT phone_numb FROM `wm_partners` WHERE `id` = (SELECT `partners_id` FROM `wm_clients` WHERE `id` = ".$client_id.");";
			if($stmt = $db->prepare($query)){
			if($stmt->execute()){
				$stmt->bind_result($phone_numb);
				$helparray = array();
				while($stmt->fetch()){
					$phone_numb = str_replace(array(" ",",",", "), '<br />', $phone_numb);
					$_SESSION['NineOneOne'] = '<center><b>'.$phone_numb.'</b></center>';
				}
				$stmt->close();
				
				
			}}
			
			
	//--------------------- select all user right ------------------------------
	/*$query = "SELECT  r.`right_name` , ur.`state`  FROM `wm_rights` r
			INNER JOIN `wm_user_rights` ur ON ur.right_id = r.id
			WHERE ur.user_id=$id
			UNION 
  			SELECT `right_name`,0 FROM `wm_rights` WHERE id NOT IN(SELECT `right_id` FROM `wm_user_rights` WHERE `user_id`=$id)";
	*/
	$query = "SELECT r.`right_name`,IF(ur.`state` IS NULL, 0, ur.`state` ) AS `state` FROM `wm_rights` r
 		LEFT JOIN `wm_user_rights` ur ON ur.right_id = r.id AND ur.user_id = $id
 		GROUP BY r.id ORDER BY r.id ;";
	//echo $query;
	$data = array();
	if($stmt = $db->prepare($query)){
	if($stmt->execute()){
		$stmt->bind_result($right_name, $state);
		while ($stmt->fetch()) {
		$data[] = array(
			'right_name' => $right_name,
			'state' => $state	
		);
		}
		$_SESSION['right'] = json_encode($data);
		$stmt->close();
	}}
	
	//--------------------- select common settings ------------------------------
	$query = "SELECT s.milestone, s.car_name_format,
IF((u.`MapCenter_longitude` IS NULL OR u.`MapCenter_longitude` = ''),s.`MapCenter_longitude`,u.MapCenter_longitude) AS lon,
IF((u.`MapCenter_latitude` IS NULL OR u.`MapCenter_latitude` = ''),s.`MapCenter_latitude`,u.MapCenter_latitude) AS lat,
s.defaultMap_scale,s.showEventSettings,s.gmt,s.use_fixed_data,s.track_detile,s.fixed_scale,s.monit_from,s.groupmarker,s.auto_correct_gmt,s.planfact
,s.shownumbertrippoint
FROM wm_settings s
LEFT JOIN wm_users u ON u.`client_id` = s.`client_id`
WHERE s.client_id = ? AND u.`id` = ?;";

	$data = array();
	if($stmt = $db->prepare($query)){
	$stmt->bind_param('ii', $client_id,$id);
	if($stmt->execute()){
		$stmt->bind_result($milestone, $car_name_format, $lon, $lat, $defaultMap_scale, $showEventSettings, $gmt, $use_fixed_data, $track_detile, $fixed_scale, $monit_from, $groupmarker, $auto_correct_gmt, $planfact, $shownumbertrippoint);
		while ($stmt->fetch()) {
		$data[] = array(
			'milestone' => $milestone,
			'car_name_format' => $car_name_format,
			'lon' => $lon,
			'lat' => $lat,
			'defaultMap_scale' => $defaultMap_scale,
			'showEventSettings' => $showEventSettings,
			'gmt' => $gmt,
			'use_fixed_data' => $use_fixed_data,
			'track_detile' => $track_detile,
			'fixed_scale' => $fixed_scale,
			'monit_from' => $monit_from,
			'groupmarker' => $groupmarker,
			'auto_correct_gmt' => $auto_correct_gmt,
			'planfact' => $planfact,
			'shownumbertrippoint' => $shownumbertrippoint
		);
		}
		$_SESSION['commonsettings'] = json_encode($data);
		$stmt->close();
	}}
			
			
			
			
			//поддержка по пратнерам старая
			/*$query = "SELECT `id` FROM `wm_clients` WHERE `partners_id`=11;";
			if($stmt = $db->prepare($query)){
				$stmt->execute();
				$stmt->bind_result($id);
				$helparray = array();
				while($stmt->fetch()){
					array_push($helparray,$id);
				}
				$stmt->close();
				if(!empty($helparray)){
					if (in_array($client_id, $helparray)){
						$_SESSION['NineOneOne'] = '<center><b><p><a style="" href="+380937627962" >+380937627962</a></p><p><a style="" href="+380500353375" >+380500353375</a></p><p><a style="" href="+380443590276" >+380443590276</a></p></b></center>';
					}else{
						$_SESSION['NineOneOne'] = '<center><b><p><a style="" href="tel:+380930133221" >+380930133221</a></p><p><a style="" href="+380992375207" >+380992375207</a></p></b></center>';
					}
				}else{
					$_SESSION['NineOneOne'] = '<center><b><p><a style="" href="tel:+380930133221" >+380930133221</a></p><p><a style="" href="+380992375207" >+380992375207</a></p></b></center>';
				}
			}*/
			
			
			//logging
       
           /* $a = new Action_log();
            $a->dir_name = $dirname;
            $query = "INSERT INTO tms_log (login,action,time) VALUES ('".$_SESSION['id']."','login',NOW())";
            $a->Save($query);*/
            
			
            $URL = 'index.php';
            uf_redirect($URL);
            
			$db->close();
			
			
			}
			
			exit;
        }
        //$stmt->close();
    }
    
?>
