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

use Spatie\Async\Pool;

class Gestion extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('wallet_model');
		$this->load->model('nano_credit_model');
		$this->load->model('nano_health_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');


			$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->isLogged()) {

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

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

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

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

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

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

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

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

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

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

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

			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->isLogged()) {
			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 = base_url("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->isLogged()) {

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

			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->isLogged()) {
			$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['message'] = "$number codes have been added!";

			$data['pays'] = $this->user_model->getAllCountries();
			$data['list'] = $this->user_model->getGeneratedHyperCodes();
			$data['active'] = "codes-hyper";
			$data['pays'] = $this->user_model->getAllCountries();
			$data['game_pays'] = $this->user_model->getGameCountry();

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


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

	}

	private function randomString($length = 10)
	{
		do {
			$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];
			}
			$q = $this->db->get_where('codeGenerer', ['code_membre' => $str]);
		} while ($q->num_rows() != 0);

		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 {

			$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['current_agent'] = $data['agent'] ? $data['agent']->first_row()->lastname : null;
			$data['alert'] = "";
			$data['active'] = "geoloc";
			$number_geolocalisation = array();
			$network_geolocalisation = array();
			$count = 0;

			if ($data['networks']) {
				foreach ($data['networks']->result() as $row) {
					$number_geolocalisation[$count] = $this->user_model->getPointGeolocalised($row->id, $data['current_agent']);
					$network_geolocalisation[$count] = $row->name;
					$count++;
				}
			}
			$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->isLogged()) {

			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;

				if ($data['networks']) {
					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'));
				if ($ajaxhyp && $ajaxhyp->num_rows() > 0) {
					echo json_encode($ajaxhyp->result_array());
				} else {
					echo json_encode("no_agent");
				}
			}

		}
	}

	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'));
				if ($ajaxhyp && $ajaxhyp->num_rows() > 0) {
					echo json_encode($ajaxhyp->result_array());
				} else {
					echo json_encode("no_agent");
				}
			}

		}
	}

	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']) {
				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'] ? $data['agent']->first_row()->lastname : null;
			$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->isLogged()) {

			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['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['list'] = $this->user_model->getMembers($pays, $data['q1']);
			$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->isLogged()) {

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

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

			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) {
					$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->isLogged()) {

			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) {
					$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->isLogged()) {
			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) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}
			} else {

			}
		}
	}

	public function update_info_geolocated()
	{
		if ($this->isLogged()) {
			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'];
				if ($this->user_model->isAgentPhoneExist($id_netAg, $phone, $transac)) {
					echo json_encode("400");
				} else {
					$res = $this->user_model->update_geolocated_infos($nom, $adresse, $email, $id_agent, $transac, $phone, $id_netAg);
					if ($res) {
						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->isLogged()) {
			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) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}
			} else {

			}
		}
	}

	public function addPubRow()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$id_country = $_POST['country_id'];
				$res = $this->user_model->createPubRow($id_country);
				if ($res) {
					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->wallet_model->getCurrency($network_id);
					if ($taux != null) {
						$taux = $taux->first_row();
						$data['idConfig'] = $taux->id;
						$data['type'] = $taux->type;
						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->wallet_model->getPalierConfigWallet("user_wallet_wallet_international", $data['idConfig']);
							$data['plr_user_wallet_cash'] = $this->wallet_model->getPalierConfigWallet("user_wallet_cash_international", $data['idConfig']);
							$data['plr_agent_depot_wallet_ilink'] = $this->wallet_model->getPalierConfigWallet("agent_depot_wallet_ilink_international", $data['idConfig']);
							$data['plr_agent_depot_autre_wallet'] = $this->wallet_model->getPalierConfigWallet("agent_depot_autre_wallet_international", $data['idConfig']);
							$data['plr_agent_cash_cash'] = $this->wallet_model->getPalierConfigWallet("agent_cash_cash_international", $data['idConfig']);

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

							$data['taxes'] = $this->wallet_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->wallet_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->wallet_model->getSharingRateByNetwork($network_id);
							$data['commission'] = $res ? $res->first_row()->balance_com : 0;
						} elseif ($taux->type == 'ilink_sante') {
							$nh_config = $this->nano_health_model->getConfig($network_id);
							$data['nh_config'] = $nh_config ? $nh_config->first_row() : null;
							$data['config_id'] = $data['nh_config'] ? $data['nh_config']->id : null;
							$data['years_prices_grid'] = $this->nano_health_model->getConfigYearsPricesGrid($data['config_id']);
							$data['months_prices_grid'] = $this->nano_health_model->getConfigMonthsPricesGrid($data['config_id']);
							$data['acts'] = $this->nano_health_model->getConfigActs($data['config_id']);
						}


						$hyper = $this->wallet_model->getNetworkHyper($network_id);
						if($hyper !== true && $hyper){
							$hyper = $hyper->first_row();
							$data['walletHyper'] = $this->wallet_model->getWallet($hyper->agent_id);
						}else{
							$data['walletHyper'] = null;
						}

						$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 == 'ilink_sante')
							$this->load->view('nano_health/admin/gestion_wallet');
						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->wallet_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)) {
				$type = $_POST['type'];

				$this->db->trans_begin();

				if ($method == 'create') {
					$country_id = $_POST['country_id'];
					$network_id = $_POST['network_id'];

					if ($type == 'ilink') {
						$exist = $this->wallet_model->verifyConfigWalletInCountry($type, $country_id);
						if ($exist) {
							echo json_encode("403");
							return;
						}
					}
					$res = $this->wallet_model->addConfigWallet($network_id, $type);

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

					$idConfig = $_POST['id_config'];

					if ($type == 'visa') {
						$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->wallet_model->updateConfigWallet($idConfig, $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') {

						$config = $_POST['config'];
						$fields = isset($_POST['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++;
							}
						}

						switch ($config) {
							case 'user_wallet_wallet':
								$plr_user_wallet_wallet = $_POST['plr_user_wallet_wallet'] ?? null;
								$plr_user_wallet_wallet_national = $_POST['plr_user_wallet_wallet_national'] ?? null;
								$this->insertPalier($plr_user_wallet_wallet, "user_wallet_wallet_international", $idConfig);
								$this->insertPalier($plr_user_wallet_wallet_national, "user_wallet_wallet_national", $idConfig);
								break;
							case 'user_wallet_carte':
								$plr_user_wallet_cart_national = $_POST['plr_user_wallet_cart_national'] ?? null;
								$plr_hyp_user_wallet_cart_national = $_POST['plr_hyp_user_wallet_cart_national'] ?? null;
								$plr_bank_user_wallet_cart_national = $_POST['plr_bank_user_wallet_cart_national'] ?? null;
//								$plr_user_wallet_cart_international = $_POST['plr_user_wallet_cart_international'] ?? null;
//								$plr_hyp_user_wallet_cart_international = $_POST['plr_hyp_user_wallet_cart_international'] ?? null;
//								$plr_bank_user_wallet_cart_international = $_POST['plr_bank_user_wallet_cart_international'] ?? null;
								$this->insertPalier($plr_user_wallet_cart_national, "user_wallet_cart_national", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_hyp_user_wallet_cart_national, "hyp_user_wallet_cart_national", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_bank_user_wallet_cart_national, "bank_user_wallet_cart_national", $idConfig,'paliers_commissions_wallet');
//								$this->insertPalier($plr_user_wallet_cart_international, "user_wallet_cart_international", $idConfig,'paliers_commissions_wallet');
//								$this->insertPalier($plr_hyp_user_wallet_cart_international, "hyp_user_wallet_cart_international", $idConfig ,'paliers_commissions_wallet');
//								$this->insertPalier($plr_bank_user_wallet_cart_international, "bank_user_wallet_cart_international", $idConfig,'paliers_commissions_wallet');
								break;
							case 'user_wallet_cash':
								$plr_user_wallet_cash = $_POST['plr_user_wallet_cash'] ?? null;
								$plr_user_wallet_cash_national = $_POST['plr_user_wallet_cash_national'] ?? null;
								$this->insertPalier($plr_user_wallet_cash, "user_wallet_cash_international", $idConfig);
								$this->insertPalier($plr_user_wallet_cash_national, "user_wallet_cash_national", $idConfig);
								break;
							case 'user_carte_wallet':
								$plr_user_cart_wallet_international = $_POST['plr_user_cart_wallet_international'] ?? null;
								$plr_user_cart_wallet_national = $_POST['plr_user_cart_wallet_national'] ?? null;
								$plr_user_cart_cash_international = $_POST['plr_user_cart_cash_international'] ?? null;
								$plr_user_cart_cash_national = $_POST['plr_user_cart_cash_national'] ?? null;
								$plr_hyp_user_cart_cash_international = $_POST['plr_hyp_user_cart_cash_international'] ?? null;
								$plr_hyp_user_cart_cash_national = $_POST['plr_hyp_user_cart_cash_national'] ?? null;
								$plr_bank_user_cart_cash_international = $_POST['plr_bank_user_cart_cash_international'] ?? null;
								$plr_bank_user_cart_cash_national = $_POST['plr_bank_user_cart_cash_national'] ?? null;

								$this->insertPalier($plr_user_cart_wallet_international, "user_cart_wallet_international", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_user_cart_wallet_national, "user_cart_wallet_national", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_user_cart_cash_international, "user_cart_cash_international", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_user_cart_cash_national, "user_cart_cash_national", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_hyp_user_cart_cash_international, "hyp_user_cart_cash_international", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_hyp_user_cart_cash_national, "hyp_user_cart_cash_national", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_bank_user_cart_cash_international, "bank_user_cart_cash_international", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_bank_user_cart_cash_national, "bank_user_cart_cash_national", $idConfig,'paliers_commissions_wallet');

								break;
							case 'user_cart_autre_wallet':
								$plr_user_cart_autre_wallet_national = $_POST['plr_user_cart_autre_wallet_national'] ?? null;
								$plr_bank_user_cart_autre_wallet_national = $_POST['plr_bank_user_cart_autre_wallet_national'] ?? null;
								$plr_user_cart_autre_wallet_international = $_POST['plr_user_cart_autre_wallet_international'] ?? null;
								$plr_bank_user_cart_autre_wallet_international = $_POST['plr_bank_user_cart_autre_wallet_international'] ?? null;
								$this->insertPalier($plr_user_cart_autre_wallet_national, "user_cart_autre_wallet_national", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_bank_user_cart_autre_wallet_national, "bank_user_cart_autre_wallet_national", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_user_cart_autre_wallet_international, "user_cart_autre_wallet_international", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_bank_user_cart_autre_wallet_international, "bank_user_cart_autre_wallet_international", $idConfig ,'paliers_commissions_wallet');
								break;
							case 'agent_remove_cash':
								$plr_agent_wallet_cash_national = $_POST['plr_agent_wallet_cash_national'] ?? null;
								$plr_sup_wallet_cash_national = $_POST['plr_sup_wallet_cash_national'] ?? null;
								$plr_agent_wallet_cash_international = $_POST['plr_agent_wallet_cash_international'] ?? null;
								$plr_sup_wallet_cash_international = $_POST['plr_sup_wallet_cash_international'] ?? null;
								$this->insertPalier($plr_agent_wallet_cash_national, "agent_wallet_cash_national", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_sup_wallet_cash_national, "sup_wallet_cash_national", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_agent_wallet_cash_international, "agent_wallet_cash_international", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_sup_wallet_cash_international, "sup_wallet_cash_international", $idConfig ,'paliers_commissions_wallet');
								break;
							case 'agent_remove_carte_cash':
//								$plr_customer_cart_cash_international = $_POST['plr_customer_cart_cash_international'] ?? null;
								$plr_customer_cart_cash_national = $_POST['plr_customer_cart_cash_national'] ?? null;
//								$plr_agent_cart_cash_international = $_POST['plr_agent_cart_cash_international'] ?? null;
								$plr_agent_cart_cash_national = $_POST['plr_agent_cart_cash_national'] ?? null;
//								$plr_sup_cart_cash_international = $_POST['plr_sup_cart_cash_international'] ?? null;
								$plr_sup_cart_cash_national = $_POST['plr_sup_cart_cash_national'] ?? null;
//								$plr_hyp_cart_cash_international = $_POST['plr_hyp_cart_cash_international'] ?? null;
								$plr_hyp_cart_cash_national = $_POST['plr_hyp_cart_cash_national'] ?? null;
//								$plr_bank_cart_cash_international = $_POST['plr_bank_cart_cash_international'] ?? null;
								$plr_bank_cart_cash_national = $_POST['plr_bank_cart_cash_national'] ?? null;

//								$this->insertPalier($plr_customer_cart_cash_international, "customer_cart_cash_international", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_customer_cart_cash_national, "customer_cart_cash_national", $idConfig ,'paliers_commissions_wallet');
//								$this->insertPalier($plr_agent_cart_cash_international, "agent_cart_cash_international", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_agent_cart_cash_national, "agent_cart_cash_national", $idConfig,'paliers_commissions_wallet');
//								$this->insertPalier($plr_sup_cart_cash_international, "sup_cart_cash_international", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_sup_cart_cash_national, "sup_cart_cash_national", $idConfig,'paliers_commissions_wallet');
//								$this->insertPalier($plr_hyp_cart_cash_international, "hyp_cart_cash_international", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_hyp_cart_cash_national, "hyp_cart_cash_national", $idConfig,'paliers_commissions_wallet');
//								$this->insertPalier($plr_bank_cart_cash_international, "bank_cart_cash_international", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_bank_cart_cash_national, "bank_cart_cash_national", $idConfig,'paliers_commissions_wallet');
								break;
							case 'agent_send_cash_carte':
//								$plr_customer_cash_cart_international = $_POST['plr_customer_cash_cart_international'] ?? null;
								$plr_customer_cash_cart_national = $_POST['plr_customer_cash_cart_national'] ?? null;
//								$plr_agent_cash_cart_international = $_POST['plr_agent_cash_cart_international'] ?? null;
								$plr_agent_cash_cart_national = $_POST['plr_agent_cash_cart_national'] ?? null;
//								$plr_sup_cash_cart_international = $_POST['plr_sup_cash_cart_international'] ?? null;
								$plr_sup_cash_cart_national = $_POST['plr_sup_cash_cart_national'] ?? null;
//								$plr_hyp_cash_cart_international = $_POST['plr_hyp_cash_cart_international'] ?? null;
								$plr_hyp_cash_cart_national = $_POST['plr_hyp_cash_cart_national'] ?? null;
//								$plr_bank_cash_cart_international = $_POST['plr_bank_cash_cart_international'] ?? null;
								$plr_bank_cash_cart_national = $_POST['plr_bank_cash_cart_national'] ?? null;

//								$this->insertPalier($plr_customer_cash_cart_international, "customer_cash_cart_international", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_customer_cash_cart_national, "customer_cash_cart_national", $idConfig ,'paliers_commissions_wallet');
//								$this->insertPalier($plr_agent_cash_cart_international, "agent_cash_cart_international", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_agent_cash_cart_national, "agent_cash_cart_national", $idConfig,'paliers_commissions_wallet');
//								$this->insertPalier($plr_sup_cash_cart_international, "sup_cash_cart_international", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_sup_cash_cart_national, "sup_cash_cart_national", $idConfig,'paliers_commissions_wallet');
//								$this->insertPalier($plr_hyp_cash_cart_international, "hyp_cash_cart_international", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_hyp_cash_cart_national, "hyp_cash_cart_national", $idConfig,'paliers_commissions_wallet');
//								$this->insertPalier($plr_bank_cash_cart_international, "bank_cash_cart_international", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_bank_cash_cart_national, "bank_cash_cart_national", $idConfig,'paliers_commissions_wallet');
								break;
							case 'agent_send_cash_canal':
								$plr_agent_depot_wallet_ilink = $_POST['plr_agent_depot_wallet_ilink'] ?? null;
								$plr_agent_depot_autre_wallet = $_POST['plr_agent_depot_autre_wallet'] ?? null;
								$plr_agent_cash_cash = $_POST['plr_agent_cash_cash'] ?? null;

								$plr_agent_depot_wallet_ilink_national = $_POST['plr_agent_depot_wallet_ilink_national'] ?? null;
								$plr_agent_depot_autre_wallet_national = $_POST['plr_agent_depot_autre_wallet_national'] ?? null;
								$plr_agent_cash_cash_national = $_POST['plr_agent_cash_cash_national'] ?? null;

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

								// Paliers des commissions

								$plr_agent_cash_wallet_or_cash_international = $_POST['plr_agent_cash_wallet_or_cash_international'] ?? null;
								$plr_agent_cash_wallet_or_cash_national = $_POST['plr_agent_cash_wallet_or_cash_national'] ?? null;
								$plr_sup_cash_wallet_or_cash_international = $_POST['plr_sup_cash_wallet_or_cash_international'] ?? null;
								$plr_sup_cash_wallet_or_cash_national = $_POST['plr_sup_cash_wallet_or_cash_national'] ?? null;
//								$plr_hyp_cash_wallet_or_cash_international = $_POST['plr_hyp_cash_wallet_or_cash_international'] ?? null;
//								$plr_hyp_cash_wallet_or_cash_national = $_POST['plr_hyp_cash_wallet_or_cash_national'] ?? null;

								$this->insertPalier($plr_agent_cash_wallet_or_cash_international, "agent_cash_wallet_or_cash_international", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_agent_cash_wallet_or_cash_national, "agent_cash_wallet_or_cash_national", $idConfig ,'paliers_commissions_wallet');
								$this->insertPalier($plr_sup_cash_wallet_or_cash_international, "sup_cash_wallet_or_cash_international", $idConfig,'paliers_commissions_wallet');
								$this->insertPalier($plr_sup_cash_wallet_or_cash_national, "sup_cash_wallet_or_cash_national", $idConfig,'paliers_commissions_wallet');
//								$this->insertPalier($plr_hyp_cash_wallet_or_cash_international, "hyp_cash_wallet_or_cash_international", $idConfig ,'paliers_commissions_wallet');
//								$this->insertPalier($plr_hyp_cash_wallet_or_cash_national, "hyp_cash_wallet_or_cash_national", $idConfig,'paliers_commissions_wallet');

								break;
						}


					} else if ($type == 'ilink_sante') {
						unset($_POST['id_config'], $_POST['type']);
						$this->nano_health_model->updateConfig($idConfig, $_POST);

					}

				}

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

	}

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

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

	private function insertPalier($palier, $type, $idConfig , $table = 'paliersConfigWallet')
	{
		$this->db->delete($table,['type' => $type , 'idConfig' => $idConfig]);

		if ($palier) {
			$data = [];
			foreach ($palier as $p) {
				$data[] = [
					'type' => $type,
					'min' => $p[0],
					'max' => $p[1],
					'taux' => $p[2],
					'plafond' => !empty($p[3]) ? $p[3] : null,
					'idConfig' => $idConfig
				];
			}
			if(sizeof($data) > 0){
				$this->db->insert_batch($table,$data);
			}
		}
	}

	private function insertTaxes($palier, $idConfig, $categorie)
	{

		$exist = $this->wallet_model->getTaxes($idConfig, $categorie);
		if ($exist) {
			$this->wallet_model->deleteTaxes($idConfig, $categorie);
		}

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

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

	}

	public function disable_config_wallet()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$network_id = $_POST['network_id'];
				$res = $this->wallet_model->disableConfigWallet($network_id);
				if ($res) {
					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->wallet_model->getAllAgentsForNetwork($network_id);
				if ($f_agents) {
					foreach ($f_agents->result() as $row) {
						//Create wallet if it not exist
						$res = $this->wallet_model->getWallet($row->agent_id);
						if ($res) {
							// Reinitialize the wallet
//						$this->wallet_model->reinitializeWallet($res->first_row()->wallet_id);
						} else {
							$this->wallet_model->addWallet($row->agent_id);
						}
					}
				}
			})->then(function () {

			});
			await($pool);
		}

	}

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

		$data['configWallet'] = $this->wallet_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 == 'recharge')
			$data['transactions'] = $this->wallet_model->getRecharges($startDate, $endDate, $network_id);

		$data['active'] = "wallet";
		$data['alert'] = "";
		$data['networks'] = $this->wallet_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;
			$data['currency_name_fr'] = $networkDetails->first_row()->currency_name_fr;
			$data['currency_name_en'] = $networkDetails->first_row()->currency_name_en;
			$data['currency_code'] = $networkDetails->first_row()->currency_code;
		}
		$data['id_network'] = $network_id;
		$this->load->view('header_gestion', $data);
		if ($type == 'transaction')
			$this->load->view('historique_transactions');
		else if ($type == 'deleted_transactions')
			$this->load->view('historique_transactions_deleted');
		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->wallet_model->getWalletsCountriesCurrencies($data['currency_code']);
				$this->load->view('header_gestion', $data);
				$this->load->view('gestion_monnaie');
				$this->load->view('footer');
			} else {

				$data['networks'] = $this->wallet_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);

			foreach ($json['rates'] as $key => $value) {
				if ($this->wallet_model->getExchangeRate($key))
					$this->wallet_model->updateExchangeRate($key, $value);
				else
					$this->wallet_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 = 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:' . WALLET_SERVICE_TOKEN,
					'X-localization:' . $this->session->userdata('site_lang') == 'french' ? 'fr' : 'en'
				));

				/* 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");
				}
			}
		}
	}

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

				/* API URL */
				$url = WALLET_SERVICE_URL . '/transactions/ilink/' . $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:' . WALLET_SERVICE_TOKEN,
					'X-localization:' . $this->session->userdata('site_lang') == 'french' ? 'fr' : 'en'
				));

				/* 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");
				}
			}
		}
	}

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

			if ($this->input->get('id')) {
				$data['network_id'] = $this->input->get('id');

				if ($this->input->get('history')) {
					$this->historique_nano_credit($data['network_id'], $this->input->get('d'), $this->input->get('f'), $this->input->get('history'));
				} elseif ($this->input->get('group')) {
					$this->users_group_details($data['network_id'], $this->input->get('group'));
				} else {
					$data['groups'] = $this->nano_credit_model->getUsersGroups($data['network_id']);
					$configWallet = $this->wallet_model->getConfigWallet($data['network_id']);
					$data['configWallet'] = is_array($configWallet) ? reset($configWallet) : $configWallet;
					$networkDetails = $this->user_model->getNetworkDetails($data['network_id']);
					if ($networkDetails) {
						$data['network'] = $networkDetails->first_row()->network;
						$data['country'] = $networkDetails->first_row()->country;
						$data['currency_code'] = $networkDetails->first_row()->currency_code;
					}

					$data['rates_nano_credit'] = $this->nano_credit_model->getNanoCreditRates($data['configWallet']->id);
					$data['taxes_nano_credit'] = $this->wallet_model->getTaxes($data['configWallet']->id, 'nano_credit');

					$data['rates_epargne'] = $this->nano_credit_model->getNanoCreditRates($data['configWallet']->id, 'epargne');
					$data['taxes_epargne'] = $this->wallet_model->getTaxes($data['configWallet']->id, 'epargne');
					$this->load->view('header_gestion', $data);
					$this->load->view('nano_credit/gestion_nano_credit_admin');
					$this->load->view('footer');
				}
			} else {
				$data['networks'] = $this->nano_credit_model->getAllIlinkWorldNetworks();
				$this->load->view('header_gestion', $data);
				$this->load->view('nano_credit/gestion_nano_credits');
				$this->load->view('footer');

			}
		}
	}

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

		$data['configWallet'] = $this->wallet_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 == 'nano_credit') {
			$data['transactions'] = $this->nano_credit_model->getUserDemandesCredit($startDate, $endDate, $network_id);
		} else if ($type == 'savings') {
			$data['transactions'] = $this->nano_credit_model->getUsersSavings($startDate, $endDate, $network_id);
		}
		$data['active'] = "nano_credit";
		$data['alert'] = "";
		$data['networks'] = $this->wallet_model->getAllActivatedNetworks();
		$data['game_pays'] = $this->user_model->getGameCountry();
		$data['id_network'] = $network_id;
		$networkDetails = $this->user_model->getNetworkDetails($network_id);
		if ($networkDetails) {
			$data['network'] = $networkDetails->first_row()->network;
			$data['country'] = $networkDetails->first_row()->country;
			$data['currency_name_fr'] = $networkDetails->first_row()->currency_name_fr;
			$data['currency_name_en'] = $networkDetails->first_row()->currency_name_en;
			$data['currency_code'] = $networkDetails->first_row()->currency_code;
		}
		$this->load->view('header_gestion', $data);
		if ($type == 'savings')
			$this->load->view('nano_credit/historique_savings');
		else
			$this->load->view('nano_credit/historique_nano_credit');
		$this->load->view('footer');
	}

	private function users_group_details($network_id, $group_code)
	{
		$data['active'] = "nano_credit";
		$data['alert'] = "";
		$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;
			$data['currency_code'] = $networkDetails->first_row()->currency_code;
		}


		$data['category'] = $this->session->userdata('category');
		$data['members'] = $this->nano_credit_model->getGroupMembers($group_code);
		$data['group'] = $this->nano_credit_model->getGroup($group_code);

		//Calcul de la capacite d'emprunt
		$CE = 0;
		if ($data['members']) {
			$sommeCredits = 0;
			$sommeEpargnes = 0;
			foreach ($data['members']->result() as $user) {
				$sum_credit = $this->nano_credit_model->sumGroupCredit($user->id_user) ? $this->nano_credit_model->sumGroupCredit($user->id_user)->credit : 0;
				$sommeCredits += $sum_credit;
				$sommeEpargnes += $user->balance_epargne;
			}
			$CE = $sommeEpargnes - $sommeCredits;
		}

		$data['CE'] = $CE;
		$data['group_code'] = $group_code;
		$this->load->view('header_gestion', $data);
		$this->load->view('nano_credit/users_group_detail');
		$this->load->view('footer');
	}

	public function activate_nano_credit()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {

				$id_network = $_POST['id_network'];
				$this->nano_credit_model->insertCreditLimit(0, 0, '1', $id_network);
				$res = true;

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

	public function delete_nano_credit()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$id_network = $_POST['id_network'];

				$this->nano_credit_model->insertCreditLimit(0, 0, '0', $id_network);
				$res = true;

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

	public function regulations()
	{

		if ($this->isLogged()) {
			$data['active'] = "regulations";
			$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->wallet_model->getWalletsCountriesCurrencies($data['currency_code']);
				$this->load->view('header_gestion', $data);
				$this->load->view('gestion_monnaie');
				$this->load->view('footer');
			} else {

				$data['countries'] = $this->wallet_model->getRegulationsCountries();

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

	public function setRegulationsLimits()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {

				$country_id = $_POST['country_id'];
				$max_day_national = $_POST['max_day_national'];
				$max_week_national = $_POST['max_week_national'];
				$max_month_national = $_POST['max_month_national'];

				$max_day_international = $_POST['max_day_international'];
				$max_week_international = $_POST['max_week_international'];
				$max_month_international = $_POST['max_month_international'];

				$limits = $this->wallet_model->getRegulationsLimits($country_id);
				if ($limits) {
					$this->wallet_model->updateRegulationsLimits($country_id, $max_day_national, $max_week_national, $max_month_national,
						$max_day_international, $max_week_international, $max_month_international);
				} else {
					$this->wallet_model->insertRegulationsLimits($country_id, $max_day_national, $max_week_national, $max_month_national,
						$max_day_international, $max_week_international, $max_month_international);
				}
				$res = true;
				if ($res) {
					echo json_encode("200");
				} else {
					echo json_encode("500");
				}
			}
		}
	}

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

			$data['operators'] = $this->wallet_model->getAllOperatorsCountries();
			$data['pays'] = $this->user_model->getAllPays();
			$data['game_pays'] = $this->user_model->getGameCountry();
			$data['alert'] = "";
			$data['active'] = "operators";
			$data['distinct_operators'] = $this->wallet_model->getAllOperators();
			$data['operators_types'] = $this->db->get('type_operators');

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

	}

	public function add_operator()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$data = array(
					'nom' => $this->input->post('name'),
					'type' => $this->input->post('type')
				);

				$query = $this->db->insert('operators', $data);
				if ($query) {
					echo json_encode("completed");
				} else {
					echo json_encode("error");
				}
			}
		}
	}

	public function add_operator_type()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {

				$query = $this->db->get_where('type_operators', array('code' => $this->input->post('code')), 1);
				$exist = $query->num_rows() > 0;
				if ($exist) {
					echo json_encode(422);
				} else {
					$data = array(
						'code' => $this->input->post('code'),
						'description_fr' => $this->input->post('description_fr'),
						'description_en' => $this->input->post('description_fr')
					);

					$query = $this->db->insert('type_operators', $data);
					if ($query) {
						echo json_encode(200);
					} else {
						echo json_encode(500);
					}
				}

			}
		}
	}

	public function delete_operator()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$id_operator = $this->input->post('id_operator');
				$id_country = $this->input->post('id_country');

				$query = $this->wallet_model->deleteOperatorCountry($id_operator, $id_country);
				if ($query) {
					echo json_encode("completed");
				} else {
					echo json_encode("error");
				}
			}
		}
	}

	public function assign_operator()
	{
		if (!$this->isLogged()) {
			echo json_encode("unauthorized");
			return;
		}

		if (!isset($_POST['id_operator']) || empty($_POST['id_country'])) {
			echo json_encode("invalid_data");
			return;
		}

		$id_operator = $this->input->post('id_operator');
		$countries = $this->input->post('id_country');

		$this->db->trans_begin();
		$existe = 0;
		$noNetwork = 0;

		foreach ($countries as $id_country) {

			// Vérifier si une assignation opérateur-pays existe déjà
			$res = $this->wallet_model->checkIfOperatorAssignationExist($id_country, $id_operator);

			if ($res === false) {
				// Créer l’assignation opérateur-pays
				$data = [
					'id_country' => $id_country,
					'id_operator' => $id_operator
				];
				$this->db->insert('operators_countries', $data);
				$id_operator_country = $this->db->insert_id();
			} else {
				$id_operator_country = $res->row()->id;
				$existe++;
			}

			// Récupérer les réseaux actifs de ce pays
			$activeNetworks = $this->db->query("
				SELECT id FROM networks 
				WHERE country_id = ? AND status = 1 AND name LIKE 'iLink%'
			", [$id_country])->result();

			if (empty($activeNetworks)) {
				$noNetwork++;
				continue; 
			}

			// Créer la liaison networks_operators pour chaque réseau actif
			foreach ($activeNetworks as $network) {
				$existsLink = $this->db->query("
					SELECT 1 FROM networks_operators
					WHERE id_operator_country = ? AND id_network = ?
				", [$id_operator_country, $network->id])->num_rows();

				if ($existsLink == 0) {
					$this->db->insert('networks_operators', [
						'id_operator_country' => $id_operator_country,
						'id_network' => $network->id
					]);
				}
			}
		}

		// Gestion des statuts de transaction
		if ($this->db->trans_status() === FALSE) {
			$this->db->trans_rollback();
			echo json_encode("error");
		} else {
			$this->db->trans_commit();
			if ($noNetwork > 0 && $existe == 0)
				echo json_encode("Aucun réseau actif"); // certains pays n’ont pas de réseaux actifs
			elseif ($existe > 0)
				echo json_encode("existe");
			else
				echo json_encode("completed");
		}
	}


	public function update_operator()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$id_operator = $this->input->post('id_operator');
				$id_country = $this->input->post('id_country');
				$name = $this->input->post('name');
				$address = $this->input->post('address');
				$code = $this->input->post('code');

				$res = $this->wallet_model->updateOperator($id_operator, $id_country, $name, $address, $code);

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

	public function change_operator_status()
	{
		if ($this->isLogged()) {
			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 $row) {

						$data = array('status' => 1);
						$this->db->where('id_operator', $row['id_operator']);
						$this->db->where('id_country', $row['id_country']);
						$this->db->update('operators_countries', $data);

					}
				}
				if (!empty($_POST['desactivations'])) {
					foreach ($_POST['desactivations'] as $row) {

						$data = array('status' => 0);
						$this->db->where('id_operator', $row['id_operator']);
						$this->db->where('id_country', $row['id_country']);
						$this->db->update('operators_countries', $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 settings()
	{
		if ($this->isLogged()) {
			$data['active'] = "settings";
			$data['alert'] = "";
			$data['game_pays'] = $this->user_model->getGameCountry();
			$data['pas_chargement'] = $this->user_model->getAdminConfig('pas_chargement');
			$data['active_pub'] = $this->user_model->getAdminConfig('active_pub', 'bool');
//			$data['enable_sms_notifications'] =  $this->user_model->getAdminConfig('enable_sms_notifications', 'bool');
//			$data['towns'] = $this->user_model->getAllVilles();

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

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

			$pas = $this->input->post('pas');
			$jours = $this->input->post('jours');
			$default_locality = $this->input->post('default_locality');
			$enable_sms_notifications = $this->input->post('enable_sms_notifications');

			$office_penalty_percent = $this->input->post('office_penalty_percent');
			$month_delay_penalty_percent = $this->input->post('month_delay_penalty_percent');
			$payment_deadline_date = $this->input->post('payment_deadline_date');
			if (isset($pas)) {
				$result = $this->user_model->insertAdminConfig('pas_chargement', $pas);
			}

			if (isset($jours)) {
				$result = $this->user_model->insertAdminConfig('jours_calendaires', $jours);
			}

			if (isset($default_locality)) {
				$result = $this->user_model->insertAdminConfig('default_locality', $default_locality, '');
			}


			if (isset($enable_sms_notifications)) {
				$result = $this->user_model->insertAdminConfig('enable_sms_notifications', $enable_sms_notifications, 'bool');

			}

			if (isset($office_penalty_percent)) {
				$result = $this->user_model->insertAdminConfig('office_penalty_percent', $office_penalty_percent);
			}

			if (isset($month_delay_penalty_percent)) {
				$result = $this->user_model->insertAdminConfig('month_delay_penalty_percent', $month_delay_penalty_percent);
			}

			if (isset($payment_deadline_date)) {
				$result = $this->user_model->insertAdminConfig('payment_deadline_date', $payment_deadline_date, 'date');
			}

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

	public function aggregators()
	{
		if ($this->isLogged()) {
			$data['active'] = "aggregators";
			$data['alert'] = "";
			$data['aggregators'] = $this->db->get_where('payment_aggregators')->result() ?? [];
			foreach ($data['aggregators'] as $i => $aggregator){
				$data['aggregators'][$i]->rates = $this->db->get_where('payment_aggregator_rates',['aggregator_id' => $aggregator->id])->result();
			}
			//$data['pays'] = $this->user_model->getAllPays();
			$data['game_pays'] = $this->user_model->getGameCountry();
			$this->load->view('header_gestion', $data);
			$this->load->view('gestion_aggregators');
			$this->load->view('footer');
		}
	}

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

			$data['request_bank_accounts'] = $this->user_model->getAllRequests();
			$data['request_links_bank_accounts'] = $this->user_model->getAllLinksBankAccounts();
			$data['alert'] = "";
			$data['active'] = "agency_banking";
			$data['game_pays'] = $this->user_model->getGameCountry();

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

	public function update_request_agency() {
		$id = $this->input->post('id');

		$data = $this->input->post();
		if (!$id) {
			echo json_encode([
				'success' => false,
				'message' => "ID manquant"
			]);
			return;
		}

		unset($data['id']); // on retire l'id pour éviter un update
		if(isset($data['type'])){
			unset($data['type']);
		}

		$response = $this->user_model->updateInfoAgency($id, $data);
		if($response) {	
			echo json_encode([
				'alert'   => 'ok',
				'success' => 'ok',
				'message' => $this->lang->line('update_successfully')
			]);
		} else {
			echo json_encode([
				'alert'   => 'ok',
				'success' => 'false',
				'message' => $this->lang->line('update_failed_one_error_occurred')
			]);
		}
    }

    public function delete_request_agency() {
        $id = $this->input->post('id');
		if(!$id){
			echo json_encode([
				'success' => false,
				'message' => "ID manquant"
			]);
			return;
		}
		
        $response = $this->user_model->deleteInfoAgency($id);
		if($response) {
			echo json_encode([
				"alert"=> "ok",
				"success"=> "ok",
				"message"=> $this->lang->line("deletion_successfully")
			]);
		}else{
			echo json_encode([
				"alert"=> "ok",
				"success"=> "false",
				"message"=> $this->lang->line("deletion_failed_one_error_occurred")
			]);
		}
    }

	public function get_account_data() {
		$id = $this->input->post('id');
		$data = $this->user_model->get_account($id);
		echo json_encode($data);
	}

	public function validate_request_agency() {
		if ($this->isLogged()) {
			$id = $this->input->post('id');
			$doc_front = $this->input->post('doc_front');
			$doc_back = $this->input->post('doc_back');

			$updateLocal = $this->user_model->updateRequestStatus($id, 'validated');
			log_message('info', 'Validation de la demande d\'ouverture de compte agence bancaire ID_demande ' . $id);

			if ($updateLocal) {
		
				$url = WALLET_SERVICE_URL . '/wallets/users/activate_user_bank_account';

				$body = [
					'id' => $id,
					'doc_front' => $doc_front,
					'doc_back' => $doc_back
					// Vous pouvez ajouter ici l'ID de l'admin qui valide si nécessaire
					// 'validated_by' => $this->session->userdata('user_id') 
				];
				
				$payload = json_encode($body);

				$ch = curl_init($url);
				
				curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
				curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
				
				curl_setopt($ch, CURLOPT_HTTPHEADER, array(
					'Content-Type: application/json',
					'Content-Length: ' . strlen($payload),
					'Authorization: ' . WALLET_SERVICE_TOKEN,
					'X-localization: ' . ($this->session->userdata('site_lang') == 'french' ? 'fr' : 'en')
				));
				
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

				// Exécution
				$result = curl_exec($ch);
				$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
				curl_close($ch);

				// log_message('info', 'Réponse API lors de l\'ouverture du compte agence bancaire ID_demande ' . $id . ' : ' . $result);

				if ($result && ($httpCode >= 200 && $httpCode < 300)) {

					echo json_encode([
						'success' => 'ok', 
						'message' => 'Compte créé avec succès.'
					]);
				} else {

					$response_array = json_decode($result, true); 
					$merror_message = isset($response_array['error']) ? $response_array['error'] : 'Unknown error';

					echo json_encode([
						'success' => 'false', 
						'message' => 'Un problème est survenu lors de l\'ouverture du compte (' . $merror_message . ')'
					]);
					log_message('error', '------------- Erreur API lors de l\'ouverture du compte agence bancaire ID_demande ' . $id . ' : ' . $result);

				}
			} else {

				echo json_encode(['alert' => 'error', 'success' => 'false', 'message' => 'Erreur lors de l\'activation du compte']);
			}
		}
	}

	/* --------------------------------------------------------------------------
	GESTION DES RATTACHEMENTS (LINKS)
	-------------------------------------------------------------------------- */

	public function validate_link_request() {
		if ($this->isLogged()) {
			$id = $this->input->post('id_transaction');
			$iban = $this->input->post('iban'); 

			log_message('info', 'Validation de la demande de rattachement ID_transaction ' . $id);

			// Démarrage transaction
			$this->db->trans_begin();

			// Appel API
			$url = WALLET_SERVICE_URL . '/wallets/users/validate_link_user_bank_account'; 
			
			log_message('info', 'URL API pour rattachement : ' . $url);
			$body = [
				'id_transaction' => $id,
				'iban' => $iban
			];

			$payload = json_encode($body);
			
			$ch = curl_init($url);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
			curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array(
				'Content-Type: application/json',
				'Content-Length: ' . strlen($payload),
				'Authorization: ' . WALLET_SERVICE_TOKEN,
				'X-localization: ' . ($this->session->userdata('site_lang') == 'french' ? 'fr' : 'en')
			));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

			// Désactivation SSL pour test local si besoin
			// curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
			// curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

			$result = curl_exec($ch);
			$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
			curl_close($ch);

			// log_message('info', 'API Response for Link ID '.$id.' : HTTP Code = '.$httpCode.', Result = '.$result);

			if ($result && ($httpCode >= 200 && $httpCode < 300)) {
				$this->db->trans_commit();
				
				// SUCCÈS
				echo json_encode([
					'success' => 'ok', 
					'message' => 'Rattachement de compte validé avec succès.'
				]);
				exit;

			} else {
				$this->db->trans_rollback();
				$result = json_decode($result, true); 
				$merror_message = isset($result['error']) ? $result['error'] : 'Unknown error';
				log_message('error', 'Erreur API Link ID '.$id.' : '.$merror_message);
				
				// ERREUR API
				echo json_encode([
					'success' => 'false',
					'message' => 'Error :  (' . $merror_message . ')'
				]);
				log_message('error', '------------- Erreur API lors de la validation du rattachement ID_transaction ' . $id . ' : ' . $merror_message);
				exit;
			}
		}
	}

	public function update_link_request() {
		if ($this->isLogged()) {
			$id = $this->input->post('id_transaction');
			
			// On récupère les données du formulaire
			$data = [];
			if($this->input->post('iban')) $data['iban'] = $this->input->post('iban');
			if($this->input->post('code_client')) $data['code_client'] = $this->input->post('code_client');
			
			// is_verified (Status)
			if($this->input->post('is_verified') !== null) {
				$data['is_verified'] = $this->input->post('is_verified');
			}

			$result = $this->user_model->updateLinkRequest($id, $data);

			if ($result) {
				echo json_encode(['success' => 'ok', 'message' => 'Mise à jour réussie']);
			} else {
				echo json_encode(['success' => 'false', 'message' => 'Erreur DB']);
			}
		}
	}

	// 3. SUPPRESSION
	public function delete_link_request() {
		if ($this->isLogged()) {
			$id = $this->input->post('id_transaction');
			$result = $this->user_model->deleteLinkRequest($id);
			
			if ($result) {
				echo json_encode(['success' => 'ok', 'message' => 'Suppression effectuée']);
			} else {
				echo json_encode(['success' => 'ko', 'message' => 'Erreur DB']);
			}
		}
	}

}

