<?php
/**
 * Created by PhpStorm.
 * User: freuddebian
 * Date: 04/08/18
 * Time: 22:51
 */
require_once ('../database/Requester.php');

$tag="";

$postdata = file_get_contents("php://input");
$request=null;
if(isset($postdata)) {
    $request = json_decode($postdata);
}else{
    $request=$_POST;
}

if($postdata!=null && isset($request->tag)){
    $tag=$request->tag;
    switch ($tag){
        case 'login_user':
            tryToLogin($request,0);
            break;
        case 'login_agent':
            tryToLogin($request,1);
            break;
        case 'login':
            tryToLogin($request);
            break;
        case "agent_by_id":
            tryGetAgentById($request);
        break;
            case 'forgot_pass':
            recoverPassword($request);
            break;

    }
}else{
    $res=[];
    $res['error']=-4;
    $res['msg']='aucun tag n a ete defini';
    $res['data']=$request;
    $res['resty']=$postdata;
    echo json_encode($res);

}
function tryGetAgentById($request){
    if(isset($request->user_id)) {
        $req = new Requester($request->user_id, $request->lang);
        echo json_encode($req->getAgentById());
    }else
        echo json_encode(['error'=>"no_user_id"]);
    }

function recoverPassword($request){

    $res=[];
    $res['request']=$request;
        if(isset($request->number)){
            $number=$request->number;

            if(isset($request->typeaccount)){
                $type=$request->typeaccount;
                $request=new Requester(null,$request->lang);
                $res=$type==='agent'?$request->recoverPasswordAgent($number):$request->recoverUserPassword($number);
            }else{
                $res['error']=-3;
                $res['msg']='aucun type de compte n a été defini';
                $res['data']=$request;
            }
        }else{
            $res['error']=-2;
            $res['msg']='aucun numero n a été defini';
            $res['data']=$request;
        }
    echo json_encode($res);

}

function tryToLogin($request,$type=-1){
    $result=[];
    $requester=new Requester(null,$request->lang);

    if(isset($request->phone)){
        $phone=$request->phone;
        if(isset($request->password)){

         $password=$request->password;

            switch ($type){
                case 0:$user=$requester->loginUser($phone,$password);
                break;
                case 1:$user=$requester->loginAgent($phone,$password);
                break;
                default:  $user=$requester->loginPhonePassword($phone,$password);

            }
         $result=$user;
        }else{
            $result['error']=-2;
            $result['error_msg']='le mot de passe defini';
        }
    }else {
        $result['error']=-1;
        $result['error_msg']='le numero n est pas defini';
    }
    echo json_encode($result);
}
?>
