<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Gestion extends CI_Controller
{

    public function _contruct()
    {
        parent::_contruct();
        $this->load->model('user_model');

    }

    public function index()
    {


        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";
            $this->load->view('login', $data);
        } else {

            $ville = $this->session->userdata('current_ville');
            $hyper = $this->session->userdata('current_hyper');
            $pays = $this->session->userdata('current_pays');

            //wallet
            $data['networks'] = $this->user_model->getActiveNetwork();
            $data['list_villes'] = $this->user_model->getAllVilles();
            $data['pays'] = $this->user_model->getAllPays();
            $data['game_pays'] = $this->user_model->getGameCountry();
            $data['alert'] = "";
            $data['active'] = "villes";

            $this->load->view('header_gestion', $data);
            $this->load->view('gestion_villes');
            $this->load->view('footer');
        }

    }

    public function activer(){
        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $villes = $this->input->post('villes');
                $max = sizeof($villes);
                $number_success = 0;
                for ($i = 0; $i < $max; $i++) {
                    $res = $this->user_model->changeVilleStatut($villes[$i],1);
                    if ($res==true){
                        $number_success++;
                    }
                }
                if($number_success==$max){
                    echo json_encode("completed");
                }else{
                    echo json_encode("error");
                }
            }
        }
    }

    public function update()
    {

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $id_country = $this->input->post('id_country');
                $id_town = $this->input->post('id_town');
                $town = $this->input->post('town');

                $res = $this->user_model->updateVille($id_country,$id_town,$town);

                if($res==true){
                    echo json_encode("completed");
                }else{
                    echo json_encode("error");
                }
            }
        }
    }

    public function activer_desactiver(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $aVilles = $this->input->post('aVilles');
                $maxA = sizeof($aVilles);
                $number_successA = 0;

                $dVilles = $this->input->post('dVilles');
                $maxD = sizeof($dVilles);
                $number_successD = 0;

                $this->db->trans_begin();
                for ($i = 0; $i < $maxD; $i++) {
                    $res = $this->user_model->changeVilleStatut($dVilles[$i],0);
                    if ($res==true){
                        $number_successD++;
                    }
                }
                for ($i = 0; $i < $maxA; $i++) {
                    $res = $this->user_model->changeVilleStatut($aVilles[$i],1);
                    if ($res==true){
                        $number_successA++;
                    }
                }

                if($this->db->trans_status() === FALSE){
                    $this->db->trans_rollback();
                    echo json_encode("error");
                }else{
                    $this->db->trans_commit();
                    echo json_encode("completed");
                }
            }
        }
    }

    public function desactiver()
    {
        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $villes = $this->input->post('villes');
                $max = sizeof($villes);
                $number_success = 0;
                for ($i = 0; $i < $max; $i++) {
                    $res = $this->user_model->changeVilleStatut($villes[$i],0);
                    if ($res==true){
                        $number_success++;
                    }
                }
                if($number_success==$max){
                    echo json_encode("completed");
                }else{
                    echo json_encode("error");
                }
            }
        }
    }

    public function suppress()
    {
        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $villes = $this->input->post('ville');
                $res = $this->user_model->deleteVille($villes);

                if($res=true){
                    echo json_encode("completed");
                }else{
                    echo json_encode("error");
                }
            }
        }
    }

    public function ajout(){
        if ($this->input->post('pays') && $this->input->post('ville')) {

            $ville = $this->input->post('ville');
            $id_pays = $this->input->post('pays');
            $stat = 0;


            $data = array('name' => $ville, 'country_id' => $id_pays, 'status' => $stat);

            $query = $this->db->insert('towns', $data);

            if ($query) {

                $data['alert'] = "ok";
                $data['success'] = "ok";
                $data['message'] = "La ville ".$ville." a bien été ajouté!";
                $data['active'] = "villes";

                $data['list_villes'] = $this->user_model->getAllVilles();
                $data['pays'] = $this->user_model->getAllPays();
                $data['game_pays'] = $this->user_model->getGameCountry();
                //wallet
                $data['networks'] = $this->user_model->getActiveNetwork();

                $this->load->view('header_gestion', $data);
                $this->load->view('gestion_villes');
                $this->load->view('footer');
            } else {

                $data['alert'] = "ok";
                $data['success'] = "error";
                $data['message'] = "Une erreur s'est produite";
                $data['active'] = "villes";
                $data['game_pays'] = $this->user_model->getGameCountry();

                $data['list_villes'] = $this->user_model->getAllVilles();
                $data['pays'] = $this->user_model->getAllPays();
                //wallet
                $data['networks'] = $this->user_model->getActiveNetwork();

                $this->load->view('header_gestion', $data);
                $this->load->view('gestion_villes');
                $this->load->view('footer');
            }

        }
    }

    public function networks(){
        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";
            $this->load->view('login', $data);
        } else {

            $ville = $this->session->userdata('current_ville');
            $hyper = $this->session->userdata('current_hyper');
            $pays = $this->session->userdata('current_pays');

            $data['list_villes'] = $this->user_model->getAllVilles();
            $data['pays'] = $this->user_model->getAllCountries();
            $data['game_pays'] = $this->user_model->getGameCountry();
            $data['alert'] = "";
            $data['active'] = "networks";
            $data['networks'] = $this->user_model->getAllNetworksNames();
            $data['assigned_networks'] = $this->user_model->getAllAssignedNetworks();
            //wallet
            $data['networks'] = $this->user_model->getActiveNetwork();

            $this->load->view('header_gestion', $data);
            $this->load->view('gestion_networks');
            $this->load->view('footer');
        }
    }

    public function creat_network(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $network = $this->input->post('new_network');

                $data = array('name' => $network);

                $query = $this->db->insert('networks', $data);

                if($query){
                    echo json_encode("completed");
                }else{
                    echo json_encode("error");
                }
            }
        }
    }

    public function assignation(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $network = $this->input->post('network');
                $existe = 0;
                $this->db->trans_begin();
                foreach ($_POST['id_country'] AS $country){
                    $res = $this->user_model->checkIfAssignationExiste($country,$network);

                    if($res==false){
                        $data = array('country_id' => $country, 'name' => $network);
                        $this->db->insert('networks', $data);

                    }else{
                        $existe = $existe+1;
                    }

                }
                if($this->db->trans_status() === FALSE){
                    $this->db->trans_rollback();
                    echo json_encode("error");
                }elseif ($existe>0){
                    $this->db->trans_commit();
                    echo json_encode("existe");
                }else{
                    $this->db->trans_commit();
                    echo json_encode("completed");
                }

            }
        }
    }

    public function update_network(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $old_network = $this->input->post('old_name');
                $new_network = $this->input->post('new_network');

                $res = $this->user_model->updateNetwork($old_network,$new_network);

                if($res==true){
                    echo json_encode("completed");
                }else{
                    echo json_encode("error");
                }
            }
        }
    }

    public function change_status_network(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $activations = $this->input->post('activations');
                $desactivation = $this->input->post('desactivations');

                $this->db->trans_begin();
                if(!empty($_POST['activations'])){
                    foreach ($_POST['activations'] AS $network){

                        $data = array('status' => 1);
                        $this->db->where('id', $network);
                        $this->db->update('networks', $data);

                    }
                }
                if(!empty($_POST['desactivations'])){
                    foreach ($_POST['desactivations'] AS $network){

                        $data = array('status' => 0);
                        $this->db->where('id', $network);
                        $this->db->update('networks', $data);

                    }
                }
                if($this->db->trans_status() === FALSE){
                    $this->db->trans_rollback();
                    echo json_encode("error");
                }else{
                    $this->db->trans_commit();
                    echo json_encode("completed");
                }

            }
        }
    }

    public function admin(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";
            $this->load->view('login', $data);
        } else {

            $ville = $this->session->userdata('current_ville');
            $hyper = $this->session->userdata('current_hyper');
            $pays = $this->session->userdata('current_pays');

            $data['list_admin'] = $this->user_model->getAllAdmin();
            $data['list_villes'] = $this->user_model->getAllVilles();
            $data['pays'] = $this->user_model->getAllCountries();
            $data['game_pays'] = $this->user_model->getGameCountry();
            //wallet
            $data['networks'] = $this->user_model->getActiveNetwork();
            $data['alert'] = "";
            $data['active'] = "admin";

            $this->load->view('header_gestion', $data);
            $this->load->view('gestion_admin');
            $this->load->view('footer');
        }

    }

    public function create_admin(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $category = 1;
                $firstname = $this->input->post('prenom');
                $lastname = $this->input->post('nom');
                $email = $this->input->post('email');
                $emailExist = $this->user_model->isEmailExist($email);
                if($emailExist==false){
                    $phone = $this->input->post('contact');
                    $phoneExist = $this->user_model->isPhoneExist($phone);
                    if($phoneExist==false){
                        $adresse = $this->input->post('adresse');
                        $country = $this->input->post('country');
                        $token = null;
                        do {
                            $token = bin2hex(openssl_random_pseudo_bytes(16));
                            $tokenExist = $this->user_model->getToken($token);
                        } while ($tokenExist==true);

                        $data = array('firstname' => $firstname,'lastname' => $lastname,'email' => $email,'phone' => $phone,'adresse' => $adresse,'country' => $country,'category' => $category,'token' => $token);

                        $query = $this->db->insert('admin', $data);

                        if($query){

                            $link = "https://ilink-app.com/backofficebeta/index.php/Admin_password/?token=".$token;
                            $this->load->library('email');

                            $this->email->from('noreply@ilink-app.com', 'iLink World');
                            $this->email->to($email);

                            $this->email->subject($this->lang->line("Confirmation de création d'un compte administrateur"));
                            $this->email->message($firstname.' '.$lastname.' '.$this->lang->line("votre compte administrateur a bien été créé. Veuillez suivre ce lien pour configurer votre mot de passe.").' '.$link);

                            $this->email->send();

                            echo json_encode("completed");
                        }else{
                            echo json_encode($this->lang->line("Une erreur s'est produite"));
                        }
                    }else{
                        echo json_encode($this->lang->line("Le numéro de téléphone entré est déjà utilisé"));
                    }
                }else{
                    echo json_encode($this->lang->line("L'email entré est déjà utilisé"));
                }
            }
        }
    }

    public function modif_admin(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $id = $this->input->post('id');
                $firstname = $this->input->post('prenom');
                $lastname = $this->input->post('nom');
                $email = $this->input->post('email');
                $phone = $this->input->post('contact');
                $adresse = $this->input->post('adresse');
                $country = $this->input->post('country');
                $category = $this->input->post('category');

                $res = $this->user_model->updateAdmin($id,$firstname,$lastname,$email,$phone,$adresse,$country,$category);

                        if($res){
                            echo json_encode("completed");
                        }else{
                            echo json_encode($this->lang->line("Une erreur s'est produite"));
                        }
            }
        }
    }

    public function delete_admin(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $id = $this->input->post('id');

                $res = $this->user_model->deleteAdmin($id);

                if($res){
                    echo json_encode("completed");
                }else{
                    echo json_encode($this->lang->line("Une erreur s'est produite"));
                }
            }
        }
    }

    public function codes(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";
            $this->load->view('login', $data);
        } else {

            $ville = $this->session->userdata('current_ville');
            $hyper = $this->session->userdata('current_hyper');
            $pays = $this->session->userdata('current_pays');

            $data['list_villes'] = $this->user_model->getAllVilles();
            $data['pays'] = $this->user_model->getAllPays();
            $data['game_pays'] = $this->user_model->getGameCountry();
            $data['alert'] = "";
            $data['active'] = "codes-hyper";
            $data['list'] = $this->user_model->getGeneratedHyperCodes();
            //wallet
            $data['networks'] = $this->user_model->getActiveNetwork();

            $this->load->view('header_gestion', $data);
            $this->load->view('codeg');
            $this->load->view('footer');
        }
    }

    public function generateCode()
    {

        if ($this->input->post('c') && $this->input->post('a')) {

            $number = intval($this->input->post('c'));
            $member_code = $this->input->post('a');
            if($number>0){
                for ($i = 0; $i < $number; $i++) {


                    $code = $this->randomString();

                    $data = array('code_parrain' => $member_code, 'code_membre' => $code, 'etat' => 0, 'category' => 'hyper');

                    $query = $this->db->insert('codeGenerer', $data);

                }
            }
            $data['alert'] = "ok";
            $data['success'] = "ok";
            $data['active'] = "members";
            $data['message'] = "$number codes have been added!";


            $ville = $this->session->userdata('current_ville');
            $hyper = $this->session->userdata('current_hyper');
            $pays = $this->session->userdata('current_pays');

            $data['pays'] = $this->user_model->getAllCountries();
            $data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
            $data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
            $data['list'] = $this->user_model->getGeneratedHyperCodes();
            $data['active'] = "codes";
            $data['pays'] = $this->user_model->getAllCountries();
            $data['game_pays'] = $this->user_model->getGameCountry();
            $data['firstname'] = $this->session->userdata('firstname');
            $data['lastname'] = $this->session->userdata('lastname');
            $data['email'] = $this->session->userdata('email');
            //wallet
            $data['networks'] = $this->user_model->getActiveNetwork();
            $this->load->view('header_gestion', $data);
            $this->load->view('codeg');
            $this->load->view('footer');

        } else {
            $data['alert'] = "ok";
            $data['success'] = "";
            $data['active'] = "members";
            $data['message'] = "Can't add codes!";

            $ville = $this->session->userdata('current_ville');
            $hyper = $this->session->userdata('current_hyper');
            $pays = $this->session->userdata('current_pays');

            $data['pays'] = $this->user_model->getAllCountries();
            $data['game_pays'] = $this->user_model->getGameCountry();
            $data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
            $data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
            $data['list'] = $this->user_model->getGeneratedHyperCodes();
            $data['active'] = "codes";
            $data['pays'] = $this->user_model->getAllCountries();
            $data['firstname'] = $this->session->userdata('firstname');
            $data['lastname'] = $this->session->userdata('lastname');
            $data['email'] = $this->session->userdata('email');
            //wallet
            $data['networks'] = $this->user_model->getActiveNetwork();

            $this->load->view('header_gestion', $data);
            $this->load->view('codeg');
            $this->load->view('footer');
        }

    }

    private function randomString($length = 10)
    {
        $str = "";
        $characters = array_merge(range('A', 'Z'), range('a', 'z'), range('0', '9'));
        $max = count($characters) - 1;
        for ($i = 0; $i < $length; $i++) {
            $rand = mt_rand(0, $max);
            $str .= $characters[$rand];
        }
        return $str;

    }

    public function geolocalisation(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";
            $this->load->view('login', $data);
        } else {

            $ville = $this->session->userdata('current_ville');
            $hyper = $this->session->userdata('current_hyper');
            $pays = $this->session->userdata('current_pays');


            $data['pays'] = $this->user_model->getAllCountries();
            $data['game_pays'] = $this->user_model->getGameCountry();
            $data['villes'] = $this->user_model->getVillesByPays($data['pays']->first_row()->id);
            $data['active_ville_name'] = $data['villes']->first_row()->name;
            $data['active_ville_id'] = $data['villes']->first_row()->id;
            $data['agent'] = $this->user_model->getAgentsFromCountry($data['pays']->first_row()->id);
            $data['networks'] = $this->user_model->getNetworks($data['pays']->first_row()->id);
            $data['alert'] = "";
            $data['active'] = "geoloc";
            $number_geolocalisation = array();
            $network_geolocalisation = array();
            $count = 0;

            foreach ($data['networks']->result() AS $row){
                $number_geolocalisation[$count] = $this->user_model->getPointGeolocalised($row->id,$data['agent']->first_row()->lastname);
                $network_geolocalisation[$count] = $row->name;
                $count++;
            }
            $data['current_agent'] = $data['agent']->first_row()->lastname;
            $data["number_geolocalisation"] = $number_geolocalisation;
            $data["network_geolocalisation"] = $network_geolocalisation;
            $data["total"] = $count;
            $data['assigned_networks'] = $this->user_model->getAllAssignedNetworks();
            //wallet
            $data['networks'] = $this->user_model->getActiveNetwork();

            $this->load->view('header_gestion', $data);
            $this->load->view('gestion_geolocalisation');
            $this->load->view('footer');
        }
    }

    public function infos_geolocalisation(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $pays = $this->input->post('pays');
                $ville = $this->input->post('ville');
                $lastname = $this->input->post('agent');


                $data['pays'] = $this->user_model->getAllCountries();
                $data['game_pays'] = $this->user_model->getGameCountry();
                $data['villes'] = $this->user_model->getVillesByPays($data['pays']->first_row()->id);
                $data['active_ville_name'] = $data['villes']->first_row()->name;
                $data['active_ville_id'] = $data['villes']->first_row()->id;
                $data['agent'] = $this->user_model->getAgentsFromCountry($data['pays']->first_row()->id);
                $data['networks'] = $this->user_model->getNetworks($pays);
                $data['alert'] = "";
                $data['active'] = "geoloc";
                $number_geolocalisation = array();
                $network_geolocalisation = array();
                $count = 0;

                foreach ($data['networks']->result() AS $row){
                    $number_geolocalisation[$count] = $this->user_model->getPointGeolocalised($row->id,$lastname);
                    $network_geolocalisation[$count] = $row->name;
                    $count++;
                }
                $data['current_agent'] = $lastname;
                $data["number_geolocalisation"] = $number_geolocalisation;
                $data["network_geolocalisation"] = $network_geolocalisation;
                $data["total"] = $count;
                $data['assigned_networks'] = $this->user_model->getAllAssignedNetworks();
                //wallet
                $data['networks'] = $this->user_model->getActiveNetwork();

                $this->load->view('header_gestion', $data);
                $this->load->view('gestion_geolocalisation');
                $this->load->view('footer');
            }
        }
    }

    public function getVilleByPays(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";


            redirect('index.php', $data);
        }
        else {

            if($this->input->is_ajax_request())
            {
                $ajaxhyp = $this->user_model->getVillesByPays($this->input->post('pays'));
                echo json_encode($ajaxhyp->result_array());
            }

        }
    }

    public function getAgentByVilles(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";


            redirect('index.php', $data);
        }
        else {

            if($this->input->is_ajax_request())
            {
                $ajaxhyp = $this->user_model->getAgentsFromCountry($this->input->post('id_country'));
                echo json_encode($ajaxhyp->result_array());
            }

        }
    }

    public function campagne(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";
            $this->load->view('login', $data);
        } else {

            $ville = $this->session->userdata('current_ville');
            $hyper = $this->session->userdata('current_hyper');
            $pays = $this->session->userdata('current_pays');

            $debut = date('Y-m-d H:i:s',strtotime($this->user_model->getMostOldDateCreationAgent()));
            $fin = date("Y-m-d H:i:s");
            $data['pays'] = $this->user_model->getAllCountries();
            $pays = $data['pays']->first_row()->id;
            if(!empty($_POST))
            {
                $debut = $this->input->post('date-debut');
                $fin = $this->input->post('date-fin');
                $pays = $this->input->post('pays');
            }

            $data['debut'] = $debut;
            $data['fin'] = $fin;
            $data['villes'] = $this->user_model->getVillesByPays($data['pays']->first_row()->id);
            $data['active_ville_name'] = $data['villes']->first_row()->name;
            $data['active_ville_id'] = $data['villes']->first_row()->id;
            $data['agent'] = $this->user_model->getAgentsFromCountry($pays);
            $data['networks'] = $this->user_model->getNetworks($pays);
            $data['alert'] = "";
            $data['active'] = "campagne";
            $agent[][] = null;
            $geo_correct[][] = null;
            $number_geolocalisation [][] = null;
            $network_geolocalisation [][] = null;
            $number_correct [][] = null;
            $count = 0;
            $countA = 0;
            $total = 0;
            $network_count = 0;
            $total_physique = 0;
            $contact_correct = 0;

            $networks_compte[] = null;
            $networks_name[] = null;

            if($data['agent']!=false){
                foreach ($data['agent']->result() AS $row1){
                    if(!strstr($row1->lastname, "Super -") and !strstr($row1->lastname, "Airtel")){
                        $totalGeo = 0;
                        $totalGeoCorrect = 0;
                        $agent[$countA][0] = $row1->lastname;
                        foreach ($data['networks']->result() AS $row2){
                                $number_geolocalisation [$countA][$count] = $this->user_model->getPointGeolocalisedByDate($row2->id,$row1->lastname,$debut,$fin);
                                $number_correct [$countA][$count] = $this->user_model->getCorrectPointGeolocalisedByDate($row2->id,$row1->lastname,$debut,$fin);
                                $network_geolocalisation [$countA][$count] = $row2->name;
                                $totalGeo = $totalGeo + $number_geolocalisation [$countA][$count];
                                $totalGeoCorrect = $totalGeoCorrect + $number_correct [$countA][$count];
                                $count++;
                        }
                        $agent[$countA][1] = $totalGeo;
                        $agent[$countA][2] = $this->user_model->getPhysicalPointBySupervisor($debut,$fin,$row1->lastname);
                        $total_physique = $total_physique + $agent[$countA][2];
                        $geo_correct [$countA][1] = $totalGeoCorrect;
                        $total = $total+$totalGeo;
                        $contact_correct = $contact_correct+$totalGeoCorrect;
                        $countA++;
                    }
                }
            }

            foreach ($data['networks']->result() AS $row){
                $networks_compte[$network_count] = $this->user_model->getPointGeolocalisedByNetwork($row->id,$debut,$fin);
                $networks_name[$network_count] = $row->name;
                $network_count++;
            }
            $data["networks_compte"] = $networks_compte;
            $data["networks_name"] = $networks_name;
            $data["network_count"] = $network_count;
            $data["total_physique"] = $total_physique;
            $data['geo_correct'] = $geo_correct;
            $data['contact_correct']=$total;
            if($pays==78){
                $data['contact_correct']=$contact_correct;
            }
            $data["agents"] = $agent;
            $data["total_points"] = $total;
            $data["countA"] = $countA;
            $data['current_agent'] = $data['agent']->first_row()->lastname;
            $data["number_geolocalisation"] = $number_geolocalisation;
            $data["network_geolocalisation"] = $network_geolocalisation;
            $data["total"] = $count;
            $data['assigned_networks'] = $this->user_model->getAllAssignedNetworks();
            $data['game_pays'] = $this->user_model->getGameCountry();
            //wallet
            $data['networks'] = $this->user_model->getActiveNetwork();

            $this->load->view('header_gestion', $data);
            $this->load->view('gestion_campagne');
            $this->load->view('footer');
        }
    }

    public function redirect_info_agent(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_GET))
            {
                $lastname = $this->input->get('agent');
                $debut = $this->input->get('debut');
                $fin = $this->input->get('fin');
                $id_country = $this->user_model->getAgentNetwork($lastname);

                $data['pays'] = $this->user_model->getAllCountries();
                $data['game_pays'] = $this->user_model->getGameCountry();
                $data['villes'] = $this->user_model->getVillesByPays($data['pays']->first_row()->id);
                $data['active_ville_name'] = $data['villes']->first_row()->name;
                $data['active_ville_id'] = $data['villes']->first_row()->id;
                $data['agent'] = $this->user_model->getAgentsFromCountry($data['pays']->first_row()->id);
                $data['networks'] = $this->user_model->getNetworks($id_country);
                $data['alert'] = "";
                $data['active'] = "geoloc";
                $number_geolocalisation = array();
                $network_geolocalisation = array();
                $count = 0;

                foreach ($data['networks']->result() AS $row){
                    $number_geolocalisation[$count] = $this->user_model->getPointGeolocalisedByDate($row->id,$lastname,$debut,$fin);
                    $network_geolocalisation[$count] = $row->name;
                    $count++;
                }
                $data['current_agent'] = $lastname;
                $data["number_geolocalisation"] = $number_geolocalisation;
                $data["network_geolocalisation"] = $network_geolocalisation;
                $data["total"] = $count;
                $data['assigned_networks'] = $this->user_model->getAllAssignedNetworks();
                //wallet
                $data['networks'] = $this->user_model->getActiveNetwork();

                $this->load->view('header_gestion', $data);
                $this->load->view('gestion_geolocalisation');
                $this->load->view('footer');
            }
        }
    }

    public function map(){
        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";
            $this->load->view('login', $data);
        } else {
            $data['positions'] = $this->user_model->getAllpositionsForWorld();
            $data['latitude'] = 0;
            $data['longitude'] = 0;
            $data['lastname'] = $this->session->userdata('lastname');
            $data['active'] = "map";
            $data['code_parrain'] = $this->session->userdata('code_parrain');
            $data['alert'] = "";
            $this->load->view('header_gestion', $data);
            $this->load->view('gestion_map');
            $this->load->view('footer');
        }
    }

    public function game(){
        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";
            $this->load->view('login', $data);
        } else {
            $pays = 1;
            if(!empty($_POST))
            {
                $pays = $this->input->post('pays');
                $pays_name = $this->user_model->getNameCountry($pays);
                $this->session->set_userdata('current_game_country',$pays);
                $this->session->set_userdata('current_game_country_name',$pays_name);
            }elseif(!empty($this->session->userdata('current_game_country'))){
                $pays = $this->session->userdata('current_game_country');
                $pays_name = $this->session->userdata('current_game_country_name');
            }
            $max = 999999;
            $data['paliers'] = $this->user_model->getPaliers();
            $data['pays'] = $this->user_model->getAllGameCountries();
            $data['list'] = $this->user_model->getMembers($pays);
            $data['game_pays'] = $this->user_model->getGameCountry();
            $data['q1'] = $this->user_model->getQuota(1);
            $data['q2'] = $this->user_model->getQuota(2);
            $data['q3'] = $this->user_model->getQuota(3);
            $data['q4'] = $this->user_model->getQuota(4);
            $data['quota1'] = $this->user_model->getCoutForQuota($pays,$data['q1'],$data['q2']);
            $data['quota2'] = $this->user_model->getCoutForQuota($pays,$data['q2'],$data['q3']);
            $data['quota3'] = $this->user_model->getCoutForQuota($pays,$data['q3'],$data['q4']);
            $data['quota4'] = $this->user_model->getCoutForQuota($pays,$data['q4'],$max);
            $data['lastname'] = $this->session->userdata('lastname');
            $data['active'] = "game";
            $data['code_parrain'] = $this->session->userdata('code_parrain');
            $data['alert'] = "";
            //wallet
            $data['networks'] = $this->user_model->getActiveNetwork();
            $this->load->view('header_gestion',$data);
            $this->load->view('game');
            $this->load->view('footer');
        }
    }

    public function activerGame(){
        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $pays = $this->input->post('pays');
                $max = sizeof($pays);
                $number_success = 0;
                for ($i = 0; $i < $max; $i++) {
                    $checkContryExist = $this->user_model->checkCountryGameExist($pays[$i]);
                    if($checkContryExist==true){
                        $res = $this->user_model->activeGameOnCountry($pays[$i],1);
                    }else{
                        $add = $this->user_model->addContryToGame($pays[$i]);
                        if($add==true){
                            $res = $this->user_model->activeGameOnCountry($pays[$i],1);
                        }else{
                            echo json_encode("error");
                        }
                    }
                    if ($res==true){
                        $number_success++;
                    }
                }
                if($number_success==$max){
                    echo json_encode("completed");
                }else{
                    echo json_encode("error");
                }
            }
        }
    }

    public function desactiverGame(){
        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $pays = $this->input->post('pays');
                $max = sizeof($pays);
                $number_success = 0;
                for ($i = 0; $i < $max; $i++) {
                    $res = $this->user_model->activeGameOnCountry($pays[$i],0);
                    if ($res==true){
                        $number_success++;
                    }
                }
                if($number_success==$max){
                    echo json_encode("completed");
                }else{
                    echo json_encode("error");
                }
            }
        }
    }

    public function activer_desactiverGame(){

        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first !";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $apays = $this->input->post('apays');
                $maxA = sizeof($apays);
                $number_successA = 0;

                $dpays = $this->input->post('dpays');
                $maxD = sizeof($dpays);
                $number_successD = 0;

                $this->db->trans_begin();
                for ($i = 0; $i < $maxD; $i++) {
                    $res = $this->user_model->activeGameOnCountry($dpays[$i],0);
                    if ($res==true){
                        $number_successD++;
                    }
                }
                for ($i = 0; $i < $maxA; $i++) {
                
                    $checkContryExist = $this->user_model->checkCountryGameExist($apays[$i]);
                    if($checkContryExist==true){
                        $res = $this->user_model->activeGameOnCountry($apays[$i],1);
                    }else{
                        $add = $this->user_model->addContryToGame($apays[$i]);
                        if($add==true){
                            $res = $this->user_model->activeGameOnCountry($apays[$i],1);
                        }else{
                            echo json_encode("error");
                        }
                    }
                    if ($res==true){
                        $number_successA++;
                    }
                }

                if($this->db->trans_status() === FALSE){
                    $this->db->trans_rollback();
                    echo json_encode("error");
                }else{
                    $this->db->trans_commit();
                    echo json_encode("completed");
                }
            }
        }
    }

    public function modifierPalier(){
        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first!";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $n1 = $this->input->post('n1');
                $n2 = $this->input->post('n2');
                $n3 = $this->input->post('n3');
                $n4 = $this->input->post('n4');
                $max = 4;
                $number_success = 0;
                
                    $res1 = $this->user_model->modifPalier($n1,1);
                    if ($res1==true){
                        $number_success++;
                        $res2 = $this->user_model->modifPalier($n2,2);
                        if($res2==true){
                            $number_success++;
                            $res3 = $this->user_model->modifPalier($n3,3);
                            if($res3){
                                $number_success++;
                                $res4 = $this->user_model->modifPalier($n4,4);
                                if($res4==true){
                                    $number_success++;
                                }else{
                                    echo json_encode("error");
                                }
                            }else{
                                echo json_encode("error");
                            }
                        }else{
                            echo json_encode("error"); 
                        }
                    }else{
                        echo json_encode("error");
                    }
                
                if($number_success==$max){
                    echo json_encode("completed");
                }else{
                    echo json_encode("error");
                }
            }
        }
    }
    public function change_country(){
        if (!$this->session->userdata('email')) {
            $this->session->set_flashdata('error', 'log in first');

            $data['alert'] = "ok";
            $data['message'] = "Login first !";

            $this->load->view('login', $data);
        } else {

            if(isset($_POST))
            {
                $pays = $this->input->post('pays');
                $pays_name = $this->user_model->getNameCountry($pays);
                if($pays_name!=false){
                    $this->session->set_userdata('current_game_country',$pays);
                    $this->session->set_userdata('current_game_country_name',$pays_name);
                    echo 1;
                }else{
                    echo 0;
                }
            }else{
                echo 0;
            }
        }
    }

    
}
