<?php
require_once ("varables.php");

$myJSON['success'] = "0";
$myJSON['token']="0";
$myJSON['id']="0";
$myJSON['name']="0";
$myJSON['isAdmin']="0";
$hash = "";
$user_id=0;
if(isset($_POST["uzermane"]) && isset($_POST["wasport"]) && isset($_POST["an1d"])&& isset($_POST["nekot"]))
{
	$tokhen = $_POST["nekot"];
    $uzername = $_POST["uzermane"];
    $passwor = $_POST["wasport"];

    $connect = @mysqli_connect($hostname,$username,$password,$database);
    if($connect)
    {
        @mysqli_query($connect,"SET CHARACTER SET utf8;");
		$query_token = "SELECT id FROM ".$tbl_sessions." WHERE token = '".$tokhen."' AND type ='A' LIMIT 1";
		$tokres=@mysqli_query($connect,$query_token);
        if (!$tokres) {
            $myJSON['success']= "400" ;
        }
		else{
			$countoft = 0;
            while($rowt = @mysqli_fetch_assoc($tokres))
                $countoft++;
			if($countoft == 0)
				  $myJSON['success']= "405" ;
			else{
				$my_query="SELECT id,name,isAdmin FROM " . $tbl_admin . " WHERE username = '" . $uzername ."' AND pass = '".$passwor."' LIMIT 1";        
				$result=@mysqli_query($connect,$my_query);
				if (!$result) {
					$myJSON['success']= "400" ;
				}
				else
				{
					$countofresult = 0;
					while($row = @mysqli_fetch_assoc($result)){
						$user_id = $row["id"];		
						$myJSON['name']=$row["name"];	
						$myJSON['isAdmin']=$row["isAdmin"];	
						$countofresult++;
					}
					if($countofresult == 0)
					{
						$myJSON['success'] = "404";
					}
					else
					{
						 $myJSON['success']="200";
						 $myJSON['token'] = md5($uzername.date("Y-m-d h:i:sa"));
						 $myJSON['id']=$user_id;
						 $my_query1="SELECT id FROM ".$tbl_sessions." WHERE uid = '".$user_id."' AND type = 'A' LIMIT 1"; 
						 $result1=@mysqli_query($connect,$my_query1);
						 if (!$result1) {
							 $myJSON['success']= "401" ;
						 }
						 else
						 {
							$ses_id=0;
							$countofresult =0;
							while($row = @mysqli_fetch_assoc($result1)){
								$ses_id = $row["id"];
								$countofresult++;
							}
							if($countofresult==0)
							{
								//insert
								$my_query2="INSERT INTO ".$tbl_sessions." (uid,token,type) 
								VALUES ('".$user_id."','".$myJSON['token']."','A')";
								$result2=@mysqli_query($connect,$my_query2);
								if (!$result2) {
									$myJSON['success']= "401" ;
								}
							}
							 //update
							else
							{
								$my_query_edit= "UPDATE ".$tbl_sessions." SET token ='".$myJSON['token']."' WHERE id = '".$ses_id."'";
								$result3=@mysqli_query($connect,$my_query_edit);
								if (!$result3) {
									$myJSON['success']= "401" ;
								}
							}
						}
					}
				}
			}
		}
	}
	 else
		 $myJSON['success']="402";

    echo json_encode($myJSON);
}
		
?>