<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: capp
 * Date: 29/05/2018
 * Time: 15:49
 */


class User_model extends CI_Model
{
    public function register_user($user){


        $this->db->insert('membres', $user);

    }

    public function login_user($id,$pass,$role){

        $table = null;
        $champ_id = null;
        $query = null;

        switch ($role) {
            case 1: //admin
                $this->db->select('*');
                $this->db->from('admin');
                $this->db->where("email",$id);
                $query=$this->db->get();
                break;
            case 2: //hyperviseur ou superviseur ou agent
                $query = $this->db->query("SELECT * FROM hyper_infos WHERE code_membre='".$id."'");
                if($query->num_rows()==0){
                    $query = $this->db->query("SELECT * FROM super_infos WHERE category='super' AND code_membre='".$id."'");
                }
				if($query->num_rows()==0){
					$query = $this->db->query("SELECT * FROM agent_plus WHERE category='geolocated' AND code_membre='".$id."'");
				}
                break;
        }

        if($query->num_rows()>0)
        {
            $salt = $query->row()->salt;
            $encrypted_password = $query->row()->encrypted_password;
            $hash = checkhashSSHA($salt, $pass);
            if ($encrypted_password == $hash) {

                return $query->row();
            }else{
                return false;
            }
        }
        else{
            return false;
        }


    }

    public function email_check($email){

        $this->db->select('*');
        $this->db->from('membres');
        $this->db->where('email',$email);
        $query=$this->db->get();

        if($query->num_rows()>0){
            return false;
        }else{
            return true;
        }

    }

    public function geolocatedCount(){
        $count = $this->db->select('uid')
                          ->from("users")
                          ->where('category', 'geolocated')
                        ->count_all_results();
        return $count;
    }

    public function geolocatedCountByParrain($parrain){
        $query = $this->db->query("SELECT count(*) AS c
                                    FROM super_infos
                                    WHERE category='geolocated' AND latitude!=-1 AND longitude!=-1
                                    AND code_parrain='".$parrain."'");
        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return 0;
        }
    }

    public function getAllpositions($network,$category,$parrain){

        if($network=='all' && $category=='geolocated' && $parrain=='all'){

            $this->db->select('latitude, longitude ,lastname');
            $this->db->from('users');
            $this->db->where('category',$category);
            $query=$this->db->get();
            return $query;

        }else{

        $this->db->select('latitude, longitude ,lastname');
        $this->db->from('super_infos');
        $this->db->where('category', $category);
        $this->db->where('code_parrain', $parrain);
        $this->db->where('network', $network);
        $query=$this->db->get();
            return $query;

        }
    }

    public function countUser($category,$network,$codeParrain){

        if($codeParrain=='all'){
            $this->db->select('count(*) as c');
            $this->db->from('users');
            $this->db->where('category',$category);
            if($network!='all'){
            $this->db->where('network',$network);
            }
            $query=$this->db->get();
        }else{
            $this->db->select('count(*) as c');
            $this->db->from('super_infos');
            $this->db->where('category',$category);
            if($network!='all'){
                $this->db->where('network',$network);
            }
            $this->db->where('code_parrain',$codeParrain);
            $query=$this->db->get();
        }

        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return 0;
        }
    }

    public function countUserGeoForHyp($codeHyp){

        $query = $this->db->query("SELECT count(*) AS c
                                    FROM super_infos
                                    WHERE category='geolocated' AND latitude!=-1 AND longitude!=-1
                                    AND code_parrain IN (SELECT code_membre 
                                                          FROM super_infos 
                                                          WHERE category='super' 
                                                          AND code_parrain='".$codeHyp."')");
        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return 0;
        }
    }

    public function getAllUserGeoForHyp($codeHyp){

        $query = $this->db->query("SELECT *
                                    FROM super_infos
                                    WHERE category='geolocated' 
                                    AND code_parrain IN (SELECT code_membre 
                                                          FROM super_infos 
                                                          WHERE category='super' 
                                                          AND code_parrain='".$codeHyp."')");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function getVilleByUserGeo($network,$country){

        $this->db->distinct('ville');
        $this->db->select('town AS ville , town_id AS id');
        $this->db->from('super_infos');
        $this->db->where('category','geolocated');
        $this->db->where('network',$network);
        $this->db->where('country',$country);
        $query=$this->db->get();

            return $query;

    }

    public function getUsersGeolocatedByVilleForHyp($ville,$codeHyp){

        $query = $this->db->query("SELECT child.adresse AS adresse,child.category AS childcat,child.lastname AS lastname,
                                               child.latitude AS latitude, child.longitude AS longitude,
                                               child.etat AS active, child.code_parrain AS code_parrain,child.code_membre AS member_code,
                                               child.network AS network, child.phone AS phone, child.email AS email,dad.adresse AS supadresse,
                                               dad.lastname AS suplastname, dad.code_membre AS sup_code_membre,dad.code_parrain AS sup_code_parrain,
                                               dad.network AS sup_network, dad.category AS dadcat
                                    FROM super_infos AS child 
                                    INNER JOIN super_infos AS dad
                                            ON child.code_parrain=dad.code_membre
                                    WHERE child.category='geolocated' AND dad.category='super' AND dad.code_parrain='".$codeHyp."' AND child.town='".$ville."'
                                  LIMIT 100");

        return $query->num_rows() > 0 ? $query : false;
    }

    public function getUsersGeolocatedPositionByVilleForHyp($ville,$codeHyp){

        $query = $this->db->query("SELECT child.lastname AS lastname,
                                               child.latitude AS latitude, child.longitude AS longitude
                                    FROM super_infos AS child 
                                    INNER JOIN super_infos AS dad
                                            ON child.code_parrain=dad.code_membre
                                    WHERE child.category='geolocated' AND dad.category='super' AND dad.code_parrain='".$codeHyp."' AND child.town='".$ville."'");

        return $query->num_rows() > 0 ? $query : false;
    }

    public function getDemandes($code_membre){

        if($code_membre=='all'){
            $query = $this->db->query("SELECT *,
                                           (SELECT TIMESTAMPDIFF(SECOND,dateAjout,dateModif)
                                            FROM demande_credit AS req_im
                                            WHERE req_im.id=d.id) AS temps
                                    FROM demande_credit AS d
                                    ORDER BY dateAjout");
        }else{
            $query = $this->db->query("SELECT *
                                    FROM info_demandeCredits AS d
                                    WHERE d.codeParrain='".$code_membre."'
                                    ORDER BY dateAjout");
        }

        return $query->num_rows() > 0 ? $query : false;

    }

    public function getDemandesByVille($code_membre,$ville){

        if($code_membre=='all'){
            $query = $this->db->query("SELECT *,
                                           (SELECT TIMESTAMPDIFF(SECOND,d.date_creation,d.date_modification)
                                            FROM demandeCredits AS req_im
                                            WHERE req_im.id=d.id) AS temps
                                    FROM demandeCredits AS d
                                    WHERE d.ville='".$ville."'
                                    ORDER BY date_creation");
        }else{
            $query = $this->db->query("SELECT *
                                    FROM info_demandeCredits AS d
                                    WHERE d.codeParrain='".$code_membre."' AND d.ville='".$ville."'
                                    ORDER BY dateAjout");
		}

		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}

	}

	public function getDemandesForSuper($debut, $fin, $member_code)
	{

		$query = $this->db->query("SELECT *
                                    FROM info_demandeCredits AS d
                                    WHERE d.codeParrain='" . $member_code . "'
                                        AND d.dateAjout BETWEEN '" . $debut . "' AND '" . $fin . "'
                                    ORDER BY dateAjout");

		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}

	}

	public function getDemandesHyperForSuper($debut, $fin, $member_code)
	{

		$query = $this->db->query("SELECT *
                                    FROM info_demandeCredits AS d
                                    WHERE d.codeMembre='" . $member_code . "'  AND d.dateAjout BETWEEN '" . $debut . "' AND '" . $fin . "'
                                    ORDER BY dateAjout DESC");

		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}

	}

    public function getDemandesAdForSuper($debut , $fin , $member_code){
		$chain = $debut ?  "AND d.date_creation BETWEEN '".$debut."' AND '".$fin."'" : "";
        $query = $this->db->query("SELECT *,
                                           (SELECT TIMESTAMPDIFF(SECOND,date_creation,date_modified)
                                            FROM demandeAdhesion AS req_im
                                            WHERE req_im.id=d.id_demande) AS temps
                                    FROM info_demandesAdhesion AS d
                                    WHERE d.code_membre='".$member_code."'".$chain.
                                    "ORDER BY date_creation");

        return $query->num_rows() > 0 ? $query : false;

    }

    public function getSupervisorsForHyp($codeHyp){

        $query = $this->db->query("SELECT child.adresse AS adresse,child.category AS childcat,child.lastname AS lastname,
                                               child.etat AS active, child.code_parrain AS code_parrain,child.code_membre AS member_code,
                                               child.network AS network, child.phone AS phone, child.email AS email,dad.adresse AS supadresse,
                                               dad.lastname AS suplastname, dad.code_membre AS sup_code_membre,dad.code_membre AS sup_code_parrain,
                                               dad.network AS sup_network, dad.category AS dadcat
                                    FROM super_infos AS child 
                                    INNER JOIN hyper_infos AS dad
                                            ON child.code_parrain='".$codeHyp."'
                                    WHERE child.category='super' AND dad.category='hyper' AND dad.code_membre='".$codeHyp."'
                                  ");

        return $query->num_rows() > 0 ? $query : false;
    }

    public function getUsersGeolocatedForSup($codeSup){

        $query = $this->db->query("SELECT child.adresse AS adresse,child.category AS childcat,child.lastname AS lastname,child.agent_id,
                                               child.etat AS active, child.code_parrain AS code_parrain,child.code_membre AS member_code,
                                               child.network AS network, child.phone AS phone, child.email AS email,dad.adresse AS supadresse,
                                               dad.lastname AS suplastname, dad.code_membre AS sup_code_membre,dad.code_parrain AS sup_code_parrain,
                                               dad.network AS sup_network, dad.category AS dadcat, child.date_created
                                    FROM super_infos AS child 
                                    INNER JOIN super_infos AS dad
                                            ON child.code_parrain='".$codeSup."'
                                    WHERE child.category='geolocated' AND dad.category='super' AND dad.code_membre='".$codeSup."' LIMIT 100
                                  ");

        return $query->num_rows() > 0 ? $query : false;
    }

    public function getAllGeolocatedUsersForHyp($codeHyp){

        $query = $this->db->query("SELECT *
                                    FROM super_infos
                                    WHERE category='geolocated' AND latitude!=-1 AND longitude!=-1 
                                    AND code_parrain IN (SELECT code_membre 
                                                          FROM super_infos 
                                                          WHERE category='super' 
                                                          AND code_parrain='".$codeHyp."')
                                  ");

        return $query->num_rows() > 0 ? $query : false;
    }

	public function getAllDemandesForSuper($member_code){
		$query = $this->db->query("SELECT *
                                    FROM info_demandeCredits AS d
                                    WHERE d.codeParrain='".$member_code."'
                                    ORDER BY dateAjout");

	return ($query->num_rows() > 0) ? $query :  false;
	}

    public function getCountDemande($codeParrain){

        if($codeParrain=='all'){
            $this->db->select('count(*) as c');
            $this->db->from('demandeCredits');
            $query=$this->db->get();
        }else{
            $this->db->select('count(*) as c');
            $this->db->from('info_demandeCredits');
            $this->db->where('codeParrain',$codeParrain);
            $query=$this->db->get();
        }

        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return 0;
        }
    }

    public function getCountDemandeAd($codeParrain){

        if($codeParrain=='all'){
            $this->db->select('count(*) as c');
            $this->db->from('demande_superviseur');
            $query=$this->db->get();
        }else{
            $this->db->select('count(*) as c');
            $this->db->from('demande_superviseur');
            $this->db->where('code',$codeParrain);
            $query=$this->db->get();
        }

        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return 0;
        }
    }

    public function getCountDemandeByStatut($codeParrain,$statut){

        if($codeParrain=='all'){
            $this->db->select('count(*) as c');
            $this->db->from('demandeCredits');
            $this->db->where('statut',$statut);
            $query=$this->db->get();
        }else{
            $this->db->select('count(*) as c');
            $this->db->from('info_demandeCredits');
            $this->db->where('codeParrain',$codeParrain);
            $this->db->where('statut',$statut);
            $query=$this->db->get();
        }

        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return 0;
        }
    }

    public function getCountDemandeAdByStatut($codeParrain,$statut){

        if($codeParrain=='all'){
            $this->db->select('count(*) as c');
            $this->db->from('demande_superviseur');
            $this->db->where('Statut',$statut);
            $query=$this->db->get();
        }else{
            $this->db->select('count(*) as c');
            $this->db->from('demande_credit');
            $this->db->where('code',$codeParrain);
            $this->db->where('Statut',$statut);
			$query = $this->db->get();
		}

		if ($query->num_rows() > 0) {
			return $query->row()->c;
		} else {
			return 0;
		}
	}

	public function getRangeASCDemandes($debut, $fin, $codeParrain)
	{

		if ($codeParrain == 'all') {
			$query = $this->db->query("SELECT d.agent , d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,
                                               (SELECT TIMESTAMPDIFF(SECOND,dateAjout,dateModif)
                                                FROM demande_credit AS req_im
                                                WHERE req_im.statut='1' AND req_im.id=d.id) AS temps
                                        FROM demande_credit AS d
                                        WHERE statut='1'
                                        ORDER BY temps
                                        LIMIT 5");
		} else {
			$query = $this->db->query("SELECT d.agent, d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,d.temps AS temps
                                        FROM info_demandeCredits AS d
                                        WHERE statut='1' AND d.codeParrain='" . $codeParrain . "'
                                                AND d.dateAjout BETWEEN '" . $debut . "' AND '" . $fin . "'
                                        ORDER BY temps
                                        LIMIT 5");
		}

		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}

	}

	public function getRangeASCDemandesOut($debut, $fin, $codeParrain)
	{

		$query = $this->db->query("SELECT d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,d.temps AS temps
                                        FROM info_demandeCredits AS d
                                        WHERE statut='1' AND d.codeMembre='" . $codeParrain . "'
                                        AND d.dateAjout BETWEEN '" . $debut . "' AND '" . $fin . "'
                                        ORDER BY temps
                                        LIMIT 5");

		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}

	}

	public function getRangeASCDemandesByNetwork($debut, $fin, $codeParrain, $ville)
	{

		if ($codeParrain == 'all') {
			$query = $this->db->query("SELECT d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,
                                               (SELECT TIMESTAMPDIFF(SECOND,dateAjout,dateModif)
                                                FROM demande_credit AS req_im
                                                WHERE req_im.statut='1' AND req_im.id=d.id) AS temps
                                        FROM demande_credit AS d
                                        WHERE statut='1' AND d.reseau='" . $ville . "' AND date_creation BETWEEN '" . $debut . "' AND '" . $fin . "'
                                        ORDER BY temps
                                        LIMIT 5");
		} else {
			$query = $this->db->query("SELECT d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,d.temps AS temps
                                        FROM info_demandeCredits AS d
                                        WHERE statut='1' AND d.codeParrain='" . $codeParrain . "'
                                        AND dateAjout BETWEEN '".$debut."' AND '".$fin."'
                                        ORDER BY temps
                                        LIMIT 5");
		}

	return ($query->num_rows() > 0) ? $query :  false;

	}

    public function getRangeASCDemandesAd($debut , $fin , $codeParrain){

        if($codeParrain=='all'){
            $query = $this->db->query("SELECT d.phone AS emetteur, d.code_membre AS superviseur, d.categorie AS montant,d.date_creation AS dateA,d.date_modified AS dateM,
                                               (SELECT TIMESTAMPDIFF(SECOND,dateAjout,dateModif)
                                                FROM demande_superviseur AS req_im
                                                WHERE req_im.Statut=1 AND req_im.id=d.id) AS temps
                                        FROM info_demandesadhesion AS d
                                        WHERE Statut=1
                                        ORDER BY temps
                                        LIMIT 5");
        }else{
			$chain = $debut ?  "AND d.date_creation BETWEEN '".$debut."' AND '".$fin."'" : "";
            $query = $this->db->query("SELECT d.phone AS emetteur, d.code_membre AS superviseur, d.date_creation AS dateA,d.date_modified AS dateM,
                                               (SELECT TIMESTAMPDIFF(SECOND,date_creation,date_modified)
                                                FROM demandeAdhesion AS req_im
                                                WHERE req_im.etat=1 
                                                AND req_im.id=d.id_demande) AS temps
                                        FROM info_demandesAdhesion AS d
                                        WHERE etat=1 AND d.code_membre='".$codeParrain."'". $chain
                                        ."ORDER BY temps
                                        LIMIT 5");
		}

		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}

	}

	public function getRangeDESCDemandes($debut, $fin, $codeParrain)
	{

		if ($codeParrain == 'all') {
			$query = $this->db->query("SELECT d.agent, d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,
                                               (SELECT TIMESTAMPDIFF(SECOND,dateAjout,dateModif)
                                                FROM demande_credit AS req_im
                                                WHERE req_im.statut='1' AND req_im.id=d.id) AS temps
                                        FROM demande_credit AS d
                                        WHERE statut='1'
                                        ORDER BY temps DESC 
                                        LIMIT 5");
		} else {
			$query = $this->db->query("SELECT d.agent, d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,d.temps AS temps
                                        FROM info_demandeCredits AS d
                                        WHERE statut='1' AND d.codeParrain='" . $codeParrain . "'
                                                AND d.dateAjout BETWEEN '" . $debut . "' AND '" . $fin . "'
                                        ORDER BY temps DESC
                                        LIMIT 5");
		}

		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}

	}

	public function getRangeDESCDemandesOut($debut, $fin, $codeParrain)
	{

		$query = $this->db->query("SELECT d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,d.temps AS temps
                                        FROM info_demandeCredits AS d
                                        WHERE statut='1' AND d.codeMembre='" . $codeParrain . "'
                                        AND d.dateAjout BETWEEN '" . $debut . "' AND '" . $fin . "'
                                        ORDER BY temps DESC
                                        LIMIT 5");

		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}

	}

	public function getRangeDESCDemandesBynetwork($debut, $fin, $codeParrain, $ville)
	{

		if ($codeParrain == 'all') {
			$query = $this->db->query("SELECT d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,
                                               (SELECT TIMESTAMPDIFF(SECOND,dateAjout,dateModif)
                                                FROM demande_credit AS req_im
                                                WHERE req_im.statut='1' AND req_im.id=d.id) AS temps
                                        FROM demande_credit AS d
                                        WHERE statut='1' AND d.reseau='" . $ville . "' AND date_creation BETWEEN '" . $debut . "' AND '" . $fin . "'
                                        ORDER BY temps DESC 
                                        LIMIT 5");
		} else {
			$query = $this->db->query("SELECT d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,d.temps AS temps
                                        FROM info_demandeCredits AS d
                                        WHERE statut='1' AND d.codeParrain='" . $codeParrain . "'
                                        AND dateAjout BETWEEN '".$debut."' AND '".$fin."'
                                        ORDER BY temps DESC
                                        LIMIT 5");
		}

	return ($query->num_rows() > 0) ? $query :  false;

	}

    public function getRangeDESCDemandesAd($debut, $fin , $codeParrain){

        if($codeParrain=='all'){
            $query = $this->db->query("SELECT d.phone AS emetteur, d.code AS superviseur, d.categorie AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,
                                               (SELECT TIMESTAMPDIFF(SECOND,dateAjout,dateModif)
                                                FROM demande_superviseur AS req_im
                                                WHERE req_im.Statut=1 AND req_im.id=d.id) AS temps
                                        FROM demande_superviseur AS d
                                        WHERE Statut=1
                                        ORDER BY temps DESC 
                                        LIMIT 5");
        }else{
			$chain = $debut ?  "AND d.date_creation BETWEEN '".$debut."' AND '".$fin."'" : "";
            $query = $this->db->query("SELECT d.phone AS emetteur, d.code_membre AS superviseur, d.date_creation AS dateA,d.date_modified AS dateM,
                                               (SELECT TIMESTAMPDIFF(SECOND,date_creation,date_modified)
                                                FROM demandeAdhesion AS req_im
                                                WHERE req_im.etat=1 
                                                AND req_im.id=d.id_demande) AS temps
                                        FROM info_demandesAdhesion AS d
                                        WHERE etat=1 AND d.code_membre='".$codeParrain."'".$chain.
                                        "ORDER BY temps DESC
                                        LIMIT 5");
		}

		return ($query->num_rows() > 0) ? $query : false ;

	}

	public function getTempsMoyen($debut, $fin, $codeParrain)
	{

		if ($codeParrain == 'all') {
			$query = $this->db->query("SELECT AVG(TIMESTAMPDIFF(SECOND,dateAjout,dateModif)) AS temps FROM demande_credit WHERE statut='1'");
		} else {
			$query = $this->db->query("SELECT AVG(temps) AS temps 
                                        FROM info_demandeCredits 
                                        WHERE statut= '1' AND codeParrain='" . $codeParrain . "'
                                                AND dateAjout BETWEEN '" . $debut . "' AND '" . $fin . "'");
		}
		return ($query->num_rows() > 0) ? $query->row()->temps : false ;
	}

    public function getTempsMoyenDemandeSup($codeParrain){

        if($codeParrain=='all'){
            $query = $this->db->query("SELECT AVG(TIMESTAMPDIFF(SECOND,dateAjout,dateModif)) AS temps FROM demande_credit WHERE statut='1'");
        }else{
            $query = $this->db->query("SELECT AVG(temps) AS temps FROM info_demandeCredits WHERE statut='1' AND codeMembre='".$codeParrain."'");
		}
		return ($query->num_rows() > 0) ? $query->row()->temps : false ;
	}

	public function getTempsMoyenByVille($codeParrain, $network)
	{

		if ($codeParrain == 'all') {
			$query = $this->db->query("SELECT AVG(TIMESTAMPDIFF(SECOND,dateAjout,dateModif)) AS temps FROM demande_credit WHERE statut='1'AND reseau='" . $network . "' ");
		} else {
			$query = $this->db->query("SELECT AVG(temps) AS temps FROM info_demandeCredits WHERE statut='1' AND codeParrain='" . $codeParrain . "' ");
		}

		return ($query->num_rows() > 0) ? $query->row()->temps : false ;
	}

	public function getTempsMoyenByNetwork($id_network)
	{
		$query = $this->db->query("SELECT AVG(temps) AS temps FROM info_demandeCredits WHERE statut='1' AND id_network='" . $id_network . "' ");

		if ($query->num_rows() > 0) {
			return $query->row()->temps;
		} else {
			return false;
		}

	}

    public function getTempsMoyenAd($debut, $fin, $codeParrain){

        if($codeParrain=='all'){
            $query = $this->db->query("SELECT AVG(TIMESTAMPDIFF(SECOND,dateAjout,dateModif)) AS temps FROM demande_superviseur WHERE statut=1");
        }else{
			$chain = $debut ?  "AND date_creation BETWEEN '".$debut."' AND '".$fin."'" : "";
            $query = $this->db->query("SELECT AVG(TIMESTAMPDIFF(SECOND,date_creation,date_modified)) AS temps FROM info_demandesAdhesion WHERE etat=1 AND code_membre='".$codeParrain."'".$chain);
        }
		return ($query->num_rows() > 0) ? $query->row()->temps : false ;
    }

    public function getNetworkByHyp($codeHyp){
        $this->db->distinct('network');
        $this->db->select('network');
        $this->db->from('super_infos');
        $this->db->where('category','super');
        $this->db->where('code_parrain',$codeHyp);
        $query=$this->db->get();

        return $query;
    }

    /*public function getAllCountries(){

        $query=$this->db->query("SELECT countries.id,countries.name,countries.code_country,countries.code_dial FROM countries INNER JOIN towns t on countries.id = t.country_id and t.status=1 GROUP BY countries.id");
        return $query;
    }*/

    public function getAllGameCountries(){

        $query=$this->db->query("SELECT countries.id,countries.name,configGame.etat 
                                    FROM countries 
                                    INNER JOIN towns t on countries.id = t.country_id and t.status=1 
                                    LEFT JOIN configGame ON countries.id=configGame.id_pays
                                    WHERE countries.id IN (SELECT country_id FROM networks INNER JOIN networks_agents ON networks.id=networks_agents.network_id GROUP BY networks.country_id)    
                                    GROUP BY countries.id");
        return $query;
    }

    public function getAllCountries(){

        $query=$this->db->query("SELECT countries.id,countries.name,countries.code_country,countries.code_dial 
                                    FROM countries 
                                    INNER JOIN towns t on countries.id = t.country_id and t.status=1    
                                    GROUP BY countries.id");
        return $query;
    }

    public function getAllHyper($pays){

        $query=$this->db->query("SELECT * FROM hyper_infos WHERE country_id='".$pays."'");
        return $query;

    }

    public function getVilleNetworkByHyper($codeHyp){
        $query = $this->db->query("SELECT town,town_id FROM super_infos WHERE code_parrain='".$codeHyp."' GROUP BY town");
        return $query;
    }

    //----------------------------ADMIN--------------------------------------//

    public function adminGetDemandes($pays,$codeHyper,$ville){

        $query = $this->db->query("SELECT * FROM info_demandeCredits
                                    WHERE ville='".$ville."'
                                          AND (codeParrain='".$codeHyper."'
                                          OR codeParrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$codeHyper."' AND category ='super'))
                                    ORDER BY dateAjout");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function adminGetTempsMoyen($pays,$codeHyper,$ville){

        $query = $this->db->query("SELECT AVG(TIMESTAMPDIFF(SECOND,dateAjout,dateModif)) AS temps
                                    FROM info_demandeCredits
                                    WHERE pays='".$pays."'
                                          AND statut='1'
                                          AND ville='".$ville."'
                                          AND (codeParrain='".$codeHyper."'
                                          OR codeParrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$codeHyper."' AND category ='super'))");

        if($query->num_rows()>0){
            return $query->row()->temps;
        }else{
            return false;
        }

    }

    public function adminGetRangeASCDemandes($pays,$codeHyper,$ville){

        $query = $this->db->query("SELECT d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,d.temps AS temps
                            FROM info_demandeCredits AS d
                            WHERE pays='".$pays."'
                                  AND statut='1'
                                  AND ville='".$ville."'
                                  AND (codeParrain='".$codeHyper."'
                                  OR codeParrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$codeHyper."' AND category ='super'))
                            ORDER BY temps
                            LIMIT 5");

        return $query->num_rows() > 0 ? $query : false;

    }

    public function adminGetRangeDESCDemandes($pays,$codeHyper,$ville){

        $query = $this->db->query("SELECT d.codeMembre AS emetteur, d.codeParrain AS superviseur, d.montant AS montant,d.dateAjout AS dateA,d.dateModif AS dateM,d.temps AS temps
                            FROM info_demandeCredits AS d
                            WHERE pays='".$pays."'
                                  AND statut='1'
                                  AND ville='".$ville."'
                                  AND (codeParrain='".$codeHyper."'
                                  OR codeParrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$codeHyper."' AND category ='super'))
                            ORDER BY temps DESC
                            LIMIT 5");

        return $query->num_rows() > 0 ? $query : false;

    }

    public function adminGetAllpositions($pays,$codeHyper,$ville){

        $query = $this->db->query("SELECT child.latitude AS latitude,child.longitude AS longitude,child.lastname AS lastname
                                FROM super_infos AS child
                                  INNER JOIN super_infos AS dad
                                    ON child.code_parrain=dad.code_membre
                                WHERE child.country_id='".$pays."'
                                      AND child.code_parrain='".$codeHyper."'
                                      OR child.code_parrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$codeHyper."' AND category ='super')
                                      AND child.town_id='".$ville."'
                                      ");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function getAllSimpleUser($pays,$codeHyper){

        $query = $this->db->query("SELECT * 
                                        FROM user_infos
                                        WHERE network_id IN (SELECT super_infos.network_id
                                                          FROM super_infos
                                                                WHERE super_infos.country_id ='".$pays."'
                                                                AND super_infos.code_parrain ='".$codeHyper."'
                                                          GROUP BY super_infos.network_id)");

        return $query->num_rows() > 0 ? $query : false;
    }

    public function getGeneratedCodes($codeHyper){

        $query = $this->db->query("SELECT * FROM codeGenerer WHERE code_parrain='".$codeHyper."' AND code_parrain!=code_membre");

        return $query->num_rows() > 0 ? $query : false;

    }

    public function getGeneratedHyperCodes(){

        $query = $this->db->query("SELECT * FROM codeGenerer WHERE category='hyper'");

        return $query->num_rows() > 0 ? $query : false;

    }

    public function getDemandeSupByHyperviseur($codeHyp){

        $query=$this->db->query("SELECT *
                                    FROM info_demandesAdhesion
                                    WHERE code_membre='".$codeHyp."'");

        return $query->num_rows() > 0 ? $query : false;
    }

    public function getCodesByHyperviseur($codeHyp){

        $query=$this->db->query("SELECT *
                                    FROM codeGenerer
                                    WHERE code_parrain='".$codeHyp."' OR code_parrain IN (SELECT code_membre
                                                                        FROM super_infos
                                                                        WHERE category='super' AND code_parrain='".$codeHyp."')
                                ");

        return $query->num_rows() > 0 ? $query : false;
    }

    public function getCoutForAdmin($pays,$hyper,$ville,$type){

        switch ($type){
            case'simple_users':
                $query=$this->db->query("SELECT count(*) AS c
                                        FROM users
                                        WHERE network_id IN (SELECT super_infos.network_id
                                                          FROM super_infos
                                                                WHERE super_infos.country_id ='".$pays."'
                                                                AND super_infos.code_parrain ='".$hyper."'
                                                          GROUP BY super_infos.network_id)");
                break;
            case 'geolocated':
                $query=$this->db->query("SELECT count(*) AS c
                                            FROM super_infos
                                            WHERE latitude!=-1 AND longitude!=-1 AND category='geolocated' and town_id='".$ville."' and code_parrain IN (SELECT super_infos.code_membre
                                                                                              FROM super_infos
                                                                                              WHERE super_infos.category='super' 
                                                                                                    AND super_infos.code_parrain='".$hyper."' 
                                                                                              GROUP BY super_infos.code_membre)");
                break;
            case 'validated_code':
                $query=$this->db->query("SELECT count(*) AS c
                                    FROM codeGenerer
                                    WHERE code_membre='".$hyper."' OR code_membre IN (SELECT code_membre
                                                                        FROM super_infos
                                                                        WHERE category='super' AND code_parrain='".$hyper."')
                                ");
                break;
            case 'generated_code':
                $query = $this->db->query("SELECT count(*) AS c FROM codeGenerer WHERE code_parrain='".$hyper."' AND code_parrain!=code_membre");
                break;
            default:
                break;
        }

        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return 0;
        }
    }

    public function getGeolocatedUsersForAdmin($pays,$hyper,$ville){

        $query = $this->db->query("SELECT child.agent_id AS id,child.adresse AS adresse,child.category AS childcat,child.lastname AS lastname,
                                           child.etat AS active, child.code_parrain AS code_parrain,child.code_membre AS member_code,
                                           child.network AS network, child.phone AS phone, child.email AS email,dad.adresse AS supadresse,
                                           dad.lastname AS suplastname, dad.code_membre AS sup_code_membre,dad.code_parrain AS sup_code_parrain,
                                           dad.network AS sup_network, dad.category AS dadcat
                                    FROM super_infos AS child
                                      INNER JOIN super_infos AS dad
                                        ON child.code_parrain=dad.code_membre
                                    WHERE child.country_id='".$pays."'
                                          AND (child.code_parrain='".$hyper."'
                                          OR child.code_parrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$hyper."' AND category ='super'))
                                          AND child.town_id='".$ville."'
                                          AND child.latitude!=-1 AND child.longitude!=-1
                                          ORDER BY child.agent_id DESC LIMIT 100");

        return $query->num_rows() > 0 ? $query : false;
    }

    public function getCoutGeolocatedUsersForAdmin($pays,$hyper,$ville){

        $query = $this->db->query("SELECT COUNT(child.agent_id) AS c
                                    FROM super_infos AS child
                                      INNER JOIN super_infos AS dad
                                        ON child.code_parrain=dad.code_membre
                                    WHERE child.country_id='".$pays."'
                                          AND (child.code_parrain='".$hyper."'
                                          OR child.code_parrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$hyper."' AND category ='super'))
                                          AND child.town_id='".$ville."'
                                          AND child.latitude!=-1 AND child.longitude!=-1
                                          ");

        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return false;
        }
    }

    public function getCoutGeolocatedUsersForHyper($hyper,$ville){

        $query = $this->db->query("SELECT COUNT(child.agent_id) AS c
                                    FROM super_infos AS child
                                      INNER JOIN super_infos AS dad
                                        ON child.code_parrain=dad.code_membre
                                    WHERE child.code_parrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$hyper."' AND category ='super')
                                          AND child.town='".$ville."'
                                          AND child.latitude!=-1 AND child.longitude!=-1
                                          ");

        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return false;
        }
    }

    public function getCoutSuperForHyper($hyper){

        $query = $this->db->query("SELECT COUNT(child.agent_id) AS c
                                    FROM super_infos AS child
                                      INNER JOIN super_infos AS dad
                                        ON child.code_parrain=dad.code_membre
                                    WHERE child.code_parrain='".$hyper."' AND child.category ='super'");

        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return false;
        }
    }

    public function getCoutGeolocatedUsersForSuper($super){

        $query = $this->db->query("SELECT COUNT(child.agent_id) AS c
                                    FROM super_infos AS child
                                      INNER JOIN super_infos AS dad
                                        ON child.code_parrain=dad.code_membre
                                    WHERE child.code_parrain='".$super."' AND child.latitude!=-1 AND child.longitude!=-1
                                          ");

        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return false;
        }
    }

    public function getOnlyGeolocatedUsersForAdmin($pays,$hyper,$ville){

        $query = $this->db->query("SELECT child.adresse AS adresse,child.category AS childcat,child.lastname AS lastname,
                                           child.etat AS active, child.code_parrain AS code_parrain,child.code_membre AS member_code,
                                           child.network AS network, child.phone AS phone, child.email AS email,dad.adresse AS supadresse,
                                           dad.lastname AS suplastname, dad.code_membre AS sup_code_membre,dad.code_parrain AS sup_code_parrain,
                                           dad.network AS sup_network, dad.category AS dadcat
                                    FROM super_infos AS child
                                      INNER JOIN super_infos AS dad
                                        ON child.code_parrain=dad.code_membre
                                    WHERE child.country_id='".$pays."'
                                          AND child.code_parrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$hyper."' AND category ='super')
                                          AND child.town_id='".$ville."'
                                          AND child.category='geolocated'
                                          ");

        return $query->num_rows() > 0 ? $query : false;
    }

    public function getUsersSimpleForSup($network,$member_code){
        $query = $this->db->query("SELECT *
                                    FROM users_simple
                                    WHERE network
                                          IN (SELECT network
                                              FROM users
                                              WHERE users.category='super'
                                                    AND users.member_code='".$member_code."'
                                                    AND users.network='".$network."')
                                    ");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function getAllVilles(){
        $query = $this->db->query("SELECT towns.id, towns.name, towns.status ,c.name AS country,c.id AS country_id
                                    FROM towns INNER JOIN countries c on towns.country_id = c.id");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function getAllPays(){
        $query = $this->db->query("SELECT * FROM countries ORDER BY name");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function changeVilleStatut($id_ville,$new_statut){

        $query = $this->db->query("UPDATE towns SET towns.status = ".$new_statut." WHERE towns.id ='".$id_ville."'");

            return $query;
    }

    public function updateVille($id_country,$id_town,$town){
        $query = $this->db->query("UPDATE towns SET towns.country_id = ".$id_country.",towns.name='".$town."' WHERE towns.id ='".$id_town."'");
        return $query;
    }

    public function getAllNetworksNames(){
        $query = $this->db->query("SELECT * FROM networks WHERE country_id IS NULL ORDER BY name");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function getAllAssignedNetworks(){
        $query = $this->db->query("SELECT networks.name AS network,networks.status AS status,networks.id,countries.name AS country,networks.country_id , networks.open_wallet_at_mobile_login FROM `networks` INNER JOIN countries ON networks.country_id=countries.id");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function assignCountryToNetwork($name,$id_country){
        $query = $this->db->query("INSERT INTO networks(country_id, name) VALUE (".$id_country.",".$name.")");
        return $query;
    }

    public function checkIfAssignationExiste($id_country,$network){
        $query = $this->db->query("SELECT * FROM networks WHERE country_id='".$id_country."' AND name='".$network."'");
        if($query->num_rows()>0){
            return true;
        }else{
            return false;
        }
    }

    public function updateNetwork($id_network,$old_network,$new_network, $open_wallet_at_mobile_login){
        $this->db->query("UPDATE networks SET networks.name='".$new_network."' WHERE networks.name ='".$old_network."'");
//		var_dump([$id_network,(int)$open_wallet_at_mobile_login]);
		$this->db->where('id', $id_network);
		return $this->db->update('networks',['open_wallet_at_mobile_login' => $open_wallet_at_mobile_login]);
    }

    public function getAllAdmin(){

        $query = $this->db->query("SELECT firstname,lastname,admin.id AS id_admin,email,phone,adresse,admin.country AS country_id,admin.category,admin.salt,c.name AS country FROM admin INNER JOIN countries c on admin.country = c.id");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function isEmailExist($email) {
       $query = $this->db->query("SELECT id FROM admin WHERE email='".$email."'");
		return $query->num_rows() > 0;
    }

    public function isPhoneExist($phone) {
        $query = $this->db->query("SELECT id FROM admin WHERE phone='".$phone."'");
		return $query->num_rows() > 0;
    }

    public function getToken($token){
        $query = $this->db->query("SELECT id FROM admin WHERE token='".$token."'");
        return $query->num_rows() > 0;
    }

    public function createPasswordAdmin($encrypted_password,$salt,$token){
        $query = $this->db->query("UPDATE admin SET encrypted_password='".$encrypted_password."',salt='".$salt."' WHERE token ='".$token."'");
        return $query;
    }

    public function updateToken($new_token,$old_token){
        $query = $this->db->query("UPDATE admin SET token='".$new_token."' WHERE token ='".$old_token."'");
        return $query;
    }

    public function updateAdmin($id,$firstname,$lastname,$email,$phone,$adresse,$country,$category){
        $query = $this->db->query("UPDATE admin SET firstname='".$firstname."',lastname='".$lastname."',email='".$email."',phone='".$phone."',adresse='".$adresse."',country='".$country."',category='".$category."' WHERE id ='".$id."'");
        return $query;
    }

    public function deleteAdmin($id){
        $query = $this->db->query("DELETE FROM admin WHERE id ='".$id."'");
        return $query;
    }

    public function getPositionHyper($codeHyper){
        $query = $this->db->query("SELECT longitude,latitude FROM hyper_infos WHERE code_membre='".$codeHyper."'");
        return $query;
    }

    public function getNumberGeoBySuper($code_membre){
        $query = $this->db->query("SELECT number_geoBysuper AS numberGeo FROM super_infos WHERE code_membre='".$code_membre."' AND number_geoBysuper IS NOT NULL");
        if($query->num_rows()>0){
            return $query->row()->numberGeo;
        }else{
            return false;
        }
    }

    public function getIdAgentByMemberCode($code,$cat){
        $query=null;
        if($cat=="hyper") {
            $query = $this->db->query("SELECT agent_id AS id FROM hyper_infos WHERE code_membre='" . $code. "' ");
        }else{
            $query = $this->db->query("SELECT agent_id AS id FROM super_infos WHERE code_membre='" . $code. "' ");
        }
        if($query->num_rows()>0){
            return $query->row()->id;
        }else{
            return false;
        }
    }

    public function updateGeolocatedUser($id,$adresse,$lastname,$email, $network_agent_id = null , $providerClassId = null){
		// Update Provider class
		if(isset($providerClassId) && isset($network_agent_id)){
			$this->db->where('id', $network_agent_id);
			$this->db->update('networks_agents', ['nh_provider_class_id' => $providerClassId]);
		}
		// Update agents infos
        $query = $this->db->query("UPDATE agents SET firstname='".$adresse."',lastname='".$lastname."',email='".$email."' WHERE id ='".$id."'");
        return $query;
    }
    public function updatePhoneAgent($id,$phone){
        $query = $this->db->query("UPDATE networks_agents SET phone='".$phone."' WHERE agent_id ='".$id."'");
        return $query;
    }

    public function deleteInfosGeolocatedUser($id){
        $query = $this->db->query("DELETE FROM agents WHERE id ='".$id."'");
        return $query;
    }

    public function deleteCodeAgent($code){
        $query = $this->db->query("DELETE FROM codeGenerer WHERE code_membre ='".$code."'");
        return $query;
    }

    public function getIdCodeGenerer($code_membre){
        $query = $this->db->query("SELECT id FROM codeGenerer WHERE code_parrain='".$code_membre."' OR code_parrain IN (SELECT code_membre FROM codeGenerer where code_parrain='".$code_membre."')");
        return $query->num_rows() > 0 ? $query : false;
    }
    public function getGabonNetwork(){
        $query = $this->db->query("SELECT id,name FROM networks WHERE country_id='78'");
        return $query->num_rows() > 0 ? $query : false;
    }
    public function getCodeHyper($id_network){
        $query = $this->db->query("SELECT codeGenerer_id FROM networks_agents WHERE network_id='".$id_network."'");
        if($query->num_rows()>0){
            $query2 = $this->db->query("SELECT code_membre FROM codeGenerer WHERE id='".$query->row()->codeGenerer_id."' AND category='hyper'");
            if($query2->num_rows()>0){
                return $query2->row()->code_membre;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    public function getVillesByPays($pays_id){
        $query = $this->db->query("SELECT towns.id, towns.name, towns.status
                                    FROM towns WHERE towns.country_id='".$pays_id."'");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function getAgentsFromCountry($id_country){
        $query = $this->db->query("SELECT agent_id,lastname AS lastname, code_parrain AS code_parrain, code_membre
                                    FROM super_infos AS ag
                                    WHERE ag.country_id='".$id_country."' AND category='super'
                                    GROUP BY lastname");
        return $query->num_rows() > 0 ? $query : false;
    }

	public function getPointGeolocalised($id_network, $lastname)
	{
		$sql = "
			SELECT COUNT(id) AS c
			FROM codeGenerer
			WHERE code_parrain IN (
				SELECT code_membre
				FROM codeGenerer
				WHERE category = 'super'
				AND id IN (
					SELECT codeGenerer_id
					FROM networks_agents
					WHERE network_id = ?
						AND agent_id IN (
							SELECT id FROM agents WHERE lastname = ?
						)
				)
			)
		";

		$query = $this->db->query($sql, [$id_network, $lastname]);

		return ($query->num_rows() > 0) ? $query->row()->c : 0;
	}


    public function getPointGeolocalisedByDate($id_network, $lastname, $debut, $fin)
    {
        $sql = "
            SELECT COUNT(id) AS c 
            FROM codeGenerer
            WHERE date_creation >= ?
            AND date_creation <= ?
            AND code_parrain IN (
                SELECT code_membre 
                FROM codeGenerer
                WHERE category = 'super'
                AND id IN (
                    SELECT codeGenerer_id
                    FROM networks_agents
                    WHERE network_id = ?
                    AND agent_id IN (
                        SELECT id 
                        FROM agents 
                        WHERE lastname = ?
                    )
                )
            )
        ";

        $query = $this->db->query($sql, [$debut, $fin, $id_network, $lastname]);

        if ($query->num_rows() > 0) {
            return $query->row()->c;
        }

        return 0;
    }

	public function getCorrectPointGeolocalisedByDate($id_network, $lastname, $debut, $fin)
	{
		$sql = "
			SELECT COUNT(*) AS c
			FROM codeGenerer
			INNER JOIN networks_agents ON codeGenerer.id = networks_agents.codeGenerer_id
			WHERE codeGenerer.date_creation >= ?
			AND codeGenerer.date_creation <= ?
			AND networks_agents.phone NOT LIKE ?
			AND networks_agents.phone NOT LIKE ?
			AND codeGenerer.code_parrain IN (
				SELECT code_membre 
				FROM codeGenerer 
				WHERE category = 'super'
					AND id IN (
						SELECT codeGenerer_id 
						FROM networks_agents 
						WHERE network_id = ?
						AND agent_id IN (
							SELECT id FROM agents WHERE lastname = ?
						)
					)
			)
		";

		$params = [
			$debut,
			$fin,
			'+241+241%',
			'+2410000%',
			$id_network,
			$lastname
		];

		$query = $this->db->query($sql, $params);

		return ($query->num_rows() > 0) ? $query->row()->c : 0;
	}


    public function getNetworks($country_id){
        $query = $this->db->query("SELECT id,name FROM networks WHERE country_id ='".$country_id."'");
        return $query->num_rows() > 0 ? $query : false;
    }

	public function getActiveNetworks($country_id){
		$query = $this->db->query("SELECT id,name FROM networks WHERE country_id ='".$country_id."' AND status = 1");
	return ($query->num_rows() > 0) ? $query :  false;
	}

    public function get_current_page_records($limit, $start,$pays,$hyper,$ville)
    {
        $query = $this->db->query("SELECT child.adresse AS adresse,child.category AS childcat,child.lastname AS lastname,
                                           child.etat AS active, child.code_parrain AS code_parrain,child.code_membre AS member_code,
                                           child.network AS network, child.phone AS phone, child.email AS email,dad.adresse AS supadresse,
                                           dad.lastname AS suplastname, dad.code_membre AS sup_code_membre,dad.code_parrain AS sup_code_parrain,
                                           dad.network AS sup_network, dad.category AS dadcat
                                    FROM super_infos AS child
                                      INNER JOIN super_infos AS dad
                                        ON child.code_parrain=dad.code_membre
                                    WHERE child.country_id='".$pays."'
                                            AND child.latitude!=-1 AND child.longitude!=-1
                                          AND (child.code_parrain='".$hyper."'
                                          OR child.code_parrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$hyper."' AND category ='super'))
                                          AND child.town_id='".$ville."'
                                          LIMIT ".$start.",".$limit);

        return $query->num_rows() > 0 ? $query : false;
    }

    public function get_current_page_records_hyper($limit, $start,$hyper,$ville)
    {
        $query = $this->db->query("SELECT child.adresse AS adresse,child.category AS childcat,child.lastname AS lastname,child.solde AS solde,
                                            child.etat AS etat,
                                           child.etat AS active, child.code_parrain AS code_parrain,child.code_membre AS member_code,
                                           child.network AS network, child.phone AS phone, child.email AS email,dad.adresse AS supadresse,
                                           dad.lastname AS suplastname, dad.code_membre AS sup_code_membre,dad.code_parrain AS sup_code_parrain,
                                           dad.network AS sup_network, dad.category AS dadcat
                                    FROM super_infos AS child
                                      INNER JOIN super_infos AS dad
                                        ON child.code_parrain=dad.code_membre
                                    WHERE child.latitude!=-1 AND child.longitude!=-1
                                          AND child.code_parrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$hyper."' AND category ='super')
                                          AND child.town='".$ville."'
                                          LIMIT ".$start.",".$limit);

        return $query->num_rows() > 0 ? $query : false;
    }

    public function get_current_page_records_super($limit, $start,$super)
    {
        $query = $this->db->query("SELECT child.adresse AS adresse,child.category AS childcat,child.lastname AS lastname,child.solde AS solde,
                                           child.etat AS active, child.code_parrain AS code_parrain,child.code_membre AS member_code,
                                           child.network AS network, child.phone AS phone, child.email AS email,dad.adresse AS supadresse,
                                           dad.lastname AS suplastname, dad.code_membre AS sup_code_membre,dad.code_parrain AS sup_code_parrain,
                                           dad.network AS sup_network, dad.category AS dadcat
                                    FROM super_infos AS child
                                      INNER JOIN super_infos AS dad
                                        ON child.code_parrain=dad.code_membre
                                    WHERE child.latitude!=-1 AND child.longitude!=-1
                                          AND child.code_parrain='".$super."'
                                          LIMIT ".$start.",".$limit);

        return $query->num_rows() > 0 ? $query : false;
    }

    public function get_total($pays,$hyper,$ville)
    {
        $query = $this->db->query("SELECT COUNT(*) AS c
                                    FROM super_infos AS child
                                      INNER JOIN super_infos AS dad
                                        ON child.code_parrain=dad.code_membre
                                    WHERE child.country_id='".$pays."'
                                          AND (child.code_parrain='".$hyper."'
                                          OR child.code_parrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$hyper."' AND category ='super'))
                                          AND child.town_id='".$ville."'");
        return $query->row()->c;
    }

    public function get_current_page_records_positions($limit, $start,$pays,$hyper,$ville)
    {
        $query = $this->db->query("SELECT child.latitude AS latitude,child.longitude AS longitude,child.lastname AS lastname
                                FROM super_infos AS child
                                  INNER JOIN super_infos AS dad
                                    ON child.code_parrain=dad.code_membre
                                WHERE child.country_id='".$pays."'
                                      AND child.code_parrain='".$hyper."'
                                      OR child.code_parrain IN (SELECT code_membre FROM super_infos WHERE code_parrain='".$hyper."' AND category ='super')
                                      AND child.town_id='".$ville."'
                                      AND child.latitude!=-1 AND child.longitude!=-1
                                      LIMIT ".$start.",".$limit);

        return $query->num_rows() > 0 ? $query : false;
    }

    public function getAllNetworksInfos($country_id){
        $query = $this->db->query("SELECT * FROM networks WHERE country_id ='".$country_id."'");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function getCountries(){
        $query = $this->db->query("SELECT countries.id,countries.name,countries.code_country,countries.code_dial,towns.name AS ville,towns.id AS id_ville FROM `towns` INNER JOIN countries ON towns.country_id=countries.id GROUP BY countries.id ");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function getFreeCode(){
        $query = $this->db->query("SELECT `code_membre` FROM `codeGenerer` WHERE `etat`=0 AND `category`='hyper' LIMIT 1");
        if($query->num_rows()>0){
            return $query->row()->code_membre;
        }else{
            return false;
        }
    }

    public function turnOnNetworkAgentEtat($phone){
        $query = $this->db->query("UPDATE `networks_agents` SET `etat`=1 WHERE `phone`=".$phone);
        if($query->num_rows()>0){
            return true;
        }else{
            return false;
        }
    }

    public function turnOnCodeGenererEtat($code_membre){
        $query = $this->db->query("UPDATE `codeGenerer` SET `etat`=1 WHERE `code_membre`=".$code_membre);
        if($query->num_rows()>0){
            return true;
        }else{
            return false;
        }
    }

    public function getInfosActivationHyperviseur(){
        $query = $this->db->query("SELECT networks_agents.phone, networks_agents.validation_code, agents.number_super,agents.number_geoBysuper FROM `agents` INNER JOIN networks_agents ON networks_agents.agent_id=agents.id INNER JOIN codeGenerer ON codeGenerer.id=networks_agents.codeGenerer_id WHERE codeGenerer.category='hyper' AND agents.number_geoBysuper IS NULL AND agents.number_super IS NULL ");
        return $query->num_rows() > 0 ? $query : false;
    }

    public function getCodeMembreHyper($network_id){
        $query = $this->db->query("SELECT codeGenerer.code_membre FROM `networks_agents` INNER JOIN networks ON networks_agents.network_id=networks.id INNER JOIN codeGenerer ON codeGenerer.id=networks_agents.codeGenerer_id WHERE networks.id=".$network_id." AND codeGenerer.category='hyper' LIMIT 1 ");
        if($query->num_rows()>0){
            return $query->row()->code_membre;
        }else{
            return false;
        }
    }

    public  function getMostOldDateCreationAgent(){
        $query = $this->db->query("SELECT `date_created` FROM `agents` ORDER BY `date_created` LIMIT 1 ");
        if($query->num_rows()>0){
            return $query->row()->date_created;
        }else{
            return false;
        }
    }

    public function contact_incorrect(){
        $query = $this->db->query("SELECT count(*) AS c FROM `networks_agents` 
                                    INNER JOIN codeGenerer ON codeGenerer.id=networks_agents.codeGenerer_id 
                                    INNER JOIN networks ON networks.id=networks_agents.network_id 
                                    INNER JOIN countries ON countries.id=networks.country_id 
                                      WHERE codeGenerer.category='geolocated' AND countries.id=78 AND networks_agents.phone LIKE '+241+241%' OR networks_agents.phone LIKE '+2410000%'");
        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return false;
        }
    }

    public function getPhysicalPointBySupervisor($debut,$fin,$agent){
        $query = $this->db->query("SELECT COUNT(DISTINCT agents.id) AS c FROM `agents` 
                                    INNER JOIN `networks_agents` ON agents.id=networks_agents.agent_id
                                    INNER JOIN codeGenerer ON codeGenerer.id=networks_agents.codeGenerer_id
                                    WHERE  agents.date_created>= '".$debut."' AND agents.date_created<='".$fin."' 
                                           AND codeGenerer.code_parrain IN
                                           (SELECT code_membre FROM codeGenerer WHERE category='super' AND 
                                                  id IN (SELECT codeGenerer_id FROM networks_agents WHERE 
                                                       agent_id IN (SELECT id FROM agents WHERE lastname='".$agent."')))");
        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return false;
        }
    }

    public function getPointGeolocalisedByNetwork($id_network,$debut,$fin){
        $query = $this->db->query("SELECT COUNT(codeGenerer.id) AS c FROM `codeGenerer` 
                                      INNER JOIN networks_agents ON networks_agents.codeGenerer_id=codeGenerer.id
                                      INNER JOIN agents ON agents.id=networks_agents.agent_id
                                      WHERE agents.latitude!=-1 AND agents.longitude!=-1 AND codeGenerer.category='geolocated' AND date_creation>= '".$debut."' AND date_creation<='".$fin."' AND networks_agents.network_id='".$id_network."'
                                   ");
        if($query->num_rows()>0){
            return $query->row()->c;
        }else{
            return 0;
        }
    }

    public function getAllpositionsForWorld(){
        $this->db->select('latitude, longitude ,lastname');
        $this->db->from('agents');
        $query=$this->db->get();
        return $query;
    }

    public function getAgentNetwork($agent_name){
        $query = $this->db->query("SELECT countries.id AS id FROM `agents` 
                                      INNER JOIN towns ON agents.town_id=towns.id 
                                      INNER JOIN countries ON towns.country_id=countries.id 
                                      WHERE agents.lastname='".$agent_name."' LIMIT 1 
                                   ");
        if($query->num_rows()>0){
            return $query->row()->id;
        }else{
            return 0;
        }
    }

    public function getSuperNameAndCodeForHyp($codeHyp){

        $query = $this->db->query("SELECT child.lastname AS lastname, child.code_membre AS member_code, child.agent_id
                                    FROM super_infos AS child 
                                    INNER JOIN hyper_infos AS dad
                                            ON child.code_parrain='".$codeHyp."'
                                    WHERE child.category='super' AND dad.category='hyper' AND dad.code_membre='" . $codeHyp . "'
                                  ");
		return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getDemandesBySuper($debut, $fin, $code_parrain)
	{

		$query = $this->db->query("SELECT *
                                    FROM info_demandeCredits AS d
                                    WHERE d.codeParrain='" . $code_parrain . "'  AND d.dateAjout BETWEEN '" . $debut . "' AND '" . $fin . "'
                                    ORDER BY dateAjout");
		return ($query->num_rows() > 0) ? $query :  false;
	}

    public function getGameCountry(){
        $query = $this->db->query("SELECT countries.id,countries.name
        FROM configGame
        INNER JOIN countries ON configGame.id_pays=countries.id
        WHERE configGame.etat=1
        GROUP BY countries.id");

		return ($query->num_rows() > 0) ? $query :  false;
    }

//    public function getCoutForQuota($pays,$quota_inf,$quota_sup){
//
//        $query = $this->db->query("SELECT COUNT(*) AS c FROM (SELECT * FROM game WHERE `id_pays`=".$pays." GROUP BY `id_parrain` HAVING COUNT(*) >= ".$quota_inf." AND COUNT(*) < ".$quota_sup." ) AS t");
//
//        if($query->num_rows()>0){
//            return $query->row()->c;
//        }else{
//            return false;
//        }
//    }
//
//    public function getMembers($pays,$minQuota){
//        $query = $this->db->query("SELECT t.lastname,t.phone,t.email,t.total
//                                   FROM (SELECT users.lastname,users.phone,users.email,COUNT(*) AS total FROM game
//                                   INNER JOIN users ON game.id_parrain=users.id
//                                   WHERE `id_pays`=".$pays." GROUP BY `id_parrain` HAVING COUNT(*) >= $minQuota) AS t");
//		return ($query->num_rows() > 0) ? $query :  false;
//    }

	public function getCoutForQuota($pays,$quota_inf,$quota_sup){

		$query = $this->db->query("SELECT COUNT(*) AS c FROM (SELECT * FROM agents_game WHERE `id_pays`=".$pays." GROUP BY `id_parrain` HAVING COUNT(*) >= ".$quota_inf." AND COUNT(*) < ".$quota_sup." ) AS t");

		if($query->num_rows()>0){
			return $query->row()->c;
		}else{
			return false;
		}
	}
	public function getMembers($pays,$minQuota){
		$query = $this->db->query("SELECT t.lastname,t.phone,t.email,t.total
                                   FROM (SELECT ag.lastname, ag.phone, ag.email,COUNT(*) AS total FROM agents_game g
                                   INNER JOIN agent_plus ag ON g.id_parrain = ag.id
                                   WHERE `id_pays`=".$pays." GROUP BY `id_parrain` HAVING COUNT(*) >= $minQuota) AS t");
		return ($query->num_rows() > 0) ? $query :  false;
	}

    public function test($pays,$hyper,$ville){

        $query = $this->db->query("SELECT child.agent_id AS id,child.adresse AS adresse,child.category AS childcat,child.lastname AS lastname,
                                           child.etat AS active, child.code_parrain AS code_parrain,child.code_membre AS member_code,
                                           child.network AS network, child.phone AS phone, child.email AS email,dad.adresse AS supadresse,
                                           dad.lastname AS suplastname, dad.code_membre AS sup_code_membre,dad.code_parrain AS sup_code_parrain,
                                           dad.network AS sup_network, dad.category AS dadcat
                                    FROM super_infos AS child
                                      INNER JOIN super_infos AS dad
                                        ON child.code_parrain=dad.code_membre
                                    WHERE child.country_id='".$pays."'
                                          ORDER BY child.agent_id DESC ");

        return $query->num_rows() > 0 ? $query : false;
    }

    public function checkCountryGameExist($pays){
        $query = $this->db->query("SELECT *
                                   FROM configGame
                                   WHERE `id_pays`=".$pays);
        if($query->num_rows()>0){
            return true;
        }else{
            return false;
        }
    }

    public function activeGameOnCountry($pays,$etat){
        $query = $this->db->query("UPDATE configGame SET etat = ".$etat." WHERE id_pays =".$pays);
        return $query;
    }

    public function addContryToGame($pays){
        $query = $this->db->query("INSERT INTO configGame(id_pays) VALUE (".$pays.")");
        //
        return $query;
    }
    public function getPaliers(){
        $query = $this->db->query("SELECT *
                                   FROM paliers");
        return $query->num_rows() > 0 ? $query : false;
    }
    public function modifPalier($value,$niveau){
        $query = $this->db->query("UPDATE paliers SET valeur = ".$value." WHERE id =".$niveau);
        return $query;
    }
    public function getQuota($id){
        $query = $this->db->query("SELECT valeur FROM paliers WHERE id=".$id);
        if($query->num_rows()>0){
            return $query->row()->valeur;
        }else{
            return false;
        }
    }
    public function getNameCountry($id){
        $query = $this->db->query("SELECT name FROM countries WHERE id=".$id);
        if($query->num_rows()>0){
            return $query->row()->name;
        }else{
            return false;
        }
    }
    public function getTownId($town_name){
        $query = $this->db->query("SELECT id FROM towns WHERE `name`='".$town_name."'");
        if($query->num_rows()>0){
            return $query->row()->id;
        }else{
            return null;
        }
    }
    public function checkPosition($lat,$lng){
        $query = $this->db->query("SELECT id FROM agents WHERE `latitude`=".$lat." AND `longitude` =".$lng);
        if($query->num_rows()>0){
            return true;
        }else{
            return false;
        }
    }
    public function create_town($country_id,$name){
        $query = $this->db->query("INSERT INTO towns (`country_id`, `name`, `status`) VALUES (".$country_id.", '".$name."', 1)");
        return $query;
    }
    public function update_town_agent($lat,$lng,$town_id){
        $query = $this->db->query("UPDATE agents SET `town_id` = ".$town_id." WHERE `latitude`= ".$lat." AND `longitude`=".$lng);
        return $query;

    }

    //wallet
    public  function getActiveNetwork(){
        $query = $this->db->query("SELECT networks.id,networks.name,countries.name AS country
                                        FROM networks
                                        INNER JOIN countries ON networks.country_id=countries.id
                                        WHERE `status`=1");
        if($query->num_rows()>0){
            return $query;
        }else{
            return null;
        }
    }
    public function getTaux($id_network){
        $query = $this->db->query("SELECT *
                                        FROM configWallet
                                        WHERE `id_network`=".$id_network);
        if($query->num_rows()>0){
            return $query;
        }else{
            return null;
        }
    }

    public function getNetworkDetails($id_network){
        $query = $this->db->query("SELECT n.name AS network , c.name AS country , c.currency_name_fr , c.currency_code , c.currency_name_en FROM networks n INNER JOIN countries_currencies c ON n.country_id = c.id WHERE n.id = ".$id_network);
        if($query->num_rows()>0){
            return $query;
        }else{
            return null;
        }
    }

    public function getTransactions($debut ,  $fin , $id_network){
		$chain = $debut ?  " AND date_created BETWEEN '".$debut."' AND '".$fin."'" : "";
        $query = $this->db->query("SELECT *
                                    FROM infos_transaction
                                    WHERE `network_id`=".$id_network.$chain);
        return $query->num_rows() > 0 ? $query : false;
    }

	public function getDeletedTransactions($debut ,  $fin , $id_network){
		$chain = $debut ?  " AND deleted_at BETWEEN '".$debut."' AND '".$fin."'" : "";
		$query = $this->db->query("SELECT *
                                    FROM infos_transaction
                                    WHERE deleted = 1 AND  `network_id`=".$id_network.$chain);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getTransactionsSup($debut ,  $fin , $codeMembre){
		$chain = $debut ?  " AND date_created BETWEEN '".$debut."' AND '".$fin."'" : "";
		$query = $this->db->query("SELECT *
                                    FROM infos_transaction
                                    WHERE `codeParrain`='".$codeMembre."'".$chain);
	return ($query->num_rows() > 0) ? $query :  false;
	}

    public function getInfosWalletAgentForHyper($id_network){
        $query = $this->db->query("SELECT *
                                    FROM wallet_agent
                                    WHERE `network_id`=".$id_network);
        return $query->num_rows() > 0 ? $query : false;
    }

	/**
	 * @param $where_clause
	 * @return bool
	 */
	public function get_user($where_clause){
		$query = $this->db->query("SELECT agents.lastname, agents.adresse,agents.email,agents.date_created,agents.id AS userID,
                                          codeGenerer.category,agents.id, agents.qr_code,'agent' as type,
                                          networks.name AS network_name,towns.name AS town_name,
                                          codeGenerer.code_parrain AS parrain,codeGenerer.code_membre AS code,
                                          networks_agents.id AS networkAgent_id,networks_agents.phone,networks_agents.transactionNumber AS transac
                                          FROM agents
                                    INNER JOIN networks_agents ON agents.id=networks_agents.agent_id
                                    INNER JOIN codeGenerer ON codeGenerer.id=networks_agents.codeGenerer_id
                                    INNER JOIN networks ON networks.id =networks_agents.network_id
                                    INNER JOIN towns ON towns.id=agents.town_id
                                    ".$where_clause);
		$statement = "SELECT agents.lastname, agents.adresse,agents.email,agents.date_created,agents.id AS userID,
        codeGenerer.category,agents.id, agents.qr_code,'agent' as type,
        networks.name AS network_name,towns.name AS town_name,
        codeGenerer.code_parrain AS parrain,codeGenerer.code_membre AS code,
        networks_agents.id AS networkAgent_id,networks_agents.phone,networks_agents.transactionNumber AS transac
        FROM agents
  INNER JOIN networks_agents ON agents.id=networks_agents.agent_id
  INNER JOIN codeGenerer ON codeGenerer.id=networks_agents.codeGenerer_id
  INNER JOIN networks ON networks.id =networks_agents.network_id
  INNER JOIN towns ON towns.id=agents.town_id
        ".$where_clause;
		//var_dump($statement);
	return ($query->num_rows() > 0) ? $query :  false;
	}

	/**
	 * @param $phone
	 * @param $name
	 * @param Pays $country
	 * @return |null |null
	 */
	public function get_simple_user($phone, $name , $country = null){
		$end_query = $country ? "AND countries.name = '".$country."'" : '';
		$query = $this->db->query("SELECT users.id AS id_user,users.active AS etat,users.lastname,users.phone,users.email,users.adresse,users.date_created,users.id , users.qr_code, 'user' as type,
                                          networks.name AS network,countries.name AS country,i.firstname as id_firstname , i.lastname as id_lastname , i.birth_date , i.gender, i.town as id_town , i.country as id_country,
                                          i.identity_document , i.id_identity_document ,i.expiry_date_document , i.status, i.user_image , i.document_image_back , i.document_image_front 
                                   FROM users
                                   INNER JOIN networks ON networks.id=users.network_id
                                   INNER JOIN countries ON countries.id=networks.country_id LEFT JOIN identifications i ON i.id_user = users.id
                                   WHERE users.phone LIKE '".$phone."%' AND users.lastname LIKE '".$name."%'".$end_query);

		if($query->num_rows()>0){
			return $query;
		}else{
			return null;
		}
	}

	/**
	 * @param $nom
	 * @param $adresse
	 * @param $email
	 * @param $phone
	 * @param int $id
	 * @return mixed
	 */
	public function update_user_infos($nom, $adresse, $email, $phone, $id){
		$this->db->where('id', $id);
		return $this->db->update('users', ['lastname' => $nom,'phone' => $phone , 'email' => $email , 'adresse' => $adresse]);
	}

	/**
	 * @param $nom
	 * @param $adresse
	 * @param $email
	 * @param int $id_agent
	 * @param $transac
	 * @param $phone
	 * @param int $id_netAg
	 * @return bool
	 */
	public function update_geolocated_infos($nom, $adresse, $email, $id_agent, $transac, $phone, $id_netAg){
		$this->db->trans_begin();

		$this->db->where('id', $id_agent);
		$this->db->update('agents', ['lastname' => $nom, 'email' => $email , 'adresse' => $adresse]);
		$this->db->where('id', $id_netAg);
		$this->db->update('networks_agents', ['phone' => $phone, 'transactionNumber' => $transac]);

		$this->db->trans_complete();
		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			return false;
		} else {
			$this->db->trans_commit();
			return true;
		}
	}


	/**
	 * @return bool
	 */
	public function getPubCountries(){
		$query = $this->db->query("SELECT countries.id AS id_country,countries.name AS pays,publiciteConfig.id,publiciteConfig.date_update AS maj ,publiciteConfig.partenariat,publiciteConfig.valeur_bool AS etat 
                                    FROM countries
                                    INNER JOIN towns ON countries.id = towns.country_id
                                    LEFT JOIN publiciteConfig ON countries.id=publiciteConfig.id_country AND publiciteConfig.id_config=2
                                    WHERE towns.status=1 
                                    GROUP BY countries.id");
	return ($query->num_rows() > 0) ? $query :  false;
	}

	/**
	 * Met a jour l'etat de la publicite
	 * @param int $id ID de la configuration
	 * @param $newState Nouvel etat
	 * @return mixed
	 */
	public function updateStatePub($id, $newState){
		$query = $this->db->query("UPDATE publiciteConfig SET date_update = NOW(),valeur_bool = ".$newState." WHERE id =".$id);
		return $query;
	}

	/**
	 * Ajoute une nouvelle ligne de publicite
	 * @param int $id_country ID du pays
	 * @return mixed
	 */
	public function createPubRow($id_country){
		$query = $this->db->query("INSERT INTO publiciteConfig(id_config,id_country, valeur_bool) VALUE (2,".$id_country.",1)");
		return $query;
	}

	public function getSuperNameAndCodeForSup($codeSup){

		$query = $this->db->query("SELECT child.lastname AS lastname, child.code_membre AS member_code
                                    FROM super_infos AS child 
                                    INNER JOIN super_infos AS dad
                                            ON child.code_parrain='".$codeSup."'
                                    WHERE child.category='geolocated' AND dad.category='super' AND dad.code_membre='".$codeSup."'
                                  ");

	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function nameOfCurrentGeolocatedUser_forSuper($geolocatedUser_memberCode){
		$query = $this->db->query("SELECT lastname FROM `super_infos` WHERE `code_membre`='".$geolocatedUser_memberCode."' ");
		if($query->num_rows()>0){
			return  $query->row()->lastname;
		}else{
			return null;
		}
	}

	// Wallet

	public function getAllActivatedNetworks(){
		$query = $this->db->query("SELECT networks.name AS network,networks.status AS status,networks.id,countries.name AS country,networks.country_id , configWallet.id_network , configWallet.type FROM `networks`
 												INNER JOIN countries ON networks.country_id=countries.id LEFT JOIN configWallet ON configWallet.id_network = networks.id WHERE status = 1");
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function addConfigWallet($network_id , $type){
		$sql='INSERT INTO `configWallet` (`id_network`, `type`) VALUES (?,?);' ;
		$query = $this->db->query($sql , array($network_id, $type));
		return $query;
	}

	public function updateConfigWallet($network_id , $taux_client_r , $taux_client_d,  $taux_ag_r , $taux_ag_d ,  $taux_sup_r , $taux_sup_d , $taux_bq_r , $taux_bq_d , $frais_d ){
		$sql= 'UPDATE `configWallet` SET  `taux_com_client_retrait` = ?, `taux_com_client_depot` = ?, `taux_com_ag_retrait` = ?, `taux_com_ag_depot` = ?, `taux_com_sup_retrait` = ? , `taux_com_sup_depot` =  ?,  `part_banque_retrait` = ?, `part_banque_depot` = ?, `frais_min_banque_depot` = ? WHERE (`id_network` = ?);';
		$query = $this->db->query($sql , array($taux_client_r,$taux_client_d,$taux_ag_r,$taux_ag_d,$taux_sup_r,$taux_sup_d, $taux_bq_r , $taux_bq_d , $frais_d , $network_id));
		return $query;
	}

	public function deleteConfigWallet($network_id){
		$query = $this->db->query("DELETE FROM `configWallet` WHERE `configWallet`.`id_network` = '".$network_id."'");
		return $query;
	}

	public function getWallet($id_agent){
		$sql = "SELECT *  FROM `wallet_agent` WHERE agent_id = ?";
		$query = $this->db->query($sql , array($id_agent));
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function addWallet($id_agent){

		$sql = "SELECT *  FROM `networks_agents` WHERE agent_id = ?";
		$query = $this->db->query($sql , array($id_agent));
		if($query->num_rows()>0){
			$id_networkAgent = $query->first_row()->id;
			$sql = "INSERT INTO `wallets` (`id_networkAgent`) VALUES (?);";
			$query = $this->db->query($sql , array($id_networkAgent));
			return $query;
		}else{
			return false;
		}

	}

	public function getAgentTransactions($id_wallet){
		$query = $this->db->query("SELECT *
                                    FROM wallet_transaction
                                    WHERE `id_wallet`= '".$id_wallet."'");
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getAgentiLinkTransactions($id_wallet){
		$query = $this->db->query("SELECT *
                                    FROM infos_ilink_transaction
                                    WHERE `id_wallet_ag`= '".$id_wallet."'");
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getNetworkHyper($id_network){
		$sql = "SELECT *  FROM `hyper_infos` WHERE network_id = ?";
		$query = $this->db->query($sql , array($id_network));
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getAllAgentsForNetwork($id_network){
		$sql = "SELECT * FROM super_infos WHERE network_id = ?";
		$query = $this->db->query($sql , array($id_network));
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function reinitializeWallet($id_wallet){
		$sql = "UPDATE `wallets` SET `balance_princ` = '0', `balance_com` = '0', `created_date` = ? WHERE (`id` = ?)";
		$query = $this->db->query($sql , array(new DateTime(),$id_wallet));
		return $query;
	}

	// Mot de passe du wallet
	public function getAllActivatedWalletNetworks(){
		$query = $this->db->query("SELECT n.id AS id_network , n.name AS network,n.status AS status,c.name AS country,c.currency_name_fr, c.currency_name_en , c.currency_code, wp.id AS wallet_password FROM networks n
 												INNER JOIN countries_currencies c ON n.country_id=c.id INNER JOIN configWallet cw ON cw.id_network = n.id
                                                LEFT JOIN walletsPassword wp ON wp.network_id = n.id WHERE status = 1;");
	return ($query->num_rows() > 0) ? $query :  false;
	}


	//Liste des pays dont un wallet est actif
	public function getWalletsCountries(){
		$sql= "SELECT id , name , currency_code FROM countries_currencies WHERE id IN (
					 SELECT distinct c.id FROM networks n INNER JOIN countries_currencies c ON n.country_id=c.id INNER JOIN configWallet cw ON cw.id_network = n.id WHERE status = 1
					);";
		$query = $this->db->query($sql);
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getActiveCountries(){
		$sql= "SELECT id , name FROM countries WHERE id IN (
					 SELECT distinct n.country_id FROM networks n WHERE n.status = 1
					);";
		$query = $this->db->query($sql);
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getCountry($id){
		$sql= "SELECT name FROM countries WHERE id = $id";
		$query = $this->db->query($sql);
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function cancelCreditRequest($id_demand){
		$sql = "SELECT *  FROM `info_demandeCredits` WHERE `demande_id` =  ?;";
		$query = $this->db->query($sql , array($id_demand));
		if($query->num_rows()>0){
			$demand = $query->first_row();
			$sql = "SELECT *  FROM `wallet_agent` WHERE `codeMembre` =  ?;";
			$query = $this->db->query($sql , array($demand->codeMembre));
			$query2 = $this->db->query($sql , array($demand->codeParrain));
			$result = $query->num_rows()>0;
			if($result){
				$result =$query2->num_rows()>0;
				if($result){
					$sql = "UPDATE wallets SET balance_princ = ? WHERE (`id` =  ?);";
					$montant = $demand->montant;
					$montantAgent = $query->first_row()->balance_princ - $montant;
					$montantParrain = $query2->first_row()->balance_princ + $montant;

					$this->db->query($sql , array($montantAgent , $query->first_row()->wallet_id ));
					$this->db->query($sql , array($montantParrain , $query2->first_row()->wallet_id));

					$sql = "UPDATE `demandeCredits` SET `status` = '2' WHERE (`id` = ?);";
					$this->db->query($sql , array($demand->demande_id));
					return true;
				}
			}
			return false;
		}else{
			return false;
		}
	}

	public function insertSimulateur($frais , $montant ,$code , $montant_init){
		$sql = "INSERT INTO `simulateur` (`com_hyp` , `montant_retrait`, `code` ,`montant` ) VALUES ( ?, ?, ? , ?);";
		$query = $this->db->query($sql , array($frais,$montant,$code,$montant_init));
		return $query;
	}

	public function getSimulateur($code){
		$sql = "SELECT *  FROM `simulateur` WHERE `code` =  ?;";
		$query = $this->db->query($sql , array($code));
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function setSharingRate($network_id,$config_id,$rate, $url){
		$sql = "SELECT *  FROM `paying_networks` WHERE `id_network` =  ? AND id_configWallet = ? ;";
		$query = $this->db->query($sql , array($network_id,$config_id));
		if($query->num_rows()>0){
			$sql = "UPDATE `paying_networks` SET `taux_partage` =  ? ,`url` =  ? WHERE `id_network` =  ? AND id_configWallet = ? ;";
			$this->db->query($sql , array($rate, $url, $network_id,$config_id));
		}else{
			$sql = "INSERT INTO `paying_networks` (`id_network`, `taux_partage`, `url`, `id_configWallet`) VALUES ( ?, ?, ? ,?); ;";
			$this->db->query($sql , array($network_id,$rate,$url,$config_id));
		}
		return true;
	}

	public function getSharingRate($id_network ,$idConfig){
		$sql = "SELECT taux_partage , url FROM `paying_networks` WHERE `id_network` =  ? AND id_configWallet = ? ;";
		$query = $this->db->query($sql , array($id_network,$idConfig));
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getSharingRateByNetwork($id_network){
		$sql = "SELECT balance_com FROM `paying_networks` WHERE `id_network` =  ? ;";
		$query = $this->db->query($sql , array($id_network));
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function countPayingNetworks($id_country ,$idConfig){
		$sql = "SELECT count(id) as total FROM `paying_networks` WHERE `id_network` IN (SELECT distinct n.id  FROM countries c INNER JOIN
					  networks n ON n.country_id = c.id WHERE  n.status = 1 AND c.id = ?
					) AND id_configWallet = ? ;";
		$query = $this->db->query($sql , array($id_country, $idConfig));
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getActiveNetworksByCountry($country_id , $network_id){
		$query = $this->db->query("SELECT networks.name , networks.id , configWallet.type FROM `networks` INNER JOIN countries ON networks.country_id=countries.id 
									INNER JOIN configWallet ON configWallet.id_network = networks.id WHERE status = 1 AND networks.id <> $network_id AND countries.id = $country_id");
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getPayingNetworksByConfigWallet($id_config)
	{
		$query = $this->db->query("SELECT n.name , n.id , cw.type , c.name as country ,c.currency_code, pw.taux_partage as rate , pw.balance_com , pw.balance_compensation, pw.id_configWallet as config_id FROM networks n INNER JOIN countries_currencies c ON n.country_id=c.id 
				INNER JOIN configWallet cw ON cw.id_network = n.id INNER JOIN paying_networks pw ON pw.id_network = n.id WHERE pw.id_configWallet = $id_config ");
		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}
	}

	public function getIlinkTransactions($debut ,  $fin , $id_network){
		$chain = $debut ? " AND date BETWEEN '" . $debut . "' AND '" . $fin . "'" : "";
		$query = $this->db->query("SELECT *
                                    FROM infos_ilink_transaction
                                    WHERE `network_emetteur`=" . $id_network . $chain);
		//var_dump($query->result_array());
		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}
	}

	public function getNetworkIlinTransactions($id_network){
		$query = $this->db->query("SELECT *
                                    FROM infos_ilink_transaction
                                    WHERE `network_emetteur`= '".$id_network."'");
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getCurrency($id_network){
		$query = $this->db->query("SELECT cc.currency_code as code FROM networks n INNER JOIN countries_currencies cc ON cc.id = n.country_id
                                    WHERE n.id = '".$id_network."'");
		if($query->num_rows()>0){
			return $query->first_row();
		}else{
			return false;
		}
	}

	public function getCommissionTransfers($debut ,  $fin , $codeMembre){
		$chain = $debut ?  " AND date BETWEEN '".$debut."' AND '".$fin."'" : "";
		$query = $this->db->query("SELECT *
                                    FROM infos_transferts_commission
                                    WHERE `codeParrain`='".$codeMembre."'".$chain);
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getIlinkTransactionsSup($debut ,  $fin , $codeMembre){
		$chain = $debut ?  " AND date BETWEEN '".$debut."' AND '".$fin."'" : "";
		$query = $this->db->query("SELECT *
                                    FROM infos_ilink_transaction
                                    WHERE `code_parrain`='".$codeMembre."'".$chain);
	return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getInfosWalletAgentForSuper($codeMembre)
	{
		$query = $this->db->query("SELECT *
                                    FROM wallet_agent
                                    WHERE `codeParrain`='" . $codeMembre . "'");
		return ($query->num_rows() > 0) ? $query :  false;
	}

	public function insertRembourssementCompensation($montant, $id_network, $id_config)
	{
		$sql = "SELECT *  FROM `paying_networks` WHERE `id_network` =  ? AND id_configWallet = ? ;";
		$query = $this->db->query($sql, array($id_network, $id_config));
		if ($query->num_rows() > 0) {
			$montant_init = $query->first_row()->balance_compensation;
			if (($montant_init - $montant) < 0)
				return false;
			$sql = "UPDATE `paying_networks` SET balance_compensation = ? WHERE `id_network` =  ? AND id_configWallet = ?;";
			$this->db->query($sql, array($montant_init - $montant, $id_network, $id_config));
			$sql = "INSERT INTO `remboursemment_compensation` (`montant` , `montant_restant`,`id_paying_network` , `id_network`) VALUES ( ?, ?, ? ,?);";
			$this->db->query($sql, array($montant, $montant_init - $montant, $id_network, $this->session->userdata('network_id')));
			return true;
		}
		return false;
	}

	public function getRefunds($debut, $fin, $id_network)
	{
		$chain = $debut ? " AND date BETWEEN '" . $debut . "' AND '" . $fin . "'" : "";
		$query = $this->db->query("SELECT rp.* , n.name as network , cc.name as country , cc.currency_code FROM remboursemment_compensation rp 
				INNER JOIN networks n ON n.id = id_paying_network INNER JOIN countries_currencies cc ON cc.id = n.country_id 
				WHERE rp.id_network =" . $id_network . $chain);
		return ($query->num_rows() > 0) ? $query :  false;
	}

	// Nano credit
	public function insertCreditLimit($limit_min, $limit_max, $has_nano_credit, $id_network)
	{
		$sql = "UPDATE `configWallet` SET `has_nano_credit` = ?, `limite_credit_min` = ? , `limite_credit_max` = ? WHERE (`id_network` = ? );";
		return $this->db->query($sql, array($has_nano_credit, $limit_min, $limit_max, $id_network));
	}

	public function insertNanoCreditSharedRates($taux_ag, $taux_sup, $taux_hyp, $id_network)
	{
		$sql = "UPDATE `configWallet` SET `taux_com_ag_nano_credit` = ?, `taux_com_sup_nano_credit` = ? , `taux_com_hyp_nano_credit` = ? WHERE (`id_network` = ? );";
		return $this->db->query($sql, array($taux_ag, $taux_sup, $taux_hyp, $id_network));
	}

	public function getAllIlinkWorldNetworks()
	{
		$query = $this->db->query("SELECT networks.name AS network,networks.status AS status,networks.id,cc.name AS country,networks.country_id , configWallet.id_network , configWallet.type,cc.currency_code,
 			 configWallet.limite_credit_min , configWallet.limite_credit_max , configWallet.has_nano_credit  FROM `networks`
 												INNER JOIN countries_currencies cc ON networks.country_id=cc.id LEFT JOIN configWallet ON configWallet.id_network = networks.id WHERE status = 1 AND configWallet.type = 'ilink'");
		return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getUsersGroups($id_network)
	{
		$query = $this->db->query("SELECT * FROM infos_users_groups WHERE id_network = '" . $id_network . "'");
		return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getNanoCreditRates($idConfig, $type = 'nano_credit')
	{
		$sql = "SELECT *  FROM `paliersConfigNanoCredit` WHERE (`idConfig` = ?  AND `type` = ? );";
		$query = $this->db->query($sql, array($idConfig, $type));
		return ($query->num_rows() > 0) ? $query :  false;
	}

	public function deleteNanoCreditRates($idConfig, $type = 'nano_credit')
	{
		$sql = "DELETE FROM `paliersConfigNanoCredit` WHERE (`idConfig` = ?  AND `type` = ? );";
		$query = $this->db->query($sql, array($idConfig, $type));
		return $query;
	}

	public function addNanoCreditRates($idConfig, $duree, $valeur, $type = 'nano_credit')
	{
		$sql = "INSERT INTO `paliersConfigNanoCredit` (`duree_mois`, `taux`, `idConfig` ,`type`) VALUES (?,?,?,?);";
		$query = $this->db->query($sql, array($duree, $valeur, $idConfig, $type));
		return $query;
	}

	public function getUserDemandesCredit($debut, $fin, $id_network)
	{
		$chain = $debut ? " AND date_creation BETWEEN '" . $debut . "' AND '" . $fin . "'" : "";
		$query = $this->db->query("SELECT *
                                    FROM infos_users_demandes_credits
                                    WHERE `id_network`='" . $id_network . "'" . $chain);
		return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getUsersSavings($debut, $fin, $id_network)
	{
		$chain = $debut ? " AND date_creation BETWEEN '" . $debut . "' AND '" . $fin . "'" : "";
		$query = $this->db->query("SELECT *
                                    FROM infos_users_epargnes
                                    WHERE `id_network`='" . $id_network . "'" . $chain);
		return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getAllCanceledCreditsDemands($debut, $fin, $id_network)
	{

		$query = $this->db->query("SELECT *
                                    FROM info_demandeCredits AS d
                                    WHERE d.id_network='" . $id_network . "'  AND d.cancellation_date BETWEEN '" . $debut . "' AND '" . $fin . "' AND canceled_by_hypervisor = '1'
                                    ORDER BY cancellation_date");
		return ($query->num_rows() > 0) ? $query :  false;
	}

	public function getAdminConfig($config_name ,$valueType = 'int'){
		$query = $this->db->query("SELECT * FROM `adminConfig` WHERE `cle`='".$config_name."' ");
		$chain = empty($valueType) ? '' : '_'.$valueType;
		return$query->num_rows()>0 ? $query->first_row()->{'valeur'.$chain} : false;
	}

	public function insertAdminConfig($config_name, $value , $valueType = 'int'){
		$chain = empty($valueType) ? '' : '_' . $valueType;
		$data = array('valeur' . $chain => $value);
		$this->db->where('cle', $config_name);
		return $this->db->update('adminConfig', $data);
	}

	// Obtenir l'heure en fonction de l'id du reseau
	public function getCurrentTimeByNetworkID($id_network){
		$query = $this->db->query("SELECT code_country FROM countries c INNER JOIN networks n on n.country_id = c.id WHERE n.id = '$id_network'");
		if($query->num_rows() > 0){
			$country= $query->first_row();
			$country_code = isset($country->code_country) ? $country->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');
		}
	}

	public function isAgentPhoneExist($id_network_agent , $phone, $phoneTransaction){
		$query = $this->db->query("SELECT na.phone from networks_agents na WHERE  na.id <> '$id_network_agent' AND (na.phone ='$phone' OR na.transactionNumber ='$phoneTransaction')");
		return $query->num_rows() ;
	}

	public function getAgentInfos($id_agent){
		$query = $this->db->query("SELECT * FROM agents WHERE id ='".$id_agent."'");
		return $query->num_rows()>0 ? $query->first_row() : false;
	}

	function getEnumValues($table, $field)
	{
		$type = $this->db->query( "SHOW COLUMNS FROM {$table} WHERE Field = '{$field}'" )->row( 0 )->Type;
		preg_match("/^enum\(\'(.*)\'\)$/", $type, $matches);
		return explode("','", $matches[1]);
	}

	function getAllRequests(){
		$this->db->select('
			user_bank_accounts.*, 
			customer_account_types.name as type,
			identifications.document_image_front,
			identifications.document_image_back
		');
		
		$this->db->from('user_bank_accounts');
		
		// Jointure type de compte
		$this->db->join('customer_account_types', 'user_bank_accounts.customer_account_type_id = customer_account_types.id', 'left');
		
		// Jointure identifications (Assurez-vous que 'id_user' est bien la clé de liaison dans user_bank_accounts)
		$this->db->join('identifications', 'identifications.id_user = user_bank_accounts.id_user', 'left');
		
		$this->db->order_by('user_bank_accounts.id', 'DESC');

		return $this->db->get()->result();
	}

	 public function updateInfoAgency($id, $data) {
        $this->db->where("id", $id);
        return $this->db->update("user_bank_accounts", $data);
    }

    public function deleteInfoAgency($id) {
        $this->db->where("id", $id);
        return $this->db->delete("user_bank_accounts");
    }

	public function get_account($id) {
		return $this->db->where('id', $id)
						->get('user_bank_accounts')
						->row();
	}

	public function getAllLinksBankAccounts()
	{
		$this->db->select('
			v.id_transaction,
			v.user_code,
			v.iban,
			v.is_verified,
			v.created_at,
			u.firstname,
			u.lastname,
			u.email,
			u.phone,
			op.nom as bank_name,
			opc.adresse as bank_address,
		');
		$this->db->from('users_banking_account_verification v');
		
		$this->db->join('users u', 'u.user_code = v.user_code', 'left');
	
		$this->db->join('operators_countries opc', 'opc.id = v.id_bank_country', 'left');
		$this->db->join('operators op', 'op.id = opc.id_operator', 'left');
		
		$this->db->order_by('v.created_at', 'ASC');
		
		$query = $this->db->get();
		return $query->num_rows() > 0 ? $query->result() : []; // Retourne un tableau d'objets
	}

	public function updateRequestStatus($id, $status) {
		$this->db->where("id", $id);
		return $this->db->update("user_bank_accounts", ['status' => $status, 'reason' => 'En attente d\'activation de compte']);
	}

	/* GESTION DES RATTACHEMENTS */

		public function updateLinkRequest($id, $data) {
			$this->db->where('id_transaction', $id);
			return $this->db->update('users_banking_account_verification', $data);
		}

		// Suppression
		public function deleteLinkRequest($id) {
			$this->db->where('id_transaction', $id);
			return $this->db->delete('users_banking_account_verification');
		}
}
