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

class Admin extends CI_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->load->model('user_model');
		$this->load->model('wallet_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 {
            $this->load->view('admin_vue');
        }
    }

    public function add()
    {
        if ($this->input->post('ad')) {
            $nom = $this->input->post('nm');
            $phon = $this->input->post('password');

            $data = array(
                'nom' => $nom, 'password' => MD5($phon),
            );

            $query = $this->db->insert('admintable', $data);
            if ($query) {
                echo "Ajout Reussie!";
                redirect('Admin');
            } else {
                echo "Echec ";
                redirect('Admin');
            }
        } else {
            echo "error db";
            redirect('Admin');
        }
    }

    public function getAllUser_g(){
        @ini_set('display_errors', 'on');

        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 {

            $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);

            $query = $this->user_model->getGeolocatedUsersForAdmin($pays,$hyper,$ville);


            $position_hyper = $this->user_model->getPositionHyper($hyper);

            $data['positions'] = $this->user_model->adminGetAllpositions($pays,$hyper,$ville);
            $data['active'] = "members";
            $data['map_title'] = $this->lang->line('Utilisateurs géolocalisés');
            $data['tab'] = $query;
            $data['latitude'] = $position_hyper->first_row()->latitude;
            $data['longitude'] = $position_hyper->first_row()->longitude;
            $data['token'] = $this->session->userdata('token');
            $data['email'] = $this->session->userdata('email');
            $data['firstname'] = $this->session->userdata('firstname');
            $data['lastname'] = $this->session->userdata('lastname');
            $data['code_parrain'] = $this->session->userdata('code_parrain');
            $data['phone'] = $this->session->userdata('phone');
            $data['adresse'] = $this->session->userdata('adresse');
            $data['category'] = $this->session->userdata('category');
            $data['network'] = $this->session->userdata('network');
            $data['pays'] = $this->user_model->getAllCountries();
            $data['alert'] = "";
            $this->load->view('header', $data);
            $this->load->view('listeadmin');
            $this->load->view('footer');
        }

    }

    public function getAllDemandes(){

        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');
            $name_ville = $this->db->query("SELECT name FROM towns WHERE id=".$ville)->first_row()->name;
            $name_pays = $this->db->query("SELECT name FROM countries WHERE id=".$pays)->first_row()->name;

            $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);

            $network = 'all';
            $data['active'] = "demandes";
            $data['type'] = 'crédits';
            $data['alert'] = "";
            $data['token'] = $this->session->userdata('token');
            $data['email'] = $this->session->userdata('email');
            $data['firstname'] = $this->session->userdata('firstname');
            $data['lastname'] = $this->session->userdata('lastname');
            $data['code_parrain'] = $this->session->userdata('code_parrain');
            $data['phone'] = $this->session->userdata('phone');
            $data['adresse'] = $this->session->userdata('adresse');
            $data['category'] = $this->session->userdata('category');
            $data['network'] = $this->session->userdata('network');
            $data['list'] = $this->user_model->adminGetDemandes($pays,$hyper,$name_ville);
            $data['tab_fastDemande'] = $this->user_model->adminGetRangeASCDemandes($name_pays,$hyper,$name_ville);
            $data['tab_slowDemande'] = $this->user_model->adminGetRangeDESCDemandes($name_pays,$hyper,$name_ville);
            $data['temp_moyen'] = $this->user_model->adminGetTempsMoyen($name_pays,$hyper,$name_ville);
            $data['pays'] = $this->user_model->getAllCountries();
            $this->load->view('header', $data);
            $this->load->view('demande');
            $this->load->view('footer');
        }
    }

    public function getHypByPays(){

        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->getAllHyper($this->input->post('pays'));
                echo json_encode($ajaxhyp->result_array());
            }

        }
    }

    public function getVilleByHyp(){

        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->getVilleNetworkByHyper($this->input->post('code'));
                echo json_encode($ajaxhyp->result_array());
            }

        }
    }

    public function filtreData(){

        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))
            {

                $this->session->set_userdata('current_pays', $this->input->post('pays'));
                $this->session->set_userdata('current_hyper', $this->input->post('hyper'));
                $this->session->set_userdata('current_ville', $this->input->post('ville'));

                $pays_name = $this->db->query("SELECT name FROM countries WHERE id='".$this->input->post('pays')."'");
                $town_name = $this->db->query("SELECT name FROM towns WHERE id='".$this->input->post('ville')."'");

                $infos_network = $this->db->query("SELECT name,phone FROM networks INNER JOIN networks_agents ON networks.id=networks_agents.network_id INNER JOIN codeGenerer ON networks_agents.codeGenerer_id=codeGenerer.id WHERE codeGenerer.code_membre='".$this->input->post('hyper')."'");
                $network = $infos_network->first_row()->name;
                $contact_hyper = $infos_network->first_row()->phone;
                $this->session->set_userdata('current_network', $network);
                $this->session->set_userdata('current_contact_hyper', $contact_hyper);

                $this->session->set_userdata('name_current_pays',$pays_name->first_row()->name);
                $this->session->set_userdata('name_current_ville',$town_name->first_row()->name);

                redirect('Admin_dash/index');
            }
        }
    }

    public function deleteUser(){

        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))
            {
                $code = $this->input->post('code');
                $cat = $this->input->post('cat');
                $id = $this->user_model->getIdAgentByMemberCode($code,$cat);

                if($id!=false){
                    $delete_infos_agents = $this->user_model->deleteInfosGeolocatedUser($id);
                    if($delete_infos_agents){
                        $delete_code = $this->user_model->deleteCodeAgent($code);
                        if($delete_code){
                            echo json_encode("completed");
                        }else{
                            echo json_encode("Une erreur s'est produite à la mise à jour du numéro de téléphone");
                        }
                    }else{
                        echo json_encode("Une erreur s'est produite lors de la mise à jour des informations");
                    }
                }else{
                    echo json_encode("Une erreur identifiant agent");
                }



                if($res){
                    echo json_encode("completed");
                }else{
                    echo json_encode("Une erreur s'est produite");
                }
            }
        }
    }

    public function updateUser(){

        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))
            {
                $code = $this->input->post('code');
                $cat = $this->input->post('cat');
                $adresse = $this->input->post('adresse');
                $lastname = $this->input->post('nom');
                $email = $this->input->post('email');
                $phone = $this->input->post('contact');
				$provider_class_id = $this->input->post('provider_class_id');
				$network_agent_id = $this->input->post('network_agent_id');

                $id = $this->user_model->getIdAgentByMemberCode($code,$cat);

                if($id!=false){
                    $update_info = $this->user_model->updateGeolocatedUser($id,$adresse,$lastname,$email,$network_agent_id,$provider_class_id);
                    if($update_info){
                        $res = $this->user_model->updatePhoneAgent($id,$phone);
                        if($res){
                            echo json_encode("completed");
                        }else{
                            echo json_encode("Une erreur s'est produite à la mise à jour du numéro de téléphone");
                        }
                    }else{
                        echo json_encode("Une erreur s'est produite lors de la mise à jour des informations");
                    }
                }else{
                    echo json_encode("Une erreur identifiant agent");
                }
            }
        }
    }

    public function getGeolocatedUsersForAdministrator(){
        $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);

        $query = $this->user_model->getGeolocatedUsersForAdmin($pays,$hyper,$ville)->result();

        echo json_encode($query);
    }

    public function pagination_User_g(){

       // @ini_set('display_errors', 'on');

        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 {

            $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);

            $query = $this->user_model->getGeolocatedUsersForAdmin($pays,$hyper,$ville);


            $position_hyper = $this->user_model->getPositionHyper($hyper);


            $data['active'] = "members";
            $data['positions'] = $this->user_model->adminGetAllpositions($pays,$hyper,$ville);
            $data['map_title'] = $this->lang->line('Utilisateurs géolocalisés');
            $data['tab'] = $query;
            $data['latitude'] = $position_hyper->first_row()->latitude;
            $data['longitude'] = $position_hyper->first_row()->longitude;
            $data['token'] = $this->session->userdata('token');
            $data['email'] = $this->session->userdata('email');
            $data['firstname'] = $this->session->userdata('firstname');
            $data['lastname'] = $this->session->userdata('lastname');
            $data['code_parrain'] = $this->session->userdata('code_parrain');
            $data['phone'] = $this->session->userdata('phone');
            $data['adresse'] = $this->session->userdata('adresse');
            $data['category'] = $this->session->userdata('category');
            $data['network'] = $this->session->userdata('network');
            $data['pays'] = $this->user_model->getAllCountries();
            $data['alert'] = "";

            // init params
            $limit_per_page = 10;
            $start_index = ($this->uri->segment(3)) ? $this->uri->segment(3) : 0;
            $total_records = $this->user_model->get_total($pays,$hyper,$ville);

            if ($total_records > 0)
            {
                // get current page records
                $data["tab"] = $this->user_model->get_current_page_records($limit_per_page, $start_index,$pays,$hyper,$ville);
                //$data['positions'] = $this->user_model->get_current_page_records_positions($limit_per_page, $start_index,$pays,$hyper,$ville);
                $config['base_url'] = base_url() . 'Admin/pagination_User_g';
                $config['total_rows'] = $total_records;
                $config['per_page'] = $limit_per_page;
                $config["uri_segment"] = 3;

                $this->load->library('pagination');
                $this->pagination->initialize($config);

                // build paging links
                $data["links"] = $this->pagination->create_links();
            }

            $this->load->view('header', $data);
            $this->load->view('listeadmin');
            $this->load->view('footer');
        }

    }

    public function get_progress_data(){
        @ini_set('display_errors', 'on');

        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 {

            $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);

            //$query = $this->user_model->getGeolocatedUsersForAdmin($pays,$hyper,$ville);

            $total_records = $this->user_model->get_total($pays,$hyper,$ville);
            $data['tab'][] = null;
            $i = 0;
            $start_index = 0;
            $limit_per_page = 100;
            while($i<=$total_records){
                $datas = $this->user_model->get_current_page_records($limit_per_page, $start_index,$pays,$hyper,$ville);
                if($i==0){
                    $data['tab'][] = $datas;
                }else{
                    $data['tab'][] = $datas;
                }
                $i = $i+$limit_per_page;
            }
            echo gettype($data['tab']->result());
            $position_hyper = $this->user_model->getPositionHyper($hyper);

            $data['positions'] = $this->user_model->adminGetAllpositions($pays,$hyper,$ville);
            $data['active'] = "members";
            $data['map_title'] = $this->lang->line('Utilisateurs géolocalisés');
            //$data['tab'] = $query;
            $data['latitude'] = $position_hyper->first_row()->latitude;
            $data['longitude'] = $position_hyper->first_row()->longitude;
            $data['token'] = $this->session->userdata('token');
            $data['email'] = $this->session->userdata('email');
            $data['firstname'] = $this->session->userdata('firstname');
            $data['lastname'] = $this->session->userdata('lastname');
            $data['code_parrain'] = $this->session->userdata('code_parrain');
            $data['phone'] = $this->session->userdata('phone');
            $data['adresse'] = $this->session->userdata('adresse');
            $data['category'] = $this->session->userdata('category');
            $data['network'] = $this->session->userdata('network');
            $data['pays'] = $this->user_model->getAllCountries();
            $data['alert'] = "";
            $this->load->view('header', $data);
            $this->load->view('listeadmin');
            $this->load->view('footer');
        }
    }

    public function initGetAllUser_g(){
        @ini_set('display_errors', 'on');

        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 {

            $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);

            $query = $this->user_model->getGeolocatedUsersForAdmin($pays,$hyper,$ville);
            $data['total_points'] = $this->user_model->getCoutGeolocatedUsersForAdmin($pays,$hyper,$ville);

            $position_hyper = $this->user_model->getPositionHyper($hyper);

            $data['positions'] = $this->user_model->adminGetAllpositions($pays,$hyper,$ville);
            $data['active'] = "members";
            $data['map_title'] = $this->lang->line('Utilisateurs géolocalisés');
            $data['tab'] = $query;
            $data['latitude'] = $position_hyper->first_row()->latitude;
            $data['longitude'] = $position_hyper->first_row()->longitude;
            $data['token'] = $this->session->userdata('token');
            $data['email'] = $this->session->userdata('email');
            $data['firstname'] = $this->session->userdata('firstname');
            $data['lastname'] = $this->session->userdata('lastname');
            $data['code_parrain'] = $this->session->userdata('code_parrain');
            $data['phone'] = $this->session->userdata('phone');
            $data['adresse'] = $this->session->userdata('adresse');
            $data['category'] = $this->session->userdata('category');
            $data['network'] = $this->session->userdata('network');
            $data['pays'] = $this->user_model->getAllCountries();
            $data['alert'] = "";
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));

			$this->load->view('header', $data);
            $this->load->view('listeadmin');
            $this->load->view('footer');
        }

    }

    public function progressRequestUser_g(){

        if(!empty($_POST))
        {

            if($this->session->userdata('category')=='1' or $this->session->userdata('category')=='0'){

                $ville = $this->session->userdata('current_ville');
                $hyper = $this->session->userdata('current_hyper');
                $pays = $this->session->userdata('current_pays');
                $query = $this->user_model->get_current_page_records(200,$this->input->post('start_at'),$pays,$hyper,$ville);
            }elseif ($this->session->userdata('category')=='super') {

                $super = $this->session->userdata('member_code');
                $query = $this->user_model->get_current_page_records_super(200,$this->input->post('start_at'),$super);
            }elseif ($this->session->userdata('category')=='hyper'){

                $ville = $this->session->userdata('current_ville');
                $hyper = $this->session->userdata('member_code');
                $query = $this->user_model->get_current_page_records_hyper(200,$this->input->post('start_at'),$hyper,$ville);
            }
            echo json_encode($query->result());
        }else{
            echo json_encode('null');
        }

    }

}
