<?php
	ini_set('display_errors',1);
	include "../fines/dist/db.php";
    	// Делаем проверку метода 
	$method = $_SERVER['REQUEST_METHOD'];
	if($method!='POST'){
        http_response_code(400);
        header("Content-Type: application/json");
        $result_array['error']="Method not allowed";  
        echo json_encode($result_array);
        return;        
    }
	
	// Читаем параметры
	$data = file_get_contents('php://input');
	$json_input = json_decode($data,1);

	if($json_input === null && json_last_error() !== JSON_ERROR_NONE){
        http_response_code(400);
        header("Content-Type: application/json");
        $result_array['error']="Error  json syntax, cannot br parsed";  
        echo json_encode($result_array);
        return;        
    }

	if (isset($json_input['username'])) $login = $json_input['username']; else $login="";
	if (isset( $json_input['password'])) $password = $json_input['password']; else $password="";    

    $login=trim($login," ");
    $password=trim($password," ");
    if($login=="" || $password==""){
        http_response_code(400);
        header("Content-Type: application/json");
        $result_array['error']="Неверный имя пользователь или пароль";  
        echo json_encode($result_array);
        return;            
    }

    global $con;
    $sql = "SELECT fio +' ' + firstname + ' ' + lastname as fio, rank, password from RBDA.dbo.users with (nolock)  
            where login = '".$login."' and status='10'";

    try{
        $query = sqlsrv_query($con,$sql);
        $arr = ["code"=>"100","id"=>0,"message"=>"No exists"];
        if(sqlsrv_has_rows($query))
        {
            $row = sqlsrv_fetch_array($query);
            if (password_verify($password,$row['password'])) 
               $arr = ["code"=>"200","fio"=>$row['fio'],"rank"=>$row['rank'],"message"=>"OK"];
            else
            $arr = ["code"=>"100","message"=>"Неверный пароль"];
        }
        }catch(Exception $ex){
            
            $arr = ["code"=>"102","id"=>0,"message"=>$ex->getMessage(),"sql"=>$sql];
        }
        if ($arr['code']==200)
        {
            $result_array['fio']=$arr['fio'];
            $result_array['p0']=$arr['rank'];
            $result_array['message']=$arr['message'];
            http_response_code(200);
            header("Content-Type: application/json");
            echo json_encode($result_array);          
        }else{
            $result_array['error']=$arr['message'];
            http_response_code(400);
            header("Content-Type: application/json");
            echo json_encode($result_array);          
        }

?>