<?php
defined('BASEPATH') OR exit('No direct script access allowed');
use Spatie\Async\Pool;

class Gestion extends CI_Controller
{

	public function _contruct()
	{
		parent::_contruct();
		$this->load->model('user_model');
		date_default_timezone_set ($this->session->userdata('timezone'));
	}

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


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


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


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


			$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');
					$data = array('code_parrain' => $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');

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


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


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


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


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


				$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'] = "";

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

	public function recherche()
	{

		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['alert'] = "";
			$data['active'] = "recherche";
			$data['result_search'] = 0;
			$data['default_phone'] = '';
			$data['default_transac'] = '';
			$data['default_code'] = '';
			$data['default_nom'] = '';
			$data['game_pays'] = $this->user_model->getGameCountry();
			$data['networks'] = $this->user_model->getActiveNetwork();

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

	public function get_user()
	{

		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)) {
				$nom = $this->input->post('nom');

				$phone = $this->input->post('phone');
				$simple_users = null;
				if ($phone != '' && $nom != '') {
					$phone_condition = "phone LIKE '" . $phone . "%'";
					$nom_condition = "AND lastname LIKE '%" . $nom . "%'";
					$simple_users = $this->user_model->get_simple_user($phone, $nom);
				} elseif ($phone != '' && $nom == '') {
					$phone_condition = "phone LIKE '" . $phone . "%'";
					$nom_condition = 'AND lastname IS NOT NULL';
					$simple_users = $this->user_model->get_simple_user($phone, '%');
				} elseif ($phone == '' && $nom != '') {
					$phone_condition = 'phone IS NOT NULL';
					$nom_condition = "AND lastname LIKE '%" . $nom . "%'";
					$simple_users = $this->user_model->get_simple_user('%', $nom);
				} elseif ($phone == '' && $nom == '') {
					$phone_condition = 'phone IS NOT NULL';
					$nom_condition = 'AND lastname IS NOT NULL';
				}

				$transac = $this->input->post('transac');
				if ($transac != '') {
					$transac_condition = "AND transactionNumber LIKE'" . $transac . "%'";
				} else {
					$transac_condition = 'AND transactionNumber IS NOT NULL';
				}
				$code = $this->input->post('code');
				if ($code != '') {
					$code_condition = "AND code_membre = '" . $code . "'";
				} else {
					$code_condition = 'AND code_membre IS NOT NULL';
				}

				$where_clause = "WHERE " . $phone_condition . ' ' . $transac_condition . ' ' . $code_condition . ' ' . $nom_condition;

				$res = $this->user_model->get_user($where_clause);

				if ($res != false) {
					$ville = $this->session->userdata('current_ville');
					$hyper = $this->session->userdata('current_hyper');
					$pays = $this->session->userdata('current_pays');
					$count_users = $res->num_rows();
					if ($simple_users != null) {
						$count_users = $res->num_rows() + $simple_users->num_rows();
					}

					$data['alert'] = "";
					$data['active'] = "recherche";
					$data['result_search'] = 1;
					$data['res_users'] = $res;
					$data['res_simple_users'] = $simple_users;
					$data['num_res'] = $count_users;
					$data['default_phone'] = $phone;
					$data['default_nom'] = $nom;
					$data['default_transac'] = $transac;
					$data['default_code'] = $code;
					$data['game_pays'] = $this->user_model->getGameCountry();
					$data['networks'] = $this->user_model->getActiveNetwork();

					$this->load->view('header_gestion', $data);
					$this->load->view('gestion_recherche');
					$this->load->view('footer');
				} else {
					$ville = $this->session->userdata('current_ville');
					$hyper = $this->session->userdata('current_hyper');
					$pays = $this->session->userdata('current_pays');

					$data['alert'] = "";
					$data['active'] = "recherche";
					$data['result_search'] = 2;
					$data['res_simple_users'] = $simple_users;
					$data['default_phone'] = '';
					$data['default_transac'] = '';
					$data['default_code'] = '';
					$data['default_nom'] = '';
					$data['game_pays'] = $this->user_model->getGameCountry();
					$data['networks'] = $this->user_model->getActiveNetwork();

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

	public function update_info_user()
	{

		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 = $_POST['user_id'];
				$phone = $_POST['contact'];
				$adresse = $_POST['adresse'];
				$email = $_POST['email'];
				$nom = $_POST['nom'];
				$res = $this->user_model->update_user_infos($nom, $adresse, $email, $phone, $id);
				if ($res != false) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}
			} else {

			}
		}
	}

	public function update_info_geolocated()
	{

		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_agent = $_POST['user_id'];
				$id_netAg = $_POST['id_netAg'];
				$phone = $_POST['contact'];
				$transac = $_POST['transac'];
				$adresse = $_POST['adresse'];
				$email = $_POST['email'];
				$nom = $_POST['nom'];
				$res = $this->user_model->update_geolocated_infos($nom, $adresse, $email, $id_agent, $transac, $phone, $id_netAg);
				if ($res != false) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}
			} else {

			}
		}
	}

	public function pub()
	{

		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['countries_list'] = $this->user_model->getPubCountries();
			$data['active'] = "pub";
			$data['alert'] = "";
			$data['game_pays'] = $this->user_model->getGameCountry();
			$data['networks'] = $this->user_model->getActiveNetwork();

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

	public function changePubState()
	{

		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_pub = $_POST['pub_id'];
				$etat = $_POST['etat'];
				if ($etat == 0) {
					$res = $this->user_model->updateStatePub($id_pub, 1);
				} elseif ($etat == 1) {
					$res = $this->user_model->updateStatePub($id_pub, 0);
				}
				if ($res != false) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}
			} else {

			}
		}
	}

	public function addPubRow()
	{
		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 = $_POST['country_id'];
				$res = $this->user_model->createPubRow($id_country);
				if ($res != false) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}
			}
		}
	}

	//Wallet

	public function wallet()
	{

		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 ($this->input->get('id')) {

				$network_id = $this->input->get('id');
				if($this->input->get('history')){
					$this->historique($network_id,$this->input->get('d'),$this->input->get('f'),$this->input->get('history'));
				}else{
					$taux = $this->user_model->getTaux($network_id);
					$data['currency'] = $this->user_model->getCurrency($network_id);
					if ($taux != null) {
						$taux = $taux->first_row();
						$data['idConfig'] = $taux->id;
						if ($taux->type == 'visa'){
							$data['taux_client_r'] = $taux->taux_com_client_retrait;
							$data['taux_client_d'] = $taux->taux_com_client_depot;
							$data['taux_ag_r'] = $taux->taux_com_ag_retrait;
							$data['taux_ag_d'] = $taux->taux_com_ag_depot;
							$data['taux_sup_r'] = $taux->taux_com_sup_retrait;
							$data['taux_sup_d'] = $taux->taux_com_sup_depot;
							$data['taux_bq_d'] = $taux->part_banque_depot;
							$data['taux_bq_r'] = $taux->part_banque_retrait;
							$data['frais_d'] = $taux->frais_min_banque_depot;

							$data['transactions'] = $this->user_model->getTransactions(null,null,$network_id);
							$totalCommissionBanque = 0;
							if($data['transactions']){
								foreach ($data['transactions']->result() as $row) {
									$totalCommissionBanque += $row->commission_banque;
								}
							}
							$data['totalCommissionBanque'] = $totalCommissionBanque ;

						} elseif ($taux->type == 'ilink'){
							$data['plr_user_wallet_wallet'] = $this->user_model->getPalierConfigWallet("user_wallet_wallet_international", $data['idConfig']);
							$data['plr_user_wallet_cash'] = $this->user_model->getPalierConfigWallet("user_wallet_cash_international", $data['idConfig']);
							$data['plr_agent_depot_wallet_ilink'] = $this->user_model->getPalierConfigWallet("agent_depot_wallet_ilink_international" , $data['idConfig']);
							$data['plr_agent_depot_autre_wallet'] = $this->user_model->getPalierConfigWallet("agent_depot_autre_wallet_international" , $data['idConfig']);
							$data['plr_agent_cash_cash'] = $this->user_model->getPalierConfigWallet("agent_cash_cash_international", $data['idConfig']);

							$data['plr_user_wallet_wallet_national'] = $this->user_model->getPalierConfigWallet("user_wallet_wallet_national", $data['idConfig']);
							$data['plr_user_wallet_cash_national'] = $this->user_model->getPalierConfigWallet("user_wallet_cash_national", $data['idConfig']);
							$data['plr_agent_depot_wallet_ilink_national'] = $this->user_model->getPalierConfigWallet("agent_depot_wallet_ilink_national" , $data['idConfig']);
							$data['plr_agent_depot_autre_wallet_national'] = $this->user_model->getPalierConfigWallet("agent_depot_autre_wallet_national" , $data['idConfig']);
							$data['plr_agent_cash_cash_national'] = $this->user_model->getPalierConfigWallet("agent_cash_cash_national", $data['idConfig']);

							$data['taxes'] = $this->user_model->getTaxes($data['idConfig']);

							$data['taux_u_w_cart'] = $taux->taux_com_user_wallet_carte;
							$data['taux_u_c_w'] = $taux->taux_com_user_carte_wallet;
							$data['taux_u_c_c'] = $taux->taux_com_user_carte_cash;
							$data['taux_ag_d_c_c'] = $taux->taux_com_wallet_ag_envoi_cash_carte;
							$data['taux_ag_cart_c'] = $taux->taux_com_wallet_ag_carte_cash;
							$data['taux_ag_cash_c'] = $taux->taux_com_wallet_ag_depot_carte;
							$data['taux_ag_s_c'] = $taux->taux_com_ag_envoi_cash;
							$data['taux_sup_s_c'] = $taux->taux_com_sup_envoi_cash;
							$data['taux_hyp_s_c'] = $taux->taux_com_hyp_envoi_cash;
							$data['taux_ag_r_c'] = $taux->taux_com_ag_retrait_cash;
							$data['taux_sup_r_c'] = $taux->taux_com_sup_retrait_cash;
							$data['taux_hyp_r_c'] = $taux->taux_com_hyp_retrait_cash;
							$data['taux_ag_d_c'] = $taux->taux_com_ag_depot_cash_carte;
							$data['taux_sup_d_c'] = $taux->taux_com_sup_depot_cash_carte;
							$data['taux_hyp_d_c'] = $taux->taux_com_hyp_depot_cash_carte;
							$data['taux_bq_d_c'] = $taux->taux_com_banque_depot_cash_carte;
							$data['taux_ag_r_cart'] = $taux->taux_com_ag_retrait_carte_cash;
							$data['taux_sup_r_cart'] = $taux->taux_com_sup_retrait_carte_cash;
							$data['taux_hyp_r_cart'] = $taux->taux_com_hyp_retrait_carte_cash;
							$data['taux_bq_r_cart'] = $taux->taux_com_banque_retrait_carte_cash;
							$data['taux_hyp_r_cart_ilink'] = $taux->taux_com_hyp_retrait_carte_cash_ilink;
							$data['taux_bq_r_cart_ilink'] = $taux->taux_com_banque_retrait_carte_cash_ilink;

							$data['transactions'] = $this->user_model->getNetworkIlinTransactions($network_id);
							$totalCommissionBanque = 0;
							if ($data['transactions']) {
								foreach ($data['transactions']->result() as $trans) {
									$totalCommissionBanque += $trans->commission_banque;
								}
							}
							$data["totalCommissionBanque"] = $totalCommissionBanque;

						}elseif ($taux->type == 'autre') {
							$res = $this->user_model->getSharingRateByNetwork($network_id);
							$data['commission'] = $res ? $res->first_row()->balance_com : 0 ;
						}




					$hyper = $this->user_model->getNetworkHyper($network_id)->first_row();
					$data['walletHyper'] = $this->user_model->getWallet($hyper->agent_id);
					$data['network_id'] = $network_id;
					$networkDetails = $this->user_model->getNetworkDetails($network_id);
					if($networkDetails){
						$data['network'] = $networkDetails->first_row()->network;
						$data['country'] =  $networkDetails->first_row()->country;
					}
//				$data['agentWalletInfos'] = $this->user_model->getInfosWalletAgentForHyper($network_id);
					$data['active'] = "wallet";
					$data['alert'] = "";
					$data['game_pays'] = $this->user_model->getGameCountry();
					$data['networks'] = $this->user_model->getActiveNetwork();

					$this->load->view('header_gestion', $data);
					if ($taux->type == 'visa')
						$this->load->view('gestion_wallet');
					elseif ($taux->type == 'ilink')
						$this->load->view('gestion_wallet_ilink');
					elseif ($taux->type == 'autre')
						$this->load->view('gestion_wallet_autre');
					$this->load->view('footer');
					}
				}


			} else {

				$data['active'] = "wallet";
				$data['alert'] = "";
				$data['game_pays'] = $this->user_model->getGameCountry();
				$data['networks'] = $this->user_model->getAllActivatedNetworks();
				$this->load->view('header_gestion', $data);
				$this->load->view('gestion_wallets');
				$this->load->view('footer');
			}
		}
	}

	public function config_wallet($method = 'create')
	{
		if($this->isLogged()){
			if (isset($_POST)) {

				$network_id = $_POST['network_id'];
				$type = $_POST['type'];
				if($method == 'create')
				{
						$res = $this->user_model->addConfigWallet($network_id , $type);
//					if($res)
//						$this->generateAllWallets($network_id);

				}
				else if($method = 'update'){

					if($type == 'uba'){
						$taux_client_r = $_POST['taux_client_r'];
						$taux_client_d = $_POST['taux_client_d'];
						$taux_ag_d = $_POST['taux_ag_d'];
						$taux_ag_r = $_POST['taux_ag_r'];
						$taux_sup_d = $_POST['taux_sup_d'];
						$taux_sup_r = $_POST['taux_sup_r'];
						$taux_bq_d = $_POST['taux_bq_d'];
						$taux_bq_r = $_POST['taux_bq_r'];
						$frais_d = $_POST['frais_d'];

						$res = $this->user_model->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);

					}else if ($type == 'ilink'){
						$idConfig = $_POST['id_config'];
						$plr_user_wallet_wallet = isset($_POST['plr_user_wallet_wallet']) ? $_POST['plr_user_wallet_wallet'] : null ;
						$plr_user_wallet_cash = isset($_POST['plr_user_wallet_cash']) ? $_POST['plr_user_wallet_cash'] : null ;
						$plr_agent_depot_wallet_ilink = isset($_POST['plr_agent_depot_wallet_ilink']) ? $_POST['plr_agent_depot_wallet_ilink'] : null;
						$plr_agent_depot_autre_wallet = isset($_POST['plr_agent_depot_autre_wallet']) ? $_POST['plr_agent_depot_autre_wallet'] : null;
						$plr_agent_cash_cash  = isset($_POST['plr_agent_cash_cash']) ? $_POST['plr_agent_cash_cash'] : null ;

						$plr_user_wallet_wallet_national = isset($_POST['plr_user_wallet_wallet_national']) ? $_POST['plr_user_wallet_wallet_national'] : null ;
						$plr_user_wallet_cash_national = isset($_POST['plr_user_wallet_cash_national']) ? $_POST['plr_user_wallet_cash_national'] : null ;
						$plr_agent_depot_wallet_ilink_national = isset($_POST['plr_agent_depot_wallet_ilink_national']) ? $_POST['plr_agent_depot_wallet_ilink_national'] : null;
						$plr_agent_depot_autre_wallet_national = isset($_POST['plr_agent_depot_autre_wallet_national']) ? $_POST['plr_agent_depot_autre_wallet_national'] : null;
						$plr_agent_cash_cash_national  = isset($_POST['plr_agent_cash_cash_national']) ? $_POST['plr_agent_cash_cash_national'] : null ;

						$fields = $_POST['fields'];
						$rows = [];
						//Convert fields to simple array
						foreach ($fields as $field) {
							$array = json_decode(json_encode($field), true);
							$i=0;
							$name = "";
							foreach ($array as $key => $value){
								if($i == 0)
								  $name = $value;
								else
									$rows[$name] = $value;
								$i++;
							}
						}

						$this->insertPalier($plr_user_wallet_wallet,"user_wallet_wallet_international", $idConfig);
						$this->insertPalier($plr_user_wallet_cash,"user_wallet_cash_international", $idConfig);
						$this->insertPalier($plr_agent_depot_wallet_ilink,"agent_depot_wallet_ilink_international", $idConfig);
						$this->insertPalier($plr_agent_depot_autre_wallet,"agent_depot_autre_wallet_international", $idConfig);
						$this->insertPalier($plr_agent_cash_cash,"agent_cash_cash_international", $idConfig);

						$this->insertPalier($plr_user_wallet_wallet_national,"user_wallet_wallet_national", $idConfig);
						$this->insertPalier($plr_user_wallet_cash_national,"user_wallet_cash_national", $idConfig);
						$this->insertPalier($plr_agent_depot_wallet_ilink_national,"agent_depot_wallet_ilink_national", $idConfig);
						$this->insertPalier($plr_agent_depot_autre_wallet_national,"agent_depot_autre_wallet_national", $idConfig);
						$this->insertPalier($plr_agent_cash_cash_national,"agent_cash_cash_national", $idConfig);

						$this->user_model->updateConfigWalletIlink($rows['taux_u_w_cart'],$rows['taux_u_c_w'],$rows['taux_u_c_c'],$rows['taux_ag_d_c_c'],$rows['taux_ag_cart_c'],$rows['taux_ag_cash_c'],$rows['taux_ag_s_c'],$rows['taux_sup_s_c'],$rows['taux_hyp_s_c'],$rows['taux_ag_r_c'],$rows['taux_sup_r_c'],
							$rows['taux_hyp_r_c'],$rows['taux_ag_d_c'],$rows['taux_sup_d_c'],$rows['taux_hyp_d_c'],$rows['taux_bq_d_c'], $rows['taux_ag_r_cart'],$rows['taux_sup_r_cart'],$rows['taux_hyp_r_cart'],$rows['taux_bq_r_cart'],
							$rows['taux_hyp_r_cart_ilink'],$rows['taux_bq_r_cart_ilink'],$rows['taux_hyp_s_wallet_cart_ilink'],$rows['taux_bq_s_wallet_cart_ilink'],$idConfig);

						$res = true;
					}

				}
				if ($res != false) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}
			}
		}

	}

	public function saveTaxes(){
		if($this->isLogged()) {
			if(isset($_POST)) {
				$idConfig = $_POST['id_config'];
				$taxes = isset($_POST['taxes']) ? $_POST['taxes'] : null ;
				$this->insertTaxes($taxes, $idConfig);
				$res = true;

				if ($res) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}
			}
		}
	}

	private function insertPalier($palier , $name , $idConfig){

		$exist = $this->user_model->getPalierConfigWallet($name , $idConfig);
		if($exist){
			$this->user_model->deletePalierConfigWallet($name , $idConfig);
		}

		if($palier) {
			foreach ($palier as $p) {
				$array = json_decode(json_encode($p), true);
				$row = [];
				foreach ($array as $key => $value){
					$row[] = $value;
				}
				$this->user_model->addPalierConfigWallet($name, $idConfig, $row[0], $row[1], $row[2]);
			}
		}
	}

	private function insertTaxes($palier , $idConfig){

		$exist = $this->user_model->getTaxes($idConfig);
		if($exist){
			$this->user_model->deleteTaxes($idConfig);
		}

		if($palier) {
			foreach ($palier as $p) {
				$array = json_decode(json_encode($p), true);
				$row = [];
				foreach ($array as $key => $value){
					$row[] = $value;
				}
				$this->user_model->addTaxe($idConfig, $row[0], $row[1], $row[2], $row[3]);
			}
		}
	}

	public function delete_config_wallet()
	{
		if($this->isLogged()){
			if (isset($_POST)) {
				$network_id = $_POST['network_id'];
				$res = $this->user_model->deleteConfigWallet($network_id);
				if ($res != false) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}
			}
		}

	}


	private function isLogged()
	{
		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);
			return false;
		}
		return true;
	}

	public function generateAllWallets(){
		// Asynchrous method

		$network_id = $_POST['network_id'];
		$type = $_POST['type'];
		if($type != 'autre'){
			$pool = Pool::create();
			$pool->add(function () use ($network_id) {
				// Fetch all agents , hyperviseur , superviseur
				$f_agents = $this->user_model->getAllAgentsForNetwork($network_id) ;
				if ($f_agents){
					foreach($f_agents->result() AS $row){
						//Create wallet if it not exist
						$res = $this->user_model->getWallet($row->agent_id);
						if($res){
							// Reinitialize the wallet
//						$this->user_model->reinitializeWallet($res->first_row()->wallet_id);
						}else{
							$this->user_model->addWallet($row->agent_id);
						}
					}
				}
			})->then(function () {

			});
			await($pool);
		}

	}

	private function historique($network_id ,$startDate ,$endDate, $type)
	{

		$data['configWallet'] = $this->user_model->getConfigWallet($network_id);
		$format = $this->session->userdata('site_lang') === 'french' ? 'd-m-Y' : 'Y-m-d' ;
		$data['startDate'] = $startDate ? date($format, strtotime($startDate)) : null ;
		$data['endDate'] = $endDate ?date($format, strtotime($endDate)): null ;
		$endDate =  Date('Y-m-d', strtotime($endDate."+1 day"));
		if ($type == 'transaction')
			$data['transactions'] = $this->user_model->getTransactions($startDate, $endDate, $network_id);
		else if ($type == 'transaction_ilink')
			$data['transactions'] = $this->user_model->getIlinkTransactions($startDate, $endDate, $network_id);
		else
			$data['transactions'] = $this->user_model->getRecharges($startDate, $endDate, $network_id);

		$data['active'] = "wallet";
		$data['alert'] = "";
		$data['networks'] = $this->user_model->getAllActivatedNetworks();
		$data['game_pays'] = $this->user_model->getGameCountry();
		$networkDetails = $this->user_model->getNetworkDetails($network_id);
		if($networkDetails){
			$data['network'] = $networkDetails->first_row()->network;
			$data['country'] =  $networkDetails->first_row()->country;
		}
		$this->load->view('header_gestion', $data);
		if ($type == 'transaction')
			$this->load->view('historique_transactions');
		else if ($type == 'transaction_ilink')
			$this->load->view('historique_transactions_ilink');
		else
			$this->load->view('historique_recharges');
		$this->load->view('footer');
	}

	public function currency()
	{

		if($this->isLogged()){
			$data['active'] = "currency";
			$data['alert'] = "";
			$data['game_pays'] = $this->user_model->getGameCountry();

			if ($this->input->get('id')) {

				$network_id = $this->input->get('id');
				$networkDetails = $this->user_model->getNetworkDetails($network_id);
					$data['network'] = $networkDetails->first_row()->network;
					$data['country'] =  $networkDetails->first_row()->country;
					$data['currency_code'] = $networkDetails->first_row()->currency_code;
					$data['currency_name_fr'] =  $networkDetails->first_row()->currency_name_fr;
					$data['currency_name_en'] =  $networkDetails->first_row()->currency_name_en;

				$data['currencies'] = $this->user_model->getWalletsCountriesCurrencies($data['currency_code']);
				$this->load->view('header_gestion', $data);
				$this->load->view('gestion_monnaie');
				$this->load->view('footer');
			}else{

				$data['networks'] = $this->user_model->getAllActivatedWalletNetworks();

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

	public function fetchExchangeRates(){
		if ($this->isLogged()) {

				$api="c4e31fe540cd49c98abffc06cc5948c8";   ///// Provide your openexchangerates.org api key here
				$string = file_get_contents("https://openexchangerates.org/api/latest.json?app_id=$api");
				$json = json_decode($string, true);

				$res= false;

				foreach ($json['rates'] as $key => $value) {
					if($this->user_model->getExchangeRate($key))
						$this->user_model->updateExchangeRate($key , $value);
					else
						$this->user_model->insertExchangeRate($key , $value);
				}
				$res = true;
				if ($res) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}


		}
	}

	public function cancelTransation()
	{
		if($this->isLogged()) {
			if (isset($_POST)) {
				$id_transacton = $_POST['id_transaction'];

				/* API URL */
				$url = $this->db->wallet_service_url.'/transactions/'.$id_transacton;

				/* Init cURL resource */
				$ch = curl_init($url);

				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");

				/* set the content type json */
				curl_setopt($ch, CURLOPT_HTTPHEADER, array(
					'Content-Type:application/json',
					'Authorization: yhSTSSqIO1uSE1icu09edPOeSFGxIDjo'
				));

				/* set return type json */
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

				/* execute request */
				$result = curl_exec($ch);

				/* close cURL resource */
				curl_close($ch);

				if ($result) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}
			}
		}
	}

}

