getAllPointInCountry
<?php
/**
 * Created by PhpStorm.
 * User: freuddebian
 * Date: 05/08/18
 * Time: 00:02
 */
include '../interacted/Messenger.php';
include '../init/init.php';

/**
 * Cette classe assure la connexion à la base de données et toutes les requetes nécéssaires
 */
class DataBaseConnector
{
    /**
     * @var Messenger
     */
    var $messenger;
    /**
     * @var false|mysqli Connexion
     */
    var $con;

    /**
     * DataBaseConnector constructor.
     * @param bool $isTest
     */
    public function __construct($isTest=false)
    {

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

    }

    /**
     *
     */
    public function __destruct()
    {
        mysqli_close($this->con);
    }

    /**
     * Retourne la config de la publicité en fonction du pays
     * @param $id_country ID du pays
     * @return array|bool|null
     */
    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;
        }
    }

    /**
     * Retourne la liste de configuration administrateur
     * @return array|bool|null
     */
    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;
        }
    }

    /**
     * @param $phone
     * @return bool
     */
    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;
        }
    }

    /**
     * @return array|null
     */
    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;
        }
    }

    /**
     * @param $phone
     * @return bool
     */
    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;
        }
    }

    /**
     * Verifie si un numéro de téléphone existe dans la table networks_agents
     * @param $phone
     * @param null $category
     * @param null $phoneTransaction
     * @return bool
     */
    public function isPhoneExistedInCategory($phone, $category=null, $phoneTransaction=null){

        if(isset($phoneTransaction) and isset($phone)){
            $result = mysqli_query($this->con,"SELECT na.phone from networks_agents na INNER JOIN codeGenerer cg ON na.codeGenerer_id=cg.id WHERE na.phone ='$phone' OR na.transactionNumber ='$phoneTransaction' LIMIT 1");
        }else{
            if(isset($phoneTransaction))
                $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'");
            else
                $result = mysqli_query($this->con,"SELECT na.phone from networks_agents na INNER JOIN codeGenerer cg ON na.codeGenerer_id=cg.id WHERE na.phone ='$phone' LIMIT 1");
        }
        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 isPhoneExistedAgent($phone){

        $result = mysqli_query($this->con,"SELECT * FROM networks_agents WHERE transactionNumber ='$phone' OR phone ='$phone' LIMIT 1");
        if($result) {
            $no_of_rows = mysqli_num_rows($result);
            if ($no_of_rows > 0) {
                return mysqli_fetch_array($result);
            }
        }else echo json_encode(mysqli_error($this->con));
        return false;

    }

    /**
     * @param $phone
     * @return bool
     */
    public function checknumberValidity($phone){
        return true;
        try {
            return $this->messenger->checkPhoneExist($phone);
        } catch(\Throwable $ex){
            return false;
        }
    }

    /**
     * @param $codemembre
     * @return bool
     */
    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;

    }

    /**
     * @param $code
     * @return array|bool|null
     */
    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;
        }
    }

    /**
     * @param $code
     * @return array|bool|null
     */
    public function getAgentWithCodeMembre($code){
        $listIdmemberParrain=mysqli_query($this->con,
            "SELECT na.id as agentId,na.transactionNumber as transactionNumber,ag.email as email, ag.lastname, ag.firstname , 
                    cc.code_country , cc.currency_code,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 , ne.name as reseau 
                    from agents ag INNER JOIN towns t ON ag.town_id = t.id INNER JOIN countries_currencies cc ON cc.id = t.country_id 
                    RIGHT JOIN networks_agents na on ag.id=na.agent_id RIGHT JOIN codeGenerer cg ON cg.id=na.codeGenerer_id 
                    LEFT JOIN networks ne ON ne.id = na.network_id  WHERE cg.code_membre='$code'");
        if($listIdmemberParrain){
            $membre=mysqli_fetch_array($listIdmemberParrain,MYSQLI_ASSOC);
            return $membre;
        }else return false;
    }

    /**
     * @param $code
     * @return array|null
     */
    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)];
    }

    /**
     * @param $id
     * @return array|bool|null
     */
    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(isset($demandere)){
                   $demand = mysqli_fetch_array($demandere,MYSQLI_ASSOC);
                   $membre['etat_demande']= isset($demand) ? $demand['etat'] : 1;
                }
            }
            if($membre['category']!='geolocated'){
                $membre['nbre_membre']=$this->getNbMemberOf($membre['code_membre']);
            }
            return $membre;
        }else {
            echo mysqli_error($this->con);
            return false;
        }
    }

    /**
     * @param $fname
     * @param $lname
     * @param $email
     * @param $phone
     * @param $password
     * @param $network
     * @param $member
     * @param $latitude
     * @param $longitude
     * @param $town
     * @param $phoneTransaction
     * @return array|bool|null
     */
    public function storeUser($fname, $lname, $email, $phone, $password, $network, $member, $latitude, $longitude, $town, $phoneTransaction
        ,$providerClassId = null)
    {
        //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 ,$providerClassId);
                    } 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($membre['code_membre'],'super');
                            }
                            return $this->createAgent($fname, $lname, $email, $phone, $password, $network, $me, $latitude, $longitude, $town,$phoneTransaction,$providerClassId);
                        } 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, $membre['code_membre'], $latitude,
                        $longitude, $town,$phoneTransaction,$providerClassId);
                } 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)];
        }
    }

    /**
     * @return string
     */
    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);
    }

    /**
     * @param $country
     * @return array|bool
     */
    public function getAllPointInCountry($country){
        $etat=1;
        $si=1;
        $category="geolocated";
           if($result= mysqli_prepare($this->con,"SELECT id , firstname, lastname, adresse , email , longitude , latitude , phone , transactionNumber , openHours , closeHours , solde , network, country FROM agent_plus WHERE code_dial=? AND etat=? AND category=? AND (longitude!=0 AND latitude!=0) LIMIT 3000")) {
               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;
    }

    /**
     * @param $user_id
     * @return array|bool
     */
    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;

    }

    /**
     * @param $codeparrain
     * @return array|null
     */
    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)];

    }

    /**
     * @return array
     */
    public function updateWrongPoints()
    {
        $result=[];

        return $result;
    }

    /**
     * @param $codeparrain
     * @param $user_id
     * @return array
     */
    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 , w.balance_princ , w.balance_com 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 LEFT JOIN wallets w ON na.id = w.id_networkAgent 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)) {
                    $row['balance_princ'] = $row['balance_princ'] == null ? 0 : $row['balance_princ'];
                    $row['balance_com'] = $row['balance_com'] == null ? 0 : $row['balance_com'];
                    $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;
    }

    /**
     * Retourne tous les points agents d'un réseau
     * @param int $network ID du réseau
     * @param $user_id
     * @return array
     */
    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)];
        }
    }

    /**
     * Verifie qu'un mot de passe correspond à un utilisateur dans la table
     * @param $phone
     * @param $password
     * @param $table
     * @return array|bool|mysqli_result|null
     */
    private function getUserByPhoneAndPassword($phone, $password, $table) {
        $result = mysqli_query($this->con,"SELECT usr.*,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];
        }
    }

    /**
     * @param $password
     * @return array
     */
    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;
    }

    /**
     * @param $phone
     * @param $encrypted_password
     * @param $salt
     * @return bool
     */
    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 forgotPasswordAgent($agent_id, $encrypted_password, $salt)
    {
        $result = mysqli_query($this->con, "UPDATE `agents` SET `encrypted_password` = '$encrypted_password',`salt` = '$salt' WHERE `id` = '$agent_id'");

        if ($result) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param $phone
     * @return array|bool|null
     */
    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 getEmailAgent($agent_id){
        $result = mysqli_query($this->con,"SELECT email FROM agents WHERE id = '$agent_id'");

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

        }
        else
        {
            return false;
        }

    }

    /**
     * @return array|null
     */
    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)];
    }

    /**
     * @param $salt
     * @param $password
     * @return string
     */
    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;
    }

    /**
     * @param $phone
     * @param $password
     * @return array|null
     */
    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,ne.open_wallet_at_mobile_login,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){
                                $demande =  mysqli_fetch_array($demandere, MYSQLI_ASSOC);
                                $row['etat_demande'] = $demande != null ? $demande['etat'] : null;
                            }
                            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)];

    }

    /**
     * @param $phone
     * @return array|bool|null
     */
    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;
            }

    }

    /**
     * Enregistre une demande de credit
     * @param $phone
     * @param $montant
     * @param $code
     * @return array|bool
     */
    public function storeDemandeCredit($phone, $montant, $code){
        $agent=$this->getAgentWithCodeMembre($code);
        if($agent) {
         $idag=$agent['agentId'];
         $datetime = $this->getCurrentTimeByUserID($agent['code_country']);
            $q = mysqli_query($this->con, "INSERT INTO demandeCredits(network_agent_id,montant,status,date_creation) VALUES('$idag','$montant','0','$datetime')");
            $id = mysqli_insert_id($this->con);
            if ($q) {
                return ['success' => 1, "agent" => $agent, "id" => $id, "datetime" => $datetime,
                    "currency_code" => $agent['currency_code'], "agent_name" => $agent['lastname'].' '.$agent['firstname']];
            }
        }
        return false;

}

    /**
     * @param $fname
     * @param $lnameu
     * @param $email
     * @param $phone
     * @param $password
     * @param $network
     * @param $member
     * @param $latitude
     * @param $longitude
     * @param $town
     * @param $phoneTransaction
     * @return array|bool|null
     */
    private function createAgent($fname, $lname, $email, $phone, $password, $network, $member, $latitude, $longitude, $town, $phoneTransaction,$providerClassId = null)
    {

            $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=GEOLOCATED_AGENT_ETAT;
                }

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

                if(isset($town->id)) {
                    $townid = $town->id;
                    $datetime = $this->getCurrentTimeByNetworkID($network->id);
                    $agentCreateResult = mysqli_prepare($this->con, "INSERT INTO agents(uid,adresse,
lastname,email,longitude,latitude,balance,encrypted_password,salt,active,date_created,town_id) VALUES (?,?,?,?,?,?,?,?,?,?,'$datetime',?)");
                        mysqli_stmt_bind_param($agentCreateResult,'ssssddissii' ,$uuid , $fname,$lname,$email,$longitude,$latitude,$balance,$encrypted_password,$salt,$etat, $townid);
                    $agentCreateResult = mysqli_stmt_execute($agentCreateResult);
//                     mysqli_stmt_get_result($agentCreateResult);

                    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,nh_provider_class_id) 
VALUES('$network->id','$agent_id','$balance','$etat','$code_id','$phone','$validation_code','$phoneTransaction','$providerClassId')");
                            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)];
        }
    }

    /**
     * @param $membre
     * @param $category
     * @return string|null
     */
    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;
    }

    /**
     * @param $agent
     * @return array
     */
    private function adddemandeAdhesionAgent($agent)
    {
        $codeparrain=$agent['code_parrain'];
        $resParrain=mysqli_query($this->con,"SELECT na.id as agentId , c.code_country 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 n on n.id = na.network_id INNER JOIN countries c ON c.id = n.country_id WHERE cg.code_membre='$codeparrain'");
        if($resParrain){
            $parrain=mysqli_fetch_array($resParrain,MYSQLI_ASSOC);
            $agentId=$parrain['agentId'];
            if($agentId){
                $phone=$agent['phone'];
                $datetime = $this->getCurrentTimeByCountryCode($parrain['code_country']);
                $resDemande=mysqli_query($this->con,"INSERT INTO demandeAdhesion(phone,networks_agent_id,date_creation) VALUES ('$phone','$agentId','$datetime')");
                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];
        }
    }

    /**
     * @param $firstname
     * @param $lastname
     * @param $email
     * @param $phone
     * @param $password
     * @param $network
     * @return array|null
     */
    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);
        // Generate user code
        do{
            $user_code=$this->generateRandomString();
            $q=mysqli_query($this->con,"SELECT * FROM users WHERE user_code='$user_code'");
            $rowcount=mysqli_num_rows($q);
            $codeCorrect=$rowcount<0;
        }while($codeCorrect);
        $networkid=$network->id;
        $datetime  = $this->getCurrentTimeByNetworkID($networkid);
        $result = mysqli_query($this->con,
            "INSERT INTO users(uid, adresse,lastname, phone, email,user_code, solde, encrypted_password, 
salt,validation_code, active,network_id , date_created , date_modified) VALUES
        ('$uuid', '$firstname', '$lastname', '$phone','$email','$user_code','$balance','$encrypted_password', '$salt',
        '$validation_code','0','$networkid','$datetime','$datetime')");
        // check for successful store
        if ($result) {
            // get user details
            $uid = mysqli_insert_id($this->con); // last inserted id
            $result = mysqli_query($this->con,"SELECT usr.id , 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 , usr.user_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,MYSQLI_ASSOC);

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

    }

    /**
     * @param $phone
     * @param string $code_parrain
     * @param $agent
     * @return array
     */
    public function generateNetworkAgent($phone, $code_parrain, $agent,$providerClassId = null)
    {
        $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,nh_provider_class_id)VALUES('$networkId','0','0','$codeGenererId','$phone','$agentPhone','$validation_code',$providerClassId)");
                        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)];
                }
            }

    /**
     * @param $validation_code
     * @return array|bool|null
     */
    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;
        }



    }

    /**
     * @param $idAgent
     * @param $idNetworkAgent
     * @return array
     */
    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)];
    }

    /**
     * Retourne la liste de de tous les réseaux géolocalisés d'un agent
     * @param $user_id ID de l'agent
     * @return array
     */
    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 , pc.name as provider_class from agents ag 
    INNER JOIN networks_agents na ON ag.id=na.agent_id LEFT JOIN nh_provider_classes pc ON pc.id = na.nh_provider_class_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)];

    }

    /**
     * Retourne la liste de de tous les réseaux libre d'un agent
     * @param string $code_parrain
     * @return array
     */
    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)];

    }

    /**
     * @param $codeparrain
     * @return array
     */
    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, ag.firstname, ag.lastname
                , dc.canceled_by_hypervisor , dc.cancellation_date 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' ORDER BY id ASC");
        if($q){
            $rows=[];
            while($row=mysqli_fetch_array($q,MYSQLI_ASSOC)){
                $rows[]=$row;
            }
            return $rows;
        }else
            return ['error'=>mysqli_error($this->con)];

    }

    /**
     * @param $user_id
     * @return array
     */
    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,ag.firstname, ag.lastname
                , dc.canceled_by_hypervisor , dc.cancellation_date 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' ORDER BY id ASC");
        if($q){
            $rows=[];
            while($row=mysqli_fetch_array($q,MYSQLI_ASSOC)){
                $rows[]=$row;
            }
            return $rows;
        }else
            return ['error'=>mysqli_error($this->con)];

    }

    /**
     * @param $user_id
     * @return array
     */
    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)];


    }

    /**
     * @param $code_membre
     * @return int
     */
    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;
        }
    }

    /**
     * Retourne les points agents d'un réseau autour d'un rayon de kilometres
     * @param $reseau
     * @param $position
     * @param float $distance
     * @param int $page
     * @return array|string
     */
    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);
    }

    public function createWalletForAgent($phoneTransaction=null){
        $result = mysqli_query($this->con,"SELECT id from networks_agents WHERE transactionNumber ='$phoneTransaction'");
        if($result){
            $array=mysqli_fetch_array($result,MYSQLI_ASSOC);
            $idNetworkAgent = $array['id'];
            if($idNetworkAgent){
                $result = mysqli_query($this->con,"INSERT INTO  wallets (id_networkAgent) VALUES ('$idNetworkAgent')");
                return $result;
            }else return false;
        }else return false;
    }

    public function getConfigWallet($id_network){
        $result = mysqli_query($this->con,"SELECT *  FROM `configWallet` WHERE id_network = '$id_network'");
        if($result){
            $num_row=mysqli_num_rows($result);
            return $num_row>0 ;
        }else{
            return false;
        }
    }

    public function createWalletIlink($phone=null){
        $result = mysqli_query($this->con,"SELECT id from users WHERE phone ='$phone'");
        if($result){
            $array=mysqli_fetch_array($result,MYSQLI_ASSOC);
            $idUser = $array['id'];
            if($idUser){
                $result = mysqli_query($this->con,"INSERT INTO  wallets_users (idUser) VALUES ('$idUser')");
                return $result;
            }else return false;
        }else return false;
    }

    // Obtenir l'heure en fonction du pays de l'utilisateur
    public function getCurrentTimeByUserID($id_user){
        $result = mysqli_query($this->con,"SELECT code_country FROM countries c INNER JOIN networks n on n.country_id = c.id INNER JOIN users u ON u.network_id = n.id WHERE u.id = '$id_user'");
        if($result){
            $array=mysqli_fetch_array($result,MYSQLI_ASSOC);
            $country_code = isset($array['code_country']) ? $array['code_country'] : 'GA';
            $timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code);
            $date = (sizeof($timezone) > 0) ? new \DateTime('now', new \DateTimeZone($timezone[0])) : new \DateTime();
            return $date->format('Y-m-d H:i:s');
        }else{
            return date('Y-m-d H:i:s');
        }
    }

    // Obtenir l'heure en fonction du code du pays pays de l'utilisateur
    public function getCurrentTimeByCountryCode($country_code){
        $timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code);
        $date = (sizeof($timezone) > 0) ? new \DateTime('now', new \DateTimeZone($timezone[0])) : new \DateTime();
        return $date->format('Y-m-d H:i:s');
    }

    // Obtenir l'heure en fonction de l'id du reseau
    public function getCurrentTimeByNetworkID($id_network){
        $result = mysqli_query($this->con,"SELECT code_country FROM countries c INNER JOIN networks n on n.country_id = c.id WHERE n.id = '$id_network'");
        if($result){
            $array=mysqli_fetch_array($result,MYSQLI_ASSOC);
            $country_code = isset($array['code_country']) ? $array['code_country'] : 'GA';
            $timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code);
            $date = (sizeof($timezone) > 0) ? new \DateTime('now', new \DateTimeZone($timezone[0])) : new \DateTime();
            return $date->format('Y-m-d H:i:s');
        }else{
            return date('Y-m-d H:i:s');
        }
    }

    function write_log($message){
        try{
            $log_filename = "../logs";
            if (!file_exists($log_filename))
            {
                // create directory/folder uploads.
                mkdir($log_filename, 0777, true);
            }
            $log_file_data = $log_filename.'/log_' . date("j-n-Y") . '.log';
            //Write action to txt log
            $log  = "User: ".$_SERVER['REMOTE_ADDR'].' - '.date("F j, Y, g:i a").PHP_EOL.
                "Messsage: ".$message.PHP_EOL.
                "-------------------------".PHP_EOL;
            //-
            file_put_contents($log_file_data, $log, FILE_APPEND);
        }catch (\Throwable $e){

        }
    }

    // Nano Santé
    public function getProviderClasses($networkId){
        $result = mysqli_query($this->con,"SELECT pc.id , pc.name FROM nh_provider_classes pc INNER JOIN nh_networks_configs nc ON nc.id = pc.nh_network_config_id 
            WHERE nc.network_id = $networkId ");

        if(isset($result)){
            while ($row=mysqli_fetch_array($result,MYSQLI_ASSOC)){
                $rows[]=$row;
            }
            return $rows ?? [];
        }
        return [];
    }
}
