<?php
/**
 * Created by PhpStorm.
 * User: freuddebian
 * Date: 05/08/18
 * Time: 00:02
 */
include '../interacted/Messenger.php';
define("DB_HOST", "localhost");
define("DB_USER", "root");
define("DB_PASSWORD", "vps@2017GA");
define("DB_DATABASE", "iLink_cannary");
define("DB_DATABASE_TEST","iLink_test2");
class DataBaseConnector
{
    var $messenger;
    var $con;
    public function __construct($isTest=false)
    {

        try {
            $this->con = mysqli_connect(DB_HOST, DB_USER
                    , DB_PASSWORD,DB_DATABASE_TEST);
        }catch (\Throwable $e){
            echo 'error';
            echo $e->getMessage();
        }
        $this->messenger = new Messenger();

    }
    public function __destruct()
    {
        mysqli_close($this->con);
    }
    public function getPubValue($id_country){
        $result = mysqli_query($this->con,"SELECT * from publiciteConfig WHERE id_config = '2' AND id_country='$id_country'");
        $no_of_rows = mysqli_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed
            return mysqli_fetch_array($result,MYSQLI_ASSOC);
        } else {
            // user not existed
            return false;
        }
    }
    public function getPasValue(){
        $result = mysqli_query($this->con,"SELECT * from adminConfig WHERE cle = 'pas_chargement'");
        $no_of_rows = mysqli_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed
            return mysqli_fetch_array($result,MYSQLI_ASSOC);
        } else {
            // user not existed
            return false;
        }
    }
    public function isPhoneExistedSimple($phone) {
        // connecting to mysql

        $result = mysqli_query($this->con,"SELECT phone from users WHERE phone = '$phone'");
        $no_of_rows = mysqli_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed
            return true;
        } else {
            // user not existed
            return false;
        }
    }
    public function getNetwork(){
        $r=mysqli_query($this->con,"select * from networks");

        while($row=mysqli_fetch_array($r, MYSQLI_ASSOC )) {

            $rows[] = $row;

        }
        if(count($rows)){
            return $rows;
        } else {
            return null;
        }
    }
    public function isPhoneExisted($phone) {
        $result = mysqli_query($this->con,"SELECT phone from users WHERE phone = '$phone'");
        $no_of_rows = mysqli_num_rows($result);
        if ($no_of_rows > 0) {
            // user existed
            return true;
        } else {
            // user not existed
            return false;
        }
    }
    public function isPhoneExistedInCategory($phone,$category=null,$phoneTransaction=null){

        $result = mysqli_query($this->con,"SELECT na.phone from networks_agents na INNER JOIN codeGenerer cg ON na.codeGenerer_id=cg.id WHERE na.transactionNumber ='$phoneTransaction'");
        if($result) {
            $no_of_rows = mysqli_num_rows($result);
            if ($no_of_rows > 0) {
                return true;
            }
        }else echo json_encode(mysqli_error($this->con));
        return false;

    }

    public function checknumberValidity($phone){
        return true;
        try {
            return true;//$this->messenger->checkPhoneExist($phone);
        } catch(\Throwable $ex){
            return false;
        }
    }
    public function  isMemberCodeExisted($codemembre)
    {
        $result = mysqli_query($this->con, "SELECT * from codeGenerer WHERE code_membre = '$codemembre'  ");
        if ($result) {
            $no_of_rows = mysqli_num_rows($result);
            if ($no_of_rows > 0)
                return true;
        }
            return false;

    }

    public function getAgentByCodeMembre($code)
    {

       $listIdmemberParrain= mysqli_query($this->con, "SELECT ag.id as id,ag.uid as uid,ag.firstname AS firstname,
ag.lastname AS lastname,
ag.email AS email,ag.longitude as longitude,ag.latitude AS latitude,ag.active as active,
na.validation_code as validation_code,ag.id as agentId,na.solde AS balance,na.etat AS etat
,cg.code_parrain AS code_parrain,cg.code_membre AS code_membre,na.phone as phone,na.transactionNumber as phoneTransaction,
        ag.date_created as date_created,cg.category as category,ag.salt as salt,ag.encrypted_password as encrypted_password,
        ne.name as network,ct.name as country,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 cg.id=na.codeGenerer_id
         INNER JOIN networks as ne ON na.network_id=ne.id INNER JOIN countries ct ON ct.id=ne.country_id  WHERE 
        cg.code_membre='$code'");
        if($listIdmemberParrain){
            $membre=mysqli_fetch_array($listIdmemberParrain,MYSQLI_ASSOC);
            if($membre['category']=='super'){
                $phone=$membre["phone"];
                $demandere=mysqli_query($this->con,"SELECT etat FROM demandeAdhesion WHERE phone='$phone'");
                if($demandere){
                    $membre['etat_demande']=mysqli_fetch_array($demandere,MYSQLI_ASSOC)['etat'];
                }
            }
            return $membre;
        }else {
            echo mysqli_error($this->con);
            return false;
        }
    }
    public function getAgentWithCodeMembre($code){
        $listIdmemberParrain=mysqli_query($this->con,
            "SELECT na.id as agentId,na.transactionNumber as transactionNumber,ag.email as email,ag.number_super as nbre_reseau,ag.number_geoBySuper as nbre_sous_reseau,cg.category as category, cg.code_parrain as code_parrain,cg.code_membre as code_membre,cg.id as idCode from agents ag RIGHT JOIN networks_agents na on ag.id=na.agent_id RIGHT JOIN codeGenerer cg ON cg.id=na.codeGenerer_id WHERE  cg.code_membre='$code'");
        if($listIdmemberParrain){
            $membre=mysqli_fetch_array($listIdmemberParrain,MYSQLI_ASSOC);
            return $membre;
        }else return false;
    }
    public function getAgentNetworkByCode($code){
        $listIdmemberParrain=mysqli_query($this->con,
        "SELECT ne.id, ne.name,ne.status from networks ne  INNER JOIN networks_agents na ON na.network_id=ne.id INNER JOIN codeGenerer cg ON cg.id=na.codeGenerer_id WHERE  cg.code_membre='$code'");
    if($listIdmemberParrain){
        $membre=mysqli_fetch_array($listIdmemberParrain,MYSQLI_ASSOC);
        return $membre;
    }else return ['error'=>mysqli_error($this->con)];
    }
    public function getAgentById($id){
        $listIdmemberParrain=mysqli_query($this->con, "SELECT ag.uid as uid,ag.firstname AS firstname,ag.lastname AS lastname,
                                    ag.email AS email,ag.longitude as longitude,ag.latitude AS latitude,ag.active as active,
                                  na.validation_code as validation_code,ag.id as agentId,na.solde AS balance,na.etat AS etat
                                  ,cg.code_parrain AS code_parrain,cg.code_membre AS code_membre,na.phone as phone,ne.id as network_id,
        ag.date_created as date_created,cg.category as category,ag.salt as salt,ag.encrypted_password asencrypted_password,
        ne.name as network,ct.name as country, ct.code_dial as indicatif,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 cg.id=na.codeGenerer_id
         INNER JOIN networks as ne ON na.network_id=ne.id INNER JOIN countries ct ON ct.id=ne.country_id  WHERE 
        ag.id='$id'");
        if($listIdmemberParrain){
            $membre=mysqli_fetch_array($listIdmemberParrain,MYSQLI_ASSOC);
            if($membre['category']=='super'){
                $phone=$membre["phone"];
                $demandere=mysqli_query($this->con,"SELECT etat FROM demandeAdhesion WHERE phone='$phone'");
                if($demandere){
                    $membre['etat_demande']=mysqli_fetch_array($demandere,MYSQLI_ASSOC)['etat'];
                }
            }
            if($membre['category']!='geolocated'){
                $membre['nbre_membre']=$this->getNbMemberOf($membre['code_membre']);
            }
            return $membre;
        }else {
            echo mysqli_error($this->con);
            return false;
        }
    }

    public function storeUser($fname, $lname, $email, $phone, $password, $network, $member,$latitude, $longitude,$town,$phoneTransaction)
    {
        //on verifie si y a un agent qui utilise ce code
        if(isset($town->id)){
        $membre = $this->getAgentWithCodeMembre($member);
        if ($membre) {
            if (isset($membre['agentId'])) {
                //s'il y a un agent qui a ce code on cree un membre de son reseau
                if (($membre['category'] == 'hyper' && $membre['nbre_reseau'] > 0) ||
                    ($membre['category'] == 'super' && $membre['nbre_sous_reseau'] > 0)) {
                    //si il s'agit d'un hyperviseur ou superviseur et qu'il peut encore créer des membres alors
                    if ($membre['category'] == 'super') {
                        $codeGenerer = $this->generateValideCode($membre['code_membre'], 'geolocated');
                        if ($codeGenerer != null)
                            return $this->createAgent($fname, $lname, $email, $phone, $password, $network, $codeGenerer, $latitude,
                                $longitude, $town,$phoneTransaction);
                    } else {
                        //on verifie s'il existe des codes superviseur disponible pour cette hyperviseur
                        $listIdmemberParrain = mysqli_query($this->con, "SELECT na.codeGenerer_id as id,cg.code_membre as code_membre from networks_agents na RIGHT JOIN codeGenerer cg ON cg.id=na.codeGenerer_id WHERE  cg.code_parrain='$member' AND na.id is null");
                        if ($listIdmemberParrain) {
                            if(mysqli_num_rows($listIdmemberParrain) > 0) {
                                $me = mysqli_fetch_array($listIdmemberParrain, MYSQLI_ASSOC)['code_membre'];
                            }
                            else{
                                $me=$this->generateValideCode($member,'super');
                            }
                            return $this->createAgent($fname, $lname, $email, $phone, $password, $network, $me, $latitude, $longitude, $town,$phoneTransaction);
                        } else {
                            return ["error" => -5, 'error_msg' => 'le code parrain que vous avez entrée n\'a pas de membre disponible','sql'=>mysqli_error($this->con)];
                        }
                    }
                } else {
                    return ["error" => -6, 'error_msg' => 'le code parrain que vous avez entrée n\'a pas de membre disponible'];
                }
            } else {
                //si aucun membre n'a ce code on verifie s'il sagit d'un hyperviseur
                if ($membre['category'] == 'hyper') {
                    return $this->createAgent($fname, $lname, $email, $phone, $password, $network, $member, $latitude,
                        $longitude, $town,$phoneTransaction);
                } else {
                    return ["error" => -1, "error_msg" => "impossible de verifier le membre"];
                }
            }
        } else {
            return ["error" => -2, "error_msg" => "impossible de verifier le membre", 'sql' => mysqli_error($this->con)];
        }
    }else{
            return ["error" => -10, "error_msg" => "La ville dans laquelle vous vous trouvez n'est pas encore pris en charge", 'sql' => mysqli_error($this->con)];
        }
    }

    public function random_string()
    {
        $character_set_array = array();
        $character_set_array[] = array('count' => 7, 'characters' => 'abcdefghjkmnpqrstuvwxyz');
        $character_set_array[] = array('count' => 1, 'characters' => '23456789');
        $temp_array = array();
        foreach ($character_set_array as $character_set) {
            for ($i = 0; $i < $character_set['count']; $i++) {
                $temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
            }
        }
        shuffle($temp_array);
        return implode('', $temp_array);
    }

    public function getAllPointInCountry($country){
        $etat=1;
        $si=1;
        $category="geolocated";
           if($result= mysqli_prepare($this->con,"SELECT * FROM agent_plus WHERE code_dial=? AND etat=? AND category=? AND (longitude!=0 AND latitude!=0)")) {
               mysqli_stmt_bind_param($result, 'sis', $country, $etat, $category);
               mysqli_stmt_execute($result);
               $r = mysqli_stmt_get_result($result);
               $rows=[];
               while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC )) {
               $rows[]=$row;
           }

               mysqli_stmt_close($result);
        return $rows;
        if($result) {
            $rows=[];
            while ($row = mysqli_fetch_assoc($result)) {
                $rows[] = $row;
            }
            // $rows;
        }else{
             return  ['error'=>mysqli_error($this->con)];

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

           }

        return false;
    }

    public function getUserCountryPoint($user_id){
        $result = mysqli_query($this->con,"SELECT * FROM agents ag inner JOIN networks_agents na ON na.agent_id=ag.id INNER JOIN codeGenerer cg ON na.codeGenerer_id=cg.id WHERE cg.category='geolocated' AND na.etat=1") or die(mysqli_error($this->con));
        if($result) {
            $rows=[];
            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                $rows[] = $row;
            }
            return $rows;
        }else return false;

    }

    public function getCategoryAgent($codeparrain){
        $result=mysqli_query($this->con,"SELECT category,etat FROM codeGenerer where code_membre = '$codeparrain'");
        if($result) {
            $rows=[];
            $row = mysqli_fetch_array($result, MYSQLI_ASSOC);

            return $row;
        }else return ["erro"=>mysqli_error($this->con)];

    }

    public function updateWrongPoints()
    {
        $result=[];

        return $result;
    }

    public function getSuperviseurNetwork($codeparrain,$user_id){
        $self=$this->getAgentByCodeMembre($codeparrain);
        $catparrain=$self['category'];
        $catchild=($catparrain=='hyper')?'super':($catparrain=='super'?'geolocated':null);
        if($catchild) {
            $result = mysqli_query($this->con, "select ag.longitude as longitude,
ag.adresse,
 ag.latitude as latitude,na.transactionNumber as phoneTransaction,
 ag.firstname as firstname,ag.lastname as lastname, ag.email as email,na.phone as phone,cg.code_membre as code_membre,
 nt.name as network,ct.name as country, na.etat as etat FROM networks_agents na INNER JOIN  codeGenerer cg ON na.codeGenerer_id=cg.id 
INNER JOIN networks nt ON na.network_id=nt.id INNER JOIN agents ag ON ag.id=na.agent_id INNER JOIN countries ct
 ON nt.country_id=ct.id WHERE cg.code_parrain='$codeparrain' AND cg.code_membre!='$codeparrain' AND na.etat='1' AND cg.category='$catchild'");

            $rows = [];
            $re = [];
            if ($result) {
                while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                    $rows[] = $row;
                }
                $re['val'] = $rows;
                $re['success'] = 1;
                $re['catchild']=$catchild;
                $re['catparrain']=$catparrain;
            } else {
                $re['error'] = mysqli_error($this->con);
            }
        }else{
            $re['error']='cat child not found';
        }
            return $re;
    }

    public function getPointsNetwork($network,$user_id){
        $result=mysqli_query($this->con,"SELECT ag.firstname,cg.code_membre,cg.code_parrain,ag.adresse,
ag.lastname,na.phone,ag.email,na.solde,cg.category,ne.name as network,ct.id as country,ag.longitude,ag.latitude,ag.id as AgentId,ne.id as network_id,ct.id as country_id 
FROM agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id INNER JOIN 
codeGenerer cg ON cg.id=na.codeGenerer_id INNER JOIN networks ne ON ne.id=na.network_id INNER JOIN countries ct ON ct.id=ne.country_id WHERE cg.category='geolocated' AND na.etat='1' AND na.network_id='$network' AND ag.longitude>0 AND ag.latitude>0 LIMIT 100");
        if($result) {
            $rows=[];
            while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                $rows[] = $row;
            }
            return $rows;
        }else
        {
            return ["error"=>mysqli_error($this->con)];
        }
    }

    private function getUserByPhoneAndPassword($phone, $password,$table) {
        $result = mysqli_query($this->con,"SELECT usr.active,usr.salt,usr.encrypted_password,usr.firstname,usr.lastname,usr.id,usr.phone,usr.email,usr.solde,usr.validation_code,usr.active,usr.network_id,ne.name as network,ne.country_id,ct.name as country,ct.code_dial,ct.code_country FROM $table usr INNER JOIN networks ne ON usr.network_id=ne.id INNER JOIN countries ct ON ct.id=ne.country_id WHERE phone = '$phone'") or die(mysqli_error($this->con));
        // check for result
        $no_of_rows = mysqli_num_rows($result);
        if ($no_of_rows > 0) {
            $result = mysqli_fetch_array($result,MYSQLI_ASSOC);
            $salt = $result['salt'];
            $encrypted_password = $result['encrypted_password'];
            $hash = $this->checkhashSSHA($salt, $password);
            // check for password equality
            if ($encrypted_password == $hash) {
                // user authentication details are correct
                return $result;
            }else{
                return ['error'=>-3];
            }
        } else {
            // user not found
            return ['error'=>-2,"use"=>$no_of_rows];
        }
    }

    public function hashSSHA($password) {

        $salt = sha1(rand());
        $salt = substr($salt, 0, 10);
        $encrypted = base64_encode(sha1($password . $salt, true) . $salt);
        $hash = array("salt" => $salt, "encrypted" => $encrypted);
        return $hash;
    }

    public function forgotPasswordSimple($phone, $encrypted_password, $salt)
    {
        $result = mysqli_query($this->con, "UPDATE `users` SET `encrypted_password` = '$encrypted_password',`salt` = '$salt' WHERE `phone` = '$phone'");

        if ($result) {

            return true;

        } else {
            return false;
        }
    }

    public function getEmailSimple($phone){
        $result = mysqli_query($this->con,"SELECT email FROM users WHERE phone = '$phone'");

        if ($result) {
            return mysqli_fetch_array($result);
            //return true;

        }
        else
        {
            return false;
        }

    }

    public function listNetwork(){
        echo "request";
        $res=mysqli_query($this->con,"SELECT * FROM network");
        if($res){
            return mysqli_fetch_array($res);

        }else return ['error'=>'unable to make request','error_'=>mysqli_error($this->con)];
    }

    private function checkhashSSHA($salt, $password) {

        $hash = base64_encode(sha1($password . $salt, true) . $salt);

        return $hash;
    }
    /**
     * Verifies user by phone and password
     */
    public function getUserByPhoneAndPasswordSimple($phone, $password) {
        return $this->getUserByPhoneAndPassword($phone,$password,'users');
    }
    /**
     * Verifies user by phone and password
     */
    public function generateRandomString($length = 10) {
        $characters = '23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ';
        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < $length; $i++) {
            $randomString .= $characters[rand(0, $charactersLength - 1)];
        }
        return $randomString;
    }

    public function getUserByPhoneAndPasswordGeolocated($phone, $password) {
        // connecting to mysql
        $result = mysqli_query($this->con, "SELECT ag.uid as  uid,ag.firstname AS firstname,ag.lastname AS lastname,
ag.email AS email,ag.longitude as longitude,ag.latitude AS latitude,ag.active as active,
na.validation_code as validation_code,ag.id as agentId,na.solde AS balance,na.etat AS etat
,cg.code_parrain AS code_parrain,cg.code_membre AS code_membre,na.phone as phone,na.transactionNumber as phoneTransaction,
ne.id as network_id,ag.date_created as date_created,cg.category as category,
        ag.salt as salt,ag.encrypted_password as encrypted_password,ne.name as network,ct.name as country
        ,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 cg.id=na.codeGenerer_id INNER JOIN networks as ne ON na.network_id=ne.id INNER JOIN countries ct ON ct.id=ne.country_id WHERE na.phone='$phone' or na.transactionNumber='$phone'");
        if($result){
            if(mysqli_num_rows($result)>0) {
                $mr=[];
                while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
                    $salt = $row['salt'];
                    $encrypted_password = $row['encrypted_password'];
                    $hash = $this->checkhashSSHA($salt, $password);
                    $mr["hash"]=$hash;
                    $mr["encrypted_password"]=$encrypted_password;
                    if ($encrypted_password == $hash) {
                        if ($row['category'] == 'super') {
                            $phone = $row["phone"];
                            $demandere = mysqli_query($this->con, "SELECT etat FROM demandeAdhesion WHERE phone='$phone'");
                            if ($demandere)
                                $row['etat_demande'] = mysqli_fetch_array($demandere, MYSQLI_ASSOC)['etat'];
                            else
                                echo mysqli_error($this->con);
                        }
                        if($row['category']!='geolocated'){
                         $row['nbre_membre']=$this->getNbMemberOf($row['code_membre']);


                        }

                        return $row;
                    }

                    return ['error'=>-3,"error_msg"=>"Mot de passe incorrect","last"=>$row];
                }
            }else
            return ['error'=>-1,"error_msg2"=>"Numéro incorrect",];
        }

        else
            return ['error'=>-2,"error_msg2"=>mysqli_error($this->con)];

    }

    public function getAgentNetworkByPhone($phone){
           $listIdmemberParrain=mysqli_query($this->con, "SELECT ag.uid as uid,ag.firstname AS firstname,
ag.lastname AS lastname,
ag.email AS email,ag.longitude as longitude,ag.latitude AS latitude,ag.active as active,
na.validation_code as validation_code,ag.id as agentId,na.solde AS balance,na.etat AS etat
,cg.code_parrain AS code_parrain,cg.code_membre AS code_membre,na.phone as phone,
ne.id as network_id,
na.id as networkAgentId,
        ag.date_created as date_created,cg.category as category,ag.salt as salt,ag.encrypted_password as encrypted_password,
        ne.name as network,ct.name as country,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 cg.id=na.codeGenerer_id
         INNER JOIN networks as ne ON na.network_id=ne.id INNER JOIN countries ct ON ct.id=ne.country_id  WHERE 
        na.phone='$phone'");
            if($listIdmemberParrain){
                $membre=mysqli_fetch_array($listIdmemberParrain,MYSQLI_ASSOC);
                if($membre['category']=='super'){
                    $phone=$membre["phone"];
                    $demandere=mysqli_query($this->con,"SELECT etat FROM demandeAdhesion WHERE phone='$phone'");
                    if($demandere){
                        $membre['etat_demande']=mysqli_fetch_array($demandere,MYSQLI_ASSOC)['etat'];
                    }
                }
                return $membre;
            }else {
                echo mysqli_error($this->con);
                return false;
            }

    }

    public function storeDemandeCredit($phone,$montant,$code){
        $agent=$this->getAgentWithCodeMembre($code);
        if($agent) {
         $idag=$agent['agentId'];
            $q = mysqli_query($this->con, "INSERT INTO demandeCredits(network_agent_id,montant,status) VALUES('$idag','$montant','0')");
            if ($q) {
                return ['success' => 1, "agent" => $agent];
            }
        }
        return false;

}

    private function createAgent($fname, $lname, $email, $phone, $password, $network, $member, $latitude, $longitude, $town,$phoneTransaction)
    {

            $resultFreeCode = mysqli_query($this->con, "SELECT id,code_membre,category,code_parrain from codeGenerer cg WHERE  code_membre='$member' ");
            if($resultFreeCode){
            $freecodenum=mysqli_num_rows($resultFreeCode);
            if($freecodenum>0) {
                $codes = mysqli_fetch_array($resultFreeCode, MYSQLI_ASSOC);
                $freecode = $codes;
                $code_id = $freecode['id'];
                $category=$freecode["category"];
                $uuid = uniqid('', true);
                $balance = 0;
                $etat=0;
                if($category=="geolocated"){
                    $etat=0;
                }

                $hash = $this->hashSSHA($password);
                $encrypted_password = $hash["encrypted"];
                $salt = $hash["salt"];
                $validation_code = $this->random_string();

                if(isset($town->id)) {
                    $townid = $town->id;

                    $agentCreateResult = mysqli_query($this->con, "INSERT INTO agents(uid,adresse,
lastname,email,longitude,latitude
,balance,encrypted_password,salt,active,date_created,town_id) VALUES ('$uuid',
'$fname','$lname','$email','$longitude','$latitude','$balance','$encrypted_password','$salt','$etat',NOW(),'$townid')");
                    if ($agentCreateResult) {
                        $agent_id = mysqli_insert_id($this->con);
                        if ($agent_id) {



                            $result = mysqli_query($this->con, "INSERT INTO networks_agents(network_id,agent_id,
solde,etat,codeGenerer_id,phone,validation_code,transactionNumber) 
VALUES('$network->id','$agent_id','$balance','$etat','$code_id','$phone','$validation_code','$phoneTransaction')");
                            if ($result) {
                                // get user details

                                $agent= $this->getAgentById($agent_id);
                                $resque=mysqli_query($this->con,"UPDATE codeGenerer SET etat='1' WHERE code_membre='$member'");
                                if($resque){
                                    if($agent['category']=='super'){
                                        $re=$this->adddemandeAdhesionAgent($agent);
                                        if(!isset($re['success']))return $re;
                                    }
                                }else{
                                    return [
                                        'error' => 'impossible de de mettre à jour',
                                        'sql_error' => mysqli_error($this->con),
                                    ];
                                }
                                return $agent;
                            } else {
                                return [
                                    'error' => 'impossible de créer un network_agent',
                                    'sql_error' => mysqli_error($this->con),
                                    'code_generer' => $freecode
                                ];
                            }

                        } else {
                            return [
                                'error' => 'impossible recuperer l agent',
                                'sql_error' => mysqli_error($this->con),
                                'code_generer' => $freecode
                            ];
                        }

                    } else {
                        return [
                            'error' => 'impossible de créer un agent',
                            'sql_error' => mysqli_error($this->con)
                        ];
                    }
                }else{
                    return ['error'=>-4,'error_msg'=>'la ville que vous aviez entrée n\'est pas encore pris en compte ','ville'=>$town];
                }

            }else return ['error'=>"ce parrain à atteint son quota de membre"];
        }else{
            return ["error"=>"impossible de recuperer verifier la disponibilité ","error_msg"=>mysqli_error($this->con)];
        }
    }

    public function generateValideCode($membre, $category)
    {
        $code=null;
        $valide=false;
        do{
            $code=$this->generateRandomString();
            $q = mysqli_query($this->con, "SELECT * from codeGenerer WHERE code_membre='$code'");
                if ($q) {
                    $valide = mysqli_num_rows($q) == 0;
                     $qe=mysqli_query($this->con, "INSERT INTO codeGenerer(code_parrain,code_membre,category,etat) VALUES ('$membre','$code','$category',0)");
                    if(!$qe){
                        echo mysqli_error($this->con);
                        return null;
                    }
            }else{
                    echo mysqli_error($this->con);
                    return null;
                }
        }while(!$valide);
        return $code;
    }

    private function adddemandeAdhesionAgent($agent)
    {
        $codeparrain=$agent['code_parrain'];
        $resParrain=mysqli_query($this->con,"SELECT na.id as agentId FROM agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id INNER JOIN codeGenerer cg ON cg.id=na.codeGenerer_id WHERE cg.code_membre='$codeparrain'");
        if($resParrain){
            $parrain=mysqli_fetch_array($resParrain,MYSQLI_ASSOC);
            $agentId=$parrain['agentId'];
            if($agentId){
                $phone=$agent['phone'];
                $resDemande=mysqli_query($this->con,"INSERT INTO demandeAdhesion(phone,networks_agent_id) VALUES ('$phone','$agentId')");
                if($resDemande){
                    return ['success'=>1];
                }else{
                    return ["error"=>1,"sql"=>mysqli_error($this->con),'agent'=>$agent];
                }
            }
        }else{
            return ['error'=>'error','ssql'=>mysqli_error($this->con),'agent'=>$agent];
        }
    }

    public function storeUserSimple($firstname, $lastname, $email, $phone, $password, $network)
    {
        $uuid = uniqid('', true);
        $balance =0;
        $hash = $this->hashSSHA($password);
        $encrypted_password = $hash["encrypted"]; // encrypted password
        $salt = $hash["salt"]; // salt
        //$validation_code = generateRandomString();
            $codeCorrect=true;
        do{
            $validation_code = $this->random_string();
            $q=mysqli_query($this->con,"SELECT * FROM networks_agents WHERE validation_code='$validation_code'");
            $rowcount=mysqli_num_rows($q);
            $codeCorrect=$rowcount<0;
        }while($codeCorrect);
        $networkid=$network->id;
        $result = mysqli_query($this->con,
            "INSERT INTO users(uid, adresse,lastname, phone, email, solde, encrypted_password, 
salt,validation_code, active,network_id) VALUES
        ('$uuid', '$firstname', '$lastname', '$phone','$email','$balance','$encrypted_password', '$salt',
        '$validation_code','0','$networkid')");
        // check for successful store
        if ($result) {
            // get user details
            $uid = mysqli_insert_id($this->con); // last inserted id
            $result = mysqli_query($this->con,"SELECT ne.name as reseau,ct.name as country,usr.firstname as firstname
,usr.lastname as lastname,usr.phone as phone,usr.email as email,usr.validation_code as validation_code FROM users usr INNER JOIN networks ne ON ne.id=usr.network_id INNER JOIN countries ct ON ct.id=ne.country_id WHERE usr.id = '$uid'");
            // return user details
            if($result){
                return mysqli_fetch_array($result);

            }else return ['error'=>'error geting information','sql'=>mysqli_error($this->con)];
        } else {
            return ['error'=>'error saving information','sql'=>mysqli_error($this->con)];
        }

    }

    public function generateNetworkAgent($phone, $code_parrain,$agent)
    {
        $code=$this->generateValideCode($code_parrain,"geolocated");
         $resParrain=mysqli_query($this->con,"SELECT * FROM agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id INNER JOIN codeGenerer cg ON cg.id=na.codeGenerer_id INNER JOIN towns tw ON ag.town_id=tw.id INNER JOIN countries ct ON tw.country_id=ct.id WHERE cg.code_membre='$code_parrain'");

            if($resParrain) {
                $parrain = mysqli_fetch_array($resParrain, MYSQLI_ASSOC);
                $networkId = $parrain['network_id'];

                $phone = $parrain['code_dial'] . $phone;
                if (true) {
                    $resgg = mysqli_query($this->con, "SELECT *  FROM codeGenerer cg WHERE cg.code_membre='$code'");
                    if ($resgg) {
                        $membre = mysqli_fetch_array($resgg, MYSQLI_ASSOC);
                        $codeGenererId = $membre['id'];
                        $codevalide=true;
                        do{
                        $validation_code = $this->random_string();
                        $se=mysqli_query($this->con,"SELECT * FROM networks_agents WHERE validation_code='$validation_code'");
                        $codevalide=mysqli_num_rows($se)>0;
                        }while($codevalide);
                        $agentPhone=$agent['phone'];
                        $result = mysqli_query($this->con, "INSERT INTO networks_agents(network_id,solde,etat,codeGenerer_id,transactionNumber,phone,validation_code)VALUES('$networkId','0','0','$codeGenererId','$phone','$agentPhone','$validation_code')");
                        if ($result) {
                            $geoId=mysqli_insert_id($this->con);
                            if (mysqli_query($this->con, "UPDATE codeGenerer SET etat='1' WHERE code_membre='$code'"))
                                return ['success' => 1,'phone'=>$phone,'code_membre' => $membre['code_membre'], 'validation_code' => $validation_code,"id"=>$geoId];
                            else {
                                $da = ['error' => -7, 'error_msg' => 'impossible de mettre à jour les informations du code membre', 'sql' => mysqli_error($this->con)];
                                mysqli_query($this->con, "DELETE FROM codeGenerer WHERE code_membre='$code'");
                                return $da;
                            }
                        } else {
                            $da = ['error' => -5, 'error_msg' => 'impossible de recuperer les informations du de code generer', 'sql' => mysqli_error($this->con)];
                            mysqli_query($this->con, "DELETE FROM codeGenerer WHERE code_membre='$code'");

                            return $da;

                        }

                    } else {
                        return ['error' => -4, 'error_msg' => 'impossible de recuperer les informations du de code generer', 'sql' => mysqli_error($this->con)];

                    }
                }
                else {
                        return ['error' => -7, 'error_msg' => 'le numéro de téléphone est invalide', 'phone' =>$phone,"parrain"=>$parrain];
                    }
                } else {
                    return ['error' => -3, 'error_msg' => 'impossible de recuperer les information du parrain', 'sql' => mysqli_error($this->con)];
                }
            }

    public function getGeoLocatedFreeWithValidationCode($validation_code)
    {
        $qu=mysqli_query($this->con,"SELECT na.id as id,na.validation_code as validation_code,na.etat as etat, na.agent_id as agent_id,cg.code_membre as code_membre,cg.code_parrain as code_parrain, cg.category as category FROM networks_agents na INNER JOIN codeGenerer cg ON cg.id=na.codeGenerer_id WHERE na.validation_code='$validation_code' AND cg.category='geolocated' AND na.agent_id is null");
        if($qu){
            $num_row=mysqli_num_rows($qu);
            if($num_row>0) {
                $geo = mysqli_fetch_array($qu, MYSQLI_ASSOC);
                return $geo;
            }else {
                return ['error'=>'Ce code n\'est disponible'];
            }
        }else{
            return false;
        }



    }

    public function assignNetworkAgent($idAgent, $idNetworkAgent)
    {
        $re=mysqli_query($this->con,"UPDATE networks_agents SET agent_id='$idAgent',etat='1' WHERE id='$idNetworkAgent'");
        if($re){
            return ['success'=>1];
        }else return ['error'=>mysqli_error($this->con)];
    }

    public function getListNetworkOfGeoPoint($user_id)
    {
        $q=mysqli_query($this->con,"SELECT na.id as id,na.network_id as network_id,na.solde as solde,na.phone as phone,cg.code_membre as code_membre, cg.code_parrain as code_parrain,cg.category as category,ne.name as name from agents ag INNER JOIN networks_agents na ON ag.id=na.agent_id INNER JOIN codeGenerer cg ON cg.id=na.codeGenerer_id INNER JOIN networks ne ON ne.id=na.network_id WHERE ag.id='$user_id'");
        if($q){

            while($row=mysqli_fetch_array($q,MYSQLI_ASSOC)){
                $rows[]=$row;
            }
            return $rows;
        }else
            return ['error'=>mysqli_error($this->con)];

    }

    public function getListFreeNetworkOfGeoPoint($code_parrain)
    {
        $q=mysqli_query($this->con,"SELECT na.id as id,na.network_id as network_id,na.solde as solde,na.phone as phone,cg.code_membre as code_membre, cg.code_parrain as code_parrain,cg.category as category,ne.name as name,na.validation_code as validation_code from  networks_agents na INNER JOIN codeGenerer cg ON cg.id=na.codeGenerer_id INNER JOIN networks ne ON ne.id=na.network_id WHERE cg.code_parrain='$code_parrain' AND cg.code_membre!='$code_parrain' AND na.agent_id IS NULL");
        if($q){
            $rows=[];
            while($row=mysqli_fetch_array($q,MYSQLI_ASSOC)){
                $rows[]=$row;
            }
            return $rows;
        }else
            return ['error'=>mysqli_error($this->con)];

    }

    public function getListDemandeReceiveAgent($codeparrain)
    {

        $q=mysqli_query($this->con,"SELECT dc.id as id,dc.montant as montant,dc.date_creation,dc.date_modification,dc.status as status,na.phone as phone,cg.code_membre as code_membre, cg.code_parrain as code_parrain,cg.category as category,ne.name as name,ne.name as reseau from demandeCredits dc INNER JOIN networks_agents na ON na.id=dc.network_agent_id INNER JOIN   agents ag ON ag.id=na.agent_id INNER JOIN codeGenerer cg ON cg.id=na.codeGenerer_id INNER JOIN networks ne ON ne.id=na.network_id WHERE cg.code_parrain='$codeparrain'");
        if($q){
            $rows=[];
            while($row=mysqli_fetch_array($q,MYSQLI_ASSOC)){
                $rows[]=$row;
            }
            return $rows;
        }else
            return ['error'=>mysqli_error($this->con)];

    }

    public function getListDemandeSendAgent($user_id)
    {
        $q=mysqli_query($this->con,"SELECT ne.name as reseau, dc.id as id,dc.montant as montant,dc.date_creation,dc.date_modification,dc.status as status,na.phone as phone,cg.code_membre as code_membre, cg.code_parrain as code_parrain,cg.category as category,ne.name as name from demandeCredits dc INNER JOIN networks_agents na ON na.id=dc.network_agent_id INNER JOIN   agents ag ON ag.id=na.agent_id INNER JOIN codeGenerer cg ON cg.id=na.codeGenerer_id INNER JOIN networks ne ON ne.id=na.network_id WHERE ag.id='$user_id'");
        if($q){
            $rows=[];
            while($row=mysqli_fetch_array($q,MYSQLI_ASSOC)){
                $rows[]=$row;
            }
            return $rows;
        }else
            return ['error'=>mysqli_error($this->con)];

    }

    public function treatDemand($user_id)
    {
        $dat=date ("Y-m-d H:i:s");
        $q=mysqli_query($this->con,"UPDATE demandeCredits SET status='1',date_modification='$dat' WHERE id='$user_id'");
        if($q){
            $qdemande=mysqli_query($this->con,"SELECT * from demandeCredits dc  WHERE dc.id='$user_id'");
            if($qdemande) {
                $demande = mysqli_fetch_array($qdemande, MYSQLI_ASSOC);
                $montant = (int)$demande["montant"];
                $id = $demande['network_agent_id'];
                return ['success' => 1,"montant"=>$montant];

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


    }

    private function getNbMemberOf($code_membre)
    {
        $q=mysqli_query($this->con,"SELECT DISTINCT COUNT(*) AS nbr_membre FROM agents ag INNER JOIN networks_agents na ON na.agent_id=ag.id INNER JOIN codeGenerer cg ON na.codeGenerer_id=cg.id WHERE cg.code_parrain='$code_membre' AND cg.code_membre!='$code_membre' AND na.etat='1'");
        if($q){
            return mysqli_fetch_array($q,MYSQLI_ASSOC)['nbr_membre'];
        }else{
            return 0;
        }
    }

    public function getPointInDistance($reseau,$position, $distance,$page)
    {
        $mlat=$position->latitude;
        $mlong=$position->longitude;
        $re=$reseau->id;
        $offset=$page*50;
       $res= mysqli_query($this->con,"SELECT ag.id as agentId,na.id as id,ag.longitude as longitude,
ag.adresse,
 ag.latitude as latitude,na.transactionNumber as phoneTransaction,
 ag.firstname as firstname,ag.lastname as lastname, ag.email as email,na.phone as phone,cg.code_membre as code_membre,
 nt.name as network,ct.name as country, na.etat as etat
  FROM agents ag INNER JOIN networks_agents na ON na.agent_id=ag.id  INNER JOIN networks nt ON na.network_id=nt.id INNER JOIN countries ct ON ct.id=nt.country_id INNER JOIN codeGenerer cg ON na.codeGenerer_id=cg.id WHERE cg.category='geolocated' AND na.etat=1 AND getDistanceMetre($mlat,ag.latitude,$mlong,ag.longitude)<=$distance AND nt.id=$re ORDER BY agentId LIMIT 51 OFFSET $offset");
        if($res){
            $li=["page"=>$page,"offset"=>$offset,"total"=>$offset,"count"=>0];
            while ($r=mysqli_fetch_array($res,MYSQLI_ASSOC)){
                $li["items"][]=$r;
                $li["count"]=$li["count"]+1;
                $li["total"]=$li["total"]+1;
            }
            return $li;
        }else return mysqli_error($this->con);
    }
}
