<?php
/**
 * Created by PhpStorm.
 * User: freuddebian
 * Date: 04/08/18
 * Time: 22:36
 */


include 'DataBaseConnector.php';
class Requester
{

//TODO ajouter la comparaison partiel de la ville query with la ville
// Step 3: instantiate a new Twilio Rest Client
    var $messenger;
    var $db;
    var $user_id;
    var $messageText;
    var $enLangs=["en","en-US","en_US","ca","in","gb","GB","us"];
    /**
     * Requester constructor.
     */
    public function __construct($user_id,$lang="en")
    {

        $this->db = new DataBaseConnector();
        $this->user_id = $user_id;
        $this->messenger=new Messenger();
        $la=$lang;
        if(in_array($lang,$this->enLangs))$la='en';
        if(file_exists("./../static/$la/message.json"))
        $this->messageText=file_get_contents("./../static/$la/message.json");
        else
        $this->messageText=file_get_contents("./../static/en/message.json");
        
        $this->messageText=json_decode($this->messageText,true);
    }

    public function loginPhonePassword($phone, $password)
    {
        // check for user
        $user = $this->loginUser($phone, $password);
        if (!$user) {
            $user = $this->loginAgent($phone, $password);
            if (!$user) {
                $response["error"] = 1;
                $response["error_msg"] =$this->messageText["PHONE_OR_NUMBER_INCORRECT"] ;
                return $response;
            }
        }
        return $user;
    }
    public function getAgentInfoByCode($code){
        $codes=$this->getChildCode($code);
        if(isset($codes["child"])){
            $codes['network']=$this->db->getAgentNetworkByCode($code);
        }
        return json_encode($codes);
    }
    public function getSuperviseurNetwork($codesuperviseur)
    {
        $point = $this->db->getSuperviseurNetwork($codesuperviseur, $this->user_id);
        if (isset($point['success'])) {
            $response['success'] = 1;
            $response['datas'] = $point['val'];
            $response['catchild']=$point['catchild'];
            $response['catparent']=$point['catparrain'];
            return $response;
        } else {
            $response = ['error' => 1,
             'error_msg' => $this->messageText['UNABLE_TO_GET_GEOLOCATED_POINT'], 'sql_error' => $point["error"]];
            return $response;
        }
    }

    public function getAllCountryPoint($country)
    {
        $point = $this->db->getAllPointInCountry($country);
        if ($point) {
            $response['success'] = 1;
            $response['datas'] = $point;
            return $response;
        } else {
            $response = ['error' => 1, 'error_msg' => "impossible de recupere les points de cette ville"];
            return $response;
        }
    }

    public function recoverPasswordAgent($number)
    {
        if ($this->db->isPhoneExistedSimple($number)) {
            $randomcode = $this->db->random_string();
            $hash = $this->db->hashSSHA($randomcode);
            $encrypted_password = $hash["encrypted"]; // encrypted password
            $salt = $hash["salt"];
            $user = $this->db->forgotPasswordSimple($number, $encrypted_password, $salt);
            if ($user) {
                $mail = $this->db->getEmailSimple($number);
                if ($mail) {
                    $subject = "Password Recovery";
                    $message = sprintf($this->messageText['TEXT_RECOVERY_PASSWORD'],$randomcode);
                    $from = "noreply@ilink-app.com";
                    $headers = "From:" . $from;
                    $this->messenger->setSubject($subject);
                    $this->messenger->setHeader($headers);
                    $this->messenger->setMessage($message);
                    $this->messenger->setContact($number);
                    $this->messenger->setMail($mail['email']);
                    $this->messenger->sendMail();
                    $this->messenger->sendSms();

                    // Stop Sending SMS
                    $response["success"] = 1;

                    $response["message"] = "Le mot de passe a été modifié et un message vous a été envoyé à " . $mail["email"];
                    return $response;
                } else {
                    $response["error"] = -6;
                    $response["message"] = "impossible d'envoyer le mail";
                    $response["last_error"] = mysqli_error($this->db->con);
                    return $response;
                }
            } else {
                $response["error"] = -7;
                $response["message"] = "impossible de changer le mots de passe";
                $response["last_error"] = mysqli_error($this->db->con);
                return $response;

            }
        }else
        return ['error' => -5, 'message' => "Ce numéro n'existe pas",'phone'=>$number];
    }

    public function recoverUserPassword($number)
    {
        if ($this->db->isPhoneExistedSimple($number)) {
            $randomcode = $this->db->random_string();
            $hash = $this->db->hashSSHA($randomcode);
            $encrypted_password = $hash["encrypted"]; // encrypted password
            $salt = $hash["salt"];
            $user = $this->db->forgotPasswordSimple($number, $encrypted_password, $salt);
            if ($user) {
                $mail = $this->db->getEmailSimple($number);
                if ($mail) {
                    $subject = "Password Recovery";
                    $message = sprintf($this->messageText['TEXT_RECOVERY_PASSWORD'],$randomcode);
                    $from = "noreply@ilink-app.com";
                    $headers = "From:" . $from;
                    $this->messenger->setSubject($subject);
                    $this->messenger->setHeader($headers);
                    $this->messenger->setMessage($message);
                    $this->messenger->setContact($number);
                    $this->messenger->setMail( $mail["email"]);
                    $this->messenger->sendMail();
                    //$this->messenger->sendSms();

                    // Stop Sending SMS
                    $response["success"] = 1;
                    $response["message"] = "Le mot de passe a été modifié et un message vous a été envoyé à " . $mail["email"];
                    return $response;
                } else {
                    $response["error"] = -6;
                    $response["message"] = "impossible d'envoyer le mail";
                    $response["last_error"] = mysqli_error($this->db->con);
                    return $response;
                }
            } else {
                $response["error"] = -7;
                $response["message"] = "impossible de changer le mots de passe";
                $response["last_error"] = mysqli_error($this->db->con);
                return $response;

            }
        }else
        return ['error' => -5, 'message' => 'Ce numéro n\'existe pas',"phone"=>"$number"];

    }

    private function sendMail($email, $subject, $message, $headers)
    {
        mail($email, $subject, $message, $headers);
    }

    private function sendMessage($message, $number)
    {
        $sms = $this->client->account->messages->create(
            $number,
            array(
                // Step 6: Change the 'From' number below to be a valid Twilio number
                // that you've purchased
                'from' => sender_number,


                // the sms body
                'body' => $message
            )
        );
    }

    public function getPointAroundKm($reseau,$position, $distance,$page)
    {
        $list=$this->db->getPointInDistance($reseau,$position,$distance,$page);
        return json_encode($list);
  }

    public function getNetworkPoint($network)
    {
        $points = $this->db->getPointsNetwork($network, $this->user_id);
        if (!isset($points['error'])) {
            $pts=['success'=>1,'datas'=>$points];
            return json_encode($pts);
        } else
            return json_encode(['error' => -4, 'error_msg' => 'error query','mysql'=> mysqli_error($this->db->con),"data"=>$points,"network"=>$network,"user"=>$this->user_id]);

    }

    function distance($lat1, $lon1, $lat2, $lon2)
    {

        $theta = $lon1 - $lon2;

        $dist = sin(deg2rad($lat1)) * sin(deg2rad($lat2)) +
            cos(deg2rad($lat1)) * cos(deg2rad($lat2)) * cos(deg2rad($theta));
        $dist = acos($dist);
        $dist = rad2deg($dist);
        $miles = $dist * 60 * 1.1515;
        $unit = "K";

        if ($unit == "K") {
            return ($miles * 1.609344);
        } else if ($unit == "N") {
            return ($miles * 0.8684);
        } else {
            return $miles;
        }
    }

    public function registerGeolocated($request)
    {
        if ($this->db->isPhoneExistedInCategory($request->phone, $request->category,$request->phone_transaction)) {
            // user is already existed - error response
            $response["error"] = 1;
            $response["error_msg"] = $this->messageText['ALREADY_PHONE_NUMBER'];
            echo json_encode($response);
        } else {
            if ($checkValidity = $this->db->checknumberValidity($request->phone)) {
                $membercodetest = $this->db->isMemberCodeExisted($request->member);
                if ($membercodetest) {
                    $user = $this->db->storeUser($request->address, $request->lastname, $request->email, $request->phone,
                        $request->password, $request->network, $request->member, $request->latitude, $request->longitude, $request->town,$request->phone_transaction);
                    if ($user != null && !isset($user['error'])) {
                        //if ($user) {
                        // user stored successfully
                        $user["success"] = 1;
                            $validation = $user["validation_code"];
                            $username = $user["lastname"];
                            $subject = "Bienvenue sur Ilink";
                            $phone = $user['phone'];
                            $ct=($user['category']=='geolocated'?'Agent Géolocalisé':($user['category']=='super'?'Administrateur':'Super Administrateur'));
                            $message1 =sprintf($this->messageText['MESSAGE_1'],$username,$ct,$phone,$request->password,$validation);
                            $message2 = sprintf($this->messageText['MESSAGE_2'],$username,$ct,$phone,$request->password);
                            $from = "noreply@ilink-app.com";
                            $headers = "From:" . $from;
                            $name = "ilink";

                            $this->messenger->setReceiverMail($user['email']);
                            $this->messenger->setContact($user['phone']);
                            $this->messenger->setMessage($user['category']=='super'?$message2:$message1);
                            $this->messenger->setSubject($subject);
                            $this->messenger->setHeader($headers);
                            if (!$this->messenger->sendMail()) {
                                return json_encode(error_get_last());
                            };
                            $sms = $this->messenger->sendSms();


                    }
                    return json_encode($user);

                  /*  echo "Réseau : ".strtoupper($user["network"])."<br />";
                    echo "<br />";
                    echo "Nom(s) :".$user["lastname"]."<br />";
                    echo "Email par défaut du réseau : ".$user["email"]."<br />";
                    echo "Telephone :".$user["phone"]."<br />";
                    echo "Code membre pour le réseau : ".$user["code_membre"]."<br />";
                    echo "<br />";*/
                } else {
                    return json_encode(['error' => 'unable to get membrre', 'error_msg' => $this->messageText['NO_CODE_MEMBER']]);

                }
            }else{
                return json_encode(['error' => 'unable to get membrre',"msg"=>$this->messageText, 'error_msg' => $this->messageText['INVALID_PHONE']]);

            }
        }


    }

    public function getNetwork()
    {
        return json_encode($this->db->getNetwork());
    }

    public function loginUser($phone, $password)
    {
        $user = $this->db->getUserByPhoneAndPasswordSimple($phone, $password);
        if (!isset($user['error'])) {
            // user found
            // echo json with success = 1
            $user["success"] = 1;
            if(isset($user['active']))
            $user['etat']=$user['active'];

        } else {
            switch ($user['error']){
                case -2:$user['error_msg']=$this->messageText['WRONG_PHONE_NUMBER'];
                break;
                case -3:
                    $user['error_msg']=$this->messageText['WRONG_PASSWORD'];break;
            }
        }
        return $user;
    }

    public function loginAgent($phone, $password)
    {
        $user = $this->db->getUserByPhoneAndPasswordGeolocated($phone, $password);
        if (!isset($user['error'])) {
            // user found
            // echo json with success = 1
            $user["success"] = 1;
            return $user;

        } else

            return $user;

    }

    public function getSupervisorAdhesionList($codeparrain)
    {
        $resparrain=mysqli_query($this->db->con,"SELECT na.id as id FROM networks_agents na INNER JOIN codeGenerer cg ON na.codeGenerer_id=cg.id WHERE cg.code_membre='$codeparrain'");
        if($resparrain){
            $parrain=mysqli_fetch_array($resparrain,MYSQLI_ASSOC)['id'];

            $r=mysqli_query($this->db->con,"select ag.firstname as firstname,ag.lastname as lastname, ag.email as email,na.phone as phone ,ne.name as network,cg.code_membre as code_membre,cg.code_parrain as code_parrain,ds.etat as etat
 from  agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id INNER JOIN codeGenerer cg ON na.codeGenerer_id=cg.id INNER JOIN networks ne ON na.network_id=ne.id INNER JOIN demandeAdhesion ds ON 1=1 WHERE ds.networks_agent_id='$parrain' AND cg.code_membre!='$codeparrain' AND na.etat='0' AND ds.etat='0' AND cg.code_parrain='$codeparrain'");
            $rows=[];
            if($r) {
                while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {

                    $rows[] = $row;
                }
                if (count($rows) > 0) {
                    return $rows;
                } else {
                    echo mysqli_error($this->db->con);
                    return $rows;
                }
            }else{

                return ['error'=>mysqli_error($this->db->con)];
            }
        }else{
            return mysqli_error($this->db->con);

        }
    }

    public function getChildCode($codeparrain)
    {
        $r=$this->db->getCategoryAgent($codeparrain);
            if($r['etat']==1){
        switch ($r['category']){
            case 'hyper':
                $r['child']='super';
                break;
            case 'super':
                $r["child"]="geolocated";
                break;
    }
}
        return $r;
    }

    public function updateWrongPoint()
    {
        $result=[];
        try{
             $result = mysqli_query($this->db->con, "UPDATE users_simple SET firstname = REPLACE(firstname, 'Ã©', 'é') WHERE firstname LIKE '%Ã©%'");
        }catch (Exception $e) {
             var_dump(mysqli_error($this->db->con));
        }
        $da="freud junior";

        return $result;
    }

    public function storeCreditAsk($phone,$montant,$code)
    {
        $result=$this->db->storeDemandeCredit($phone,$montant,$code);
       if ($result) {
                $usr=$result['agent'];
               $subject = $this->messageText['NEW_DEMAND_TITLE'];
               $email = $usr['email'];
               $message = $this->messageText['SEND_CREDIT_DEMAND_TEXT_SUCCESS'];
               $from = "noreply@ilink.com";
               $headers = "From:" . $from;
               $name = "ilink";

               $this->messenger->setHeader($headers);
               $this->messenger->setContact($phone);
               $this->messenger->setMessage($message);
               $this->messenger->setReceiverMail($email);
               $this->messenger->setSubject($subject);
               $this->messenger->sendMail();
               try {
                   $this->messenger->sendSms();
               }catch (Exception $e){

               }
           } else {
               // user failed to store
               $response["error"] = 1;
               $response["result"]=$result;
               $response["error_msg"] = $this->messageText['UNABLE_TO_SEND_DEMAND'];
               $response["sql"]=mysqli_error($this->db->con);
               $response["last"]=error_get_last();
               $response["montant"]=$montant;
               $response["phone"]=$phone;
               echo json_encode($response);

           }
            return json_encode($result);

        }



    public function getCountryNetWork($indicatif)

    {
        $res=mysqli_query($this->db->con,
            "SELECT nt.id AS id, nt.name AS name,nt.country_id AS countryId FROM networks  nt INNER JOIN countries ct
                   ON nt.country_id=ct.id WHERE ct.code_dial='$indicatif' AND nt.name!=''AND nt.status=1");
        if($res){
            $rows=[];
            while($row=mysqli_fetch_array($res,MYSQLI_ASSOC)){
                $rows[]=$row;
            }
            return $rows;
       }else
           return ['error'=>'unable to query list networks','error_sql'=>mysqli_error($this->db->con)];

    }

    public function getTownInfoByName($name)
    {

        $res=mysqli_query($this->db->con,"SELECT nt.name as name,nt.id as id ,ct.code_dial as indicatif FROM towns nt INNER JOIN countries ct ON nt.country_id=ct.id WHERE UPPER(nt.name)=UPPER('$name')");
        if($res){
            while($row=mysqli_fetch_array($res,MYSQLI_ASSOC)){
                $rows[]=$row;
            }
            if($rows==null){
                return ['error'=>'unable to query town information','ville'=>$name,'error_sql'=>mysqli_error($this->db->con)];

            }
            return $rows;
        }else
            return ['error'=>'unable to query town information','ville'=>$name,'error_sql'=>mysqli_error($this->db->con)];

    }

    public function getListTownsCountry($indicatif)
    {

        $res=mysqli_query($this->db->con,"SELECT nt.name as name,nt.id as id ,ct.code_dial as indicatif FROM towns nt INNER JOIN countries ct ON nt.country_id=ct.id WHERE ct.code_dial='$indicatif'");
        if($res){
            $rows=[];
            while($row=mysqli_fetch_array($res,MYSQLI_ASSOC)){
                $rows[]=$row;
            }
            return $rows;
        }else
            return ['error'=>'unable to query list towns','indicatif'=>$indicatif,'error_sql'=>mysqli_error($this->db->con)];

    }

    public function validateAgent($phone, $code_validation,$mbre_reseau=null,$mr_sous_reseau=null)
    {
        if(isset($phone) && isset($code_validation)){
             $res=mysqli_query($this->db->con,"SELECT na.id as agentId,ag.id as agId,cg.category as category,cg.code_membre as code_membre,cg.code_parrain AS code_parrain FROM agents ag INNER JOIN networks_agents na on ag.id=na.agent_id inner JOIN codeGenerer cg ON na.codeGenerer_id=cg.id WHERE na.phone='$phone' OR na.transactionNumber='$phone' AND na.validation_code='$code_validation'");
             if($res){
                 if(mysqli_num_rows($res)>0){
                     $net=mysqli_fetch_array($res,MYSQLI_ASSOC);
                     $agentId=$net['agentId'];
                     $agId=$net['agId'];
                     $codeparrain = $net['code_parrain'];
                     $codeMembre=$net['code_membre'];
                     $re = mysqli_query($this->db->con, "SELECT ag.id as parrainId, ag.number_super as nbre_reseau,ag.number_geoBysuper as nbre_sous_reseau FROM agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id inner JOIN codeGenerer cg ON na.codeGenerer_id=cg.id WHERE cg.code_membre='$codeparrain'");
                     if($re) {
                         $parrain = mysqli_fetch_array($re, MYSQLI_ASSOC);
                         $nbre_sup = $parrain['nbre_sous_reseau'];
                         $nbre = $parrain['nbre_reseau'];
                         $parrainId=$parrain['parrainId'];
                         switch ($net['category']) {
                             case 'hyper':
                                 if (isset($mbre_reseau) && isset($mr_sous_reseau)) {
                                     $r = mysqli_query($this->db->con, "UPDATE `networks_agents` SET etat = '1' WHERE `id` = $agentId ");
                                     $var3["message_erreur_1"] = mysqli_error($this->db->con);
                                     $rs = mysqli_query($this->db->con, "UPDATE agents SET number_super='$mbre_reseau',number_geoBysuper='$mr_sous_reseau' WHERE id='$agId'");
                                     if ($r && $rs) {

                                         $var3["success"] = 1;
                                         $var3["message"] = "User has been validated successfully !";
                                         return $var3;
                                     } else {
                                         $var3["error"] = 1;
                                         $var3["message"] = mysqli_error($this->db->con);
                                         return $var3;
                                     }
                                 } else {

                                     $var3["error"] = -2;
                                     $var3["message"] = "no nbre reseau et sous reseau";
                                     return $var3;

                                 }
                                 break;
                             case 'geolocated':
                                 $r = mysqli_query($this->db->con, "UPDATE networks_agents SET etat = '1' WHERE id = '$agentId' ");
                                 if ($r) {
                                     $nbre -= $nbre > 0 ? 1 : 0;
                                     mysqli_query($this->db->con, "UPDATE agents SET number_geoBysuper = '$nbre' WHERE `id` = '$parrainId' ");
                                     $var3["success"] = 1;
                                     $var3["message"] = "User has been validated successfully !";
                                     return $var3;
                                 } else {
                                     $var3["error"] = 1;
                                     $var3["message"] = mysqli_error($this->db->con);
                                     return $var3;
                                 }
                                 break;
                             case 'super':
                                     $rs = mysqli_query($this->db->con, "UPDATE agents SET number_geoBysuper='$nbre_sup',number_super='$nbre_sup' WHERE id='$agId'");
                                     if ($rs) {
                                         if (mysqli_num_rows($re) > 0) {
                                             $r = mysqli_query($this->db->con, "UPDATE `networks_agents` SET etat = '1' WHERE id ='$agentId'");
                                             if ($r) {
                                                 $nbre -= $nbre > 0 ? 1 : 0;
                                                 if(mysqli_query($this->db->con, "UPDATE `agents` SET number_super = '$nbre' WHERE id='$parrainId'")){
                                                     $var3["success"] = 1;
                                                     $var3['nbre_sup']=$nbre;
                                                     $var3["message"] = "User has been validated successfully !";
                                                     return $var3;

                                                 }else {
                                                     $var3["error"] = 1;
                                                     $var3["message"] = mysqli_error($this->db->con);
                                                     return $var3;
                                                 }

                                             } else {
                                                 $var3["error"] = 1;
                                                 $var3["message"] = mysqli_error($this->db->con);
                                                 return $var3;
                                             }

                                         } else {
                                             $var3["error"] = -4;
                                             $var3["message"] = "impossible de trouve le parrain";
                                             return $var3;

                                         }
                                     } else {
                                         $var3["error"] = -3;
                                         $var3["message"] = mysqli_error($this->db->con);
                                         return $var3;
                                     }
                                 break;
                         }
                     }else{
                         return ['error'=>'impossible de recuperer le parrain','error_msg'=>mysqli_error($this->db->con)];

                     }
                 }else{
                     return ['error'=>'invalide code','error_msg'=>"code de validation incorrect"];
                 }
             }else{
                 return ['error'=>'unable to query info network agent','error_msg'=>mysqli_error($this->db->con)];
             }
        }

    }

    public function activeSupervisorAdhesion($code,$phone)
    {
        $idsUser=mysqli_query($this->db->con,"SELECT ag.email as email,ag.firstname as firstname,ag.lastname as lastname,na.validation_code as validation_code,na.phone as phone,
na.id as agent_id,ds.id  as demande_id FROM agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id INNER JOIN demandeAdhesion ds ON 1=1 INNER JOIN codeGenerer cg ON na.codeGenerer_id=cg.id WHERE ds.phone='$phone'  AND cg.code_membre='$code'");
        if($idsUser){
            $idsusr=mysqli_fetch_array($idsUser,MYSQLI_ASSOC);
            $idAgent=$idsusr['agent_id'];
            $demandeId=$idsusr['demande_id'];
            $udateDemande=mysqli_query($this->db->con,"UPDATE demandeAdhesion SET etat='1' WHERE id='$demandeId'");
            if($udateDemande){
                $user=$idsusr;
                $validation = $user["validation_code"];
                $username = $user["lastname"];
                $subject = "Bienvenue sur Ilink";
                $phone = $user['phone'];
                $ct='Administrateur';
                $message1 =sprintf($this->messageText['MESSAGE_3'],$ct,$phone,$validation);

                $from = "noreply@ilink-app.com";
                $headers = "From:" . $from;
                $name = "ilink";

                $this->messenger->setReceiverMail($user['email']);
                $this->messenger->setContact($user['phone']);
                $this->messenger->setMessage($message1);
                $this->messenger->setSubject($subject);
                $this->messenger->setHeader($headers);
                if (!$this->messenger->sendMail()) {
                    return json_encode(error_get_last());
                };

                $sms = $this->messenger->sendSms();


            }else{
                echo mysqli_error($this->db->con);
            }
            echo json_encode($idsusr);
        }else{
            echo mysqli_error($this->db->con);
        }


    }

    public function registerUser($request)
    {
        if ($this->db->isPhoneExistedSimple($request->phone)) {
            // user is already existed - error response
            $response["error"] = 1;
            $response["error_msg"] = "numero existe deja";
            echo json_encode($response);
        } else {
            if ($checkValidity = $this->db->checknumberValidity($request->phone)) {
                $user = $this->db->storeUserSimple($request->address, $request->lastname, $request->email,
                    $request->phone,
                    $request->password, $request->network);
                if ($user != null && !isset($user['error'])) {
                    $user["success"] = 1;
                    $username = $user["lastname"];
                    $subject = "Bienvenue sur Ilink";
                    $phone = $user['phone'];
                    $validation_code=$user['validation_code'];
                    $ct="Utilisateur";
                    $message1 =sprintf($this->messageText['MESSAGE_1'],$username,$ct,$phone,$request->password,$validation_code);
                    $message2 = sprintf($this->messageText['MESSAGE_2'],$username,$ct,$phone,$request->password,"");

                    $from = "noreply@ilink-app.com";
                    $headers = "From:" . $from;
                    $name = "ilink";

                    $this->messenger->setReceiverMail($user['email']);
                    $this->messenger->setContact($user['phone']);
                    $this->messenger->setMessage($message1);
                    $this->messenger->setSubject($subject);
                    $this->messenger->setHeader($headers);
                    if (!$this->messenger->sendMail()) {
                        return json_encode(error_get_last());
                    };

                    $sms = $this->messenger->sendSms();

                } else {
                    $user = ['error' => 'impossible de créer l\'utilisateur', 'error_sql' => mysqli_error($this->db->con)];
                }
                return json_encode($user);
            } else {
                return json_encode(['error' => 'unable to get membrre', 'error_msg' =>$this->messageText['INVALID_PHONE']]);

            }

        }
    }

    public function generateEmptyAgentNetworkForAgent($phone, $code_parrain)
    {
        if ($this->db->isPhoneExistedInCategory($phone)) {
            // user is al5eady existed - error response
            $response["error"] = 1;
            $response["error_msg"] =$this->messageText['ALREADY_PHONE_NUMBER'];
            return json_encode($response);
        }else{
                $user=$this->db->generateNetworkAgent($phone,$code_parrain);
                if(isset($user['success'])) {
                    $validation = $user["validation_code"];
                    $subject = "Bienvenue sur Ilink";
                    $phone1 = $user['phone'];
                    $ct='Agent Géolocalisé';
                    $message1 =sprintf($this->messageText['MESSAGE_3'],$ct,$phone,$validation);


                    $this->messenger->setContact($phone1);
                    $this->messenger->setMessage($message1);
                    $this->messenger->setSubject($subject);

                    if ($sms = $this->messenger->sendSms()) {

                        $user['message'] = $sms;
                    } else {
                        return json_encode(['error' => 'imossible d\'envoyer le message']);
                    };
                }
                return json_encode($user);
        }

    }

    public function assignNetworkToAgent($agentId, $code_parrain,$phone)
    {
        $agent = $this->db->getAgentById($agentId);
        if ($agent) {
            $indicatif=$agent["indicatif"];
            if ($this->db->isPhoneExistedInCategory(null,null,$indicatif.$phone)) {
            $response["error"] = 1;
            $response["error_msg"] =$this->messageText['ALREADY_PHONE_NUMBER'];
            return json_encode($response);
        } else {
                $user = $this->db->generateNetworkAgent($phone, $code_parrain);
                if (isset($user['success'])) {
                     $result = $this->db->assignNetworkAgent($agentId, $user['id']);
                            if (isset($result['success'])) {
                                $geoLocated['success'] = 1;
                                $geoLocated['agent_id'] = $agentId;
                                $validation = $user["validation_code"];
                                $subject = "Bienvenue sur Ilink";
                                $phone1 = $user['phone'];
                                $message1 = sprintf($this->messageText['MESSAGE_ATTRIBUTE'],$phone1,$validation);

                                $this->messenger->setContact($phone1);
                                $this->messenger->setMessage($message1);
                                $this->messenger->setSubject($subject);
                                $this->messenger->setReceiverMail($agent['email']);
                                if ($sms = $this->messenger->sendSms()) {

                                    $user['message'] = $sms;
                                } else {
                                    return json_encode(['error' => 'imossible d\'envoyer le message']);
                                };

                                return json_encode($geoLocated);
                            } else {
                                return json_encode($result);
                            }
                        } else {
                            return json_encode($user);
                        }

                }

    } else {
            return json_encode(['error' => mysqli_error($this->db->con)]);
        }
}


    public function listNetworksGeo()
    {
        if($this->user_id){
            $result= $this->db->getListNetworkOfGeoPoint($this->user_id);
            if(!isset($result['error'])){
            $networks=['success'=>1,'networks'=>$result];
            return $networks;

            }else
            return $result;
        }else{
            return ['error'=>'unable to find user_id'];
        }

    }

    public function listFreeNetworksForSuper()
    {
        if($this->user_id){
            $result= $this->db->getListFreeNetworkOfGeoPoint($this->user_id);
            if(!isset($result['error'])){
                $networks=['success'=>1,'networks'=>$result];
                return $networks;

            }else
                return $result;
        }else{
            return ['error'=>'unable to find user_id'];
        }
    }

    public function getAgentReceiveDemande()
    {
        if($this->user_id){
            $result= $this->db->getListDemandeReceiveAgent($this->user_id);
            if(!isset($result['error'])){
                $networks=['success'=>1,'demands'=>$result];
                return json_encode($networks);

            }else
                return json_encode($result);
        }else{
            return json_encode(['error'=>'unable to find user_id']);
        }

    }

    public function getAgentSendDemande()
    {
        if($this->user_id){
            $result= $this->db->getListDemandeSendAgent($this->user_id);
            if(!isset($result['error'])){
                $networks=['success'=>1,'demands'=>$result];
                return json_encode($networks);

            }else
                return json_encode($result);
        }else{
            return json_encode(['error'=>'unable to find user_id']);
        } }

    public function treatDemand($phone)
    {
        if($this->user_id){
            $result= $this->db->treatDemand($this->user_id);
            if(isset($result['success'])){
                $this->messenger->setContact($phone);
                $this->messenger->setMessage($this->messageText['MESSAGE_TREAT']);
                $this->messenger->sendSms();
            }
                return json_encode($result);
        }else{
            return json_encode(['error'=>'unable to find user_id']);
        }

    }

    public function getActiveCountries()
    {
        $mq=mysqli_query($this->db->con,"SELECT DISTINCT ct.id,ct.code_dial,ct.name,ct.code_country FROM countries ct INNER JOIN networks ne ON ne.country_id=ct.id");
        if($mq){
            while($row=mysqli_fetch_array($mq,MYSQLI_ASSOC)){
                $rows[]=$row;
            }
            return json_encode($rows);
        }else{
            return ['error'=>mysqli_error($this->db->con)];
        }
    }

    public function getAgentById()
    {
        return$this->db->getAgentById($this->user_id);
    }

    public function updatePosition($agentId, $longitude, $latitude)
    {
        $result=[];
            $q = mysqli_query($this->db->con, "UPDATE agents SET longitude='$longitude',latitude='$latitude' WHERE  id='$agentId'");
            if($q){
                return json_encode(['success'=>1]);
            }else return json_encode(['error'=>0,'sql'=>mysqli_error($this->db->con)]);

        }

    public function validateUser($phone)
    {

        if(isset($phone)){
            $res=mysqli_query($this->db->con,"SELECT * from users_simple WHERE phone='$phone'");
            if($res){
                if(mysqli_num_rows($res)>0){
                    $user=mysqli_fetch_array($res,MYSQLI_ASSOC);
                    $userId=$user['id'];
                    $r = mysqli_query($this->db->con, "UPDATE users SET active = '1' WHERE id = '$userId' ");
                    if($r) {
                        $var3["success"] = 1;
                        $var3["message"] = "User has been validated successfully !";
                        $res=mysqli_query($this->db->con,"SELECT * from users_simple WHERE phone='$phone'");
                        $user=mysqli_fetch_array($res,MYSQLI_ASSOC);
                        $var3['user']=$user;
                        return $var3;

                    }else{
                        return ['error'=>'impossible de recuperer le parrain','error_msg'=>mysqli_error($this->db->con)];

                    }
                }else{
                    return ['error'=>'invalide code','error_msg'=>"code de validation incorrect"];
                }
            }else{
                return ['error'=>'unable to query info network agent','error_msg'=>mysqli_error($this->db->con)];
            }
        }

    }


}
