<?php

use Brick\Money\Context\AutoContext;
use Brick\Money\Money;

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

class Admin_dash extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('user_model');
		$this->load->model('wallet_model');
		$this->load->model('nano_credit_model');

	}

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

			$data['pays'] = $this->user_model->getAllCountries();
			$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
			$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);

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

			$data['c_users'] = $this->user_model->getCoutForAdmin($pays, $hyper, $ville, 'simple_users');
			$data['c_geolocated'] = $this->user_model->getCoutForAdmin($pays, $hyper, $ville, 'geolocated');
			$data['c_code'] = $this->user_model->getCoutForAdmin($pays, $hyper, $ville, 'validated_code');
			$data['c_generated'] = $this->user_model->getCoutForAdmin($pays, $hyper, $ville, 'generated_code');
			$data['list_simple_users'] = $this->user_model->getAllSimpleUser($pays, $hyper);
			$data['list_geolocated_users'] = $this->user_model->getOnlyGeolocatedUsersForAdmin($pays, $hyper, $ville);
			$data['active'] = "dash";
			$data['firstname'] = $this->session->userdata('firstname');
			$data['lastname'] = $this->session->userdata('lastname');
			$data['email'] = $this->session->userdata('email');
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));

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

	}

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

			$data['pays'] = $this->user_model->getAllCountries();
			$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
			if ($data['hyper']->num_rows() > 0) {
				$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
			} else {
				$data['ville'] = null;
			}
			$data['active'] = "dash";
			$data['firstname'] = $this->session->userdata('firstname');
			$data['lastname'] = $this->session->userdata('lastname');
			$data['email'] = $this->session->userdata('email');
			$this->load->view('firstfilter', $data);
		}
	}

	public function firstFilter()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$this->session->set_userdata('current_pays', $this->input->post('pays'));
				$pays_name = $this->db->query("SELECT name , currency_code FROM countries_currencies WHERE id='" . $this->input->post('pays') . "'");
				$this->session->set_userdata('current_hyper', $this->input->post('hyper'));
				$infos_network = $this->db->query("SELECT networks.id, name,phone, networks_agents.agent_id, code_membre FROM networks INNER JOIN networks_agents ON networks.id=networks_agents.network_id INNER JOIN codeGenerer ON networks_agents.codeGenerer_id=codeGenerer.id WHERE codeGenerer.code_membre='" . $this->input->post('hyper') . "'");
				$network = $infos_network->first_row()->name;
				$contact_hyper = $infos_network->first_row()->phone;
				$this->session->set_userdata('current_network', $network);
				$this->session->set_userdata('current_network_id',$infos_network->first_row()->id);
				$this->session->set_userdata('current_hyper_id',$infos_network->first_row()->agent_id);
				$this->session->set_userdata('current_hyper_member_code',$infos_network->first_row()->code_membre);

				$this->session->set_userdata('current_contact_hyper', $contact_hyper);
				$this->session->set_userdata('current_ville', $this->input->post('ville'));
				$town_name = $this->db->query("SELECT name FROM towns WHERE id='" . $this->input->post('ville') . "'");

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

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

				$data['c_users'] = $this->user_model->getCoutForAdmin($pays, $hyper, $ville, 'simple_users');
				$data['c_code'] = $this->user_model->getCoutForAdmin($pays, $hyper, $ville, 'validated_code');
				$data['c_geolocated'] = $this->user_model->getCoutForAdmin($pays, $hyper, $ville, 'geolocated');
				$data['c_generated'] = $this->user_model->getCoutForAdmin($pays, $hyper, $ville, 'generated_code');
				$data['list_simple_users'] = $this->user_model->getAllSimpleUser($pays, $hyper);
				$data['list_geolocated_users'] = $this->user_model->getOnlyGeolocatedUsersForAdmin($pays, $hyper, $ville);

				$data['pays'] = $this->user_model->getAllCountries();
				$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
				$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
				$data['active'] = "dash";
				$data['firstname'] = $this->session->userdata('firstname');
				$data['lastname'] = $this->session->userdata('lastname');
				$data['email'] = $this->session->userdata('email');
				$data['network'] = $this->session->userdata('current_network');
				$data['contact_hyper'] = $this->session->userdata('current_contact_hyper');
				$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));
				$hyperPosition = $this->db->query("SELECT a.latitude,a.longitude FROM agents a INNER JOIN networks_agents na ON a.id= na.agent_id INNER JOIN codeGenerer ON na.codeGenerer_id=codeGenerer.id WHERE codeGenerer.code_membre='" . $this->input->post('hyper') . "'");
				$this->session->set_userdata('hyper_latitude', $hyperPosition->first_row()->latitude);
				$this->session->set_userdata('hyper_longitude', $hyperPosition->first_row()->longitude);

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

	// Wallet
	public function wallet()
	{
		if ($this->isLogged()) {
			$id_network = $this->session->userdata('current_network_id');
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));
			if ($data['hasWallet']) {

				if ($this->input->get('history')) {
					$this->historique($id_network, $this->input->get('d'), $this->input->get('f'), $this->input->get('history'));
				} elseif ($this->input->get('config')) {
					$this->config_wallet($this->input->get('config'), $this->input->get('country'));
				} elseif ($this->input->get('show')) {
					$this->show_config_infos($this->input->get('show'));
				}else {
					$context = new AutoContext();

					$data["commission"] = "";
					$data["principal"] = "";
					$data["transactions"] = "";
					$agent_id = $this->session->userdata('current_hyper_id');


					$taux = $data['hasWallet'];
					$data['idConfig'] = $taux->id;
					if ($data['hasWallet']?->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;

						$agents_g = $this->user_model->getAllGeolocatedUsersForHyp($this->session->userdata('member_code'));

						//Fetch all transactions of any geolocated agent of the network
						$data["transactions"] = array();
						$totalCommissionBanque = 0;
						if ($agents_g) {
							foreach ($agents_g->result() as $row) {
								$wallet = $this->wallet_model->getWallet($row->agent_id);
								if ($wallet) {
									$transactions = $this->user_model->getAgentTransactions($wallet->first_row()->wallet_id);
									if ($transactions) {
										foreach ($transactions->result() as $trans) {
											$totalCommissionBanque += $trans->commission_banque;
											$trans->code_parrain = $row->code_parrain; // Add code parrain to transaction
											array_push($data['transactions'], $trans);
										}
									}
								}
							}
						}
						$data["totalCommissionBanque"] = Money::of(round($totalCommissionBanque,2), $this->session->userdata('currency_code'), $context )->formatTo('fr_FR');

					} elseif ($data['hasWallet']?->type == 'ilink') {

						$transactions = $this->wallet_model->getNetworkIlinTransactions($id_network);
						$data["transactions"] = array();
						$totalCommissionBanque = 0;
						if ($transactions) {
							foreach ($transactions->result() as $trans) {
								$totalCommissionBanque += $trans->commission_banque;
								array_push($data['transactions'], $trans);
							}
						}
						$data["totalCommissionBanque"] = Money::of(round($totalCommissionBanque,2), $this->session->userdata('currency_code'), $context )->formatTo('fr_FR');

					}

					//Create wallet if it not exist
					$res = $this->wallet_model->getWallet($agent_id);
					if ($res == false) {
						$this->user_model->addWallet($agent_id);
						$res = $this->wallet_model->getWallet($agent_id);
					}

					$row = $res->first_row();
					$data["commission"] = Money::of(round($row->balance_com, 2), $this->session->userdata('currency_code'), $context)->formatTo('fr_FR');
					$data["principal"] = Money::of(round($row->balance_princ, 2), $this->session->userdata('currency_code'), $context)->formatTo('fr_FR');
					$data['wallet_id'] = $row->wallet_id;
					$data['currency_code'] = $this->session->userdata('currency_code');


					$res = $this->wallet_model->getWalletPassword($id_network);
					$data['walletPassword'] = $res ? $res->first_row() : null;
					$data['alert'] = "";
					$data['active'] = "wallet_wallet";
					$data['pays'] = $this->user_model->getAllCountries();
					$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
					$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
					$data['firstname'] = $this->session->userdata('firstname');
					$data['lastname'] = $this->session->userdata('lastname');
					$data['email'] = $this->session->userdata('email');
					$data['network'] = $this->session->userdata('current_network');
					$data['contact_hyper'] = $this->session->userdata('current_contact_hyper');
					$data['network_id'] = $this->session->userdata('current_network_id');
					$data['country'] = $this->session->userdata('name_current_pays');

					$data['superviseurs'] = $this->user_model->getSuperNameAndCodeForHyp($this->session->userdata('current_hyper_member_code'));
					$data['agentWalletInfos'] = $this->user_model->getInfosWalletAgentForHyper($id_network);
					
					$this->load->view('header', $data);
					if ($data['hasWallet']?->type == 'visa')
						$this->load->view('gestion_wallet_hyp');
					elseif ($data['hasWallet']?->type == 'ilink')
						$this->load->view('gestion_wallet_ilink_hyp');
					$this->load->view('footer');
				}
			}
		}
	}

	private function historique($current_network_id, $startDate, $endDate, $type)
	{
		$data['configWallet'] = $this->wallet_model->getConfigWallet($current_network_id);
		$format = $this->session->userdata('site_lang') === 'french' ? 'd-m-Y' : 'Y-m-d';
		$data['startDate'] = $startDate ? date($format, strtotime($startDate)) : null;
		$data['endDate'] = $endDate ? date($format, strtotime($endDate)) : null;
		$endDate = Date('Y-m-d', strtotime($endDate . "+1 day"));
		if ($type == 'transaction_ilink') {
			$networkDetails = $this->user_model->getNetworkDetails($current_network_id);
			$data['currency_name_fr'] = $networkDetails->first_row()->currency_name_fr;
			$data['currency_name_en'] = $networkDetails->first_row()->currency_name_en;
		}else if ($type == 'deleted_transactions')
			$data['transactions'] = $this->user_model->getDeletedTransactions($startDate, $endDate, $this->session->userdata('current_network_id'));
		else if ($type == 'commission_transfer')
			$data['transactions'] = $this->wallet_model->getCommissionTransfersByNetwork($startDate, $endDate, $this->session->userdata('current_network_id'));
		else if ($type == 'balance_statement'){
			$res = $this->wallet_model->getWalletPassword($this->session->userdata('current_network_id'));
			$data['walletPassword'] = $res ? $res->first_row() : null;

			$data['wallets'] = $this->user_model->getInfosWalletAgentForHyper($this->session->userdata('current_network_id'));

		} else if ($type == 'refund_history')
			$data['refunds'] = $this->wallet_model->getRefunds($startDate, $endDate, $current_network_id);
		else if ($type == 'commission_payments')
			$data['payments'] = $this->wallet_model->getCommissionPayments($startDate, $endDate, $current_network_id);
		else
			$data['transactions'] = $this->wallet_model->getRecharges($startDate, $endDate, $current_network_id);

		$data['active'] = "wallet_wallet";
		$data['alert'] = "";
		$data['pays'] = $this->user_model->getAllCountries();
		$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
		$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
		$data['firstname'] = $this->session->userdata('firstname');
		$data['lastname'] = $this->session->userdata('lastname');
		$data['email'] = $this->session->userdata('email');
		$data['network'] = $this->session->userdata('current_network');
		$data['contact_hyper'] = $this->session->userdata('current_contact_hyper');
		$data['network_id'] = $this->session->userdata('current_network_id');
		$data['country'] = $this->session->userdata('name_current_pays');
		$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));
		$data['currency_code'] = $this->session->userdata('currency_code');

		$data['category'] = $this->session->userdata('category');
		$data['id_network'] = $current_network_id;

		$this->load->view('header', $data);
		if ($type == 'transaction')
			$this->load->view('historique_transactions');
		else if ($type == 'transaction_ilink')
			$this->load->view('historique_transactions_ilink');
		else if ($type == 'deleted_transactions')
			$this->load->view('historique_transactions_deleted');
		else if ($type == 'commission_transfer')
			$this->load->view('historique_transferts_commission');
		else if ($type == 'balance_statement')
			$this->load->view('config_wallet_ilink_hyp/etat_soldes');
		else if ($type == 'refund_history')
			$this->load->view('historique_remboursement');
		else if ($type == 'commission_payments')
			$this->load->view('config_wallet_ilink_hyp/historique_commission_payements');
		else
			$this->load->view('historique_recharges');
		$this->load->view('footer');
	}

	public function walletPassword()
	{
		if ($this->isLogged()) {
			$data['active'] = "wallet_password";
			$data['alert'] = "";
			$data['pays'] = $this->user_model->getAllCountries();
			$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
			$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
			$data['firstname'] = $this->session->userdata('firstname');
			$data['lastname'] = $this->session->userdata('lastname');
			$data['email'] = $this->session->userdata('email');
			$data['network'] = $this->session->userdata('current_network');
			$data['contact_hyper'] = $this->session->userdata('current_contact_hyper');
			$data['network_id'] = $this->session->userdata('current_network_id');
			$data['country'] = $this->session->userdata('name_current_pays');
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));
			$data['currency_code'] = $this->session->userdata('currency_code');

			$res = $this->wallet_model->getWalletPassword($this->session->userdata('current_network_id'));
			$data['walletPassword'] = $res ? $res->first_row() : null;
			$this->load->view('header', $data);
			$this->load->view('wallet_password');
			$this->load->view('footer');
		}
	}

	private function config_wallet($config , $country)
	{
		//$data['configWallet'] = $this->wallet_model->getConfigWallet($network_id);
		$data['active'] = "wallet_wallet";
		$data['alert'] = "";
		$data['pays'] = $this->user_model->getAllCountries();
		$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
		$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
		$data['firstname'] = $this->session->userdata('firstname');
		$data['lastname'] = $this->session->userdata('lastname');
		$data['email'] = $this->session->userdata('email');
		$data['network'] = $this->session->userdata('current_network');
		$data['contact_hyper'] = $this->session->userdata('current_contact_hyper');
		$data['network_id'] = $this->session->userdata('current_network_id');
		$data['country'] = $this->session->userdata('name_current_pays');
		$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));
		$data['currency_code'] = $this->session->userdata('currency_code');

		$data['category'] = $this->session->userdata('category');
		$data['idConfig'] = $data['hasWallet']?->id;
		$data['network_id'] = $this->session->userdata('current_network_id');
		if (isset($country)) {
			$data['country_id'] = $country;
			$data['country'] = $this->wallet_model->getCountry($country)->first_row();
			$res = $this->wallet_model->getActiveNetworksByCountry($country,$this->session->userdata('current_network_id'));
			$data['networks'] = [];
			if($res){
				$result = $res->result();
				foreach ($result as $network){
					if($network->type == 'ilink_sante'){
						continue;
					}
					$res = $this->wallet_model->getSharingRate($network->id , $data['idConfig']);
					$res2 = $this->wallet_model->getTransmittingNetwork($network->id , $data['idConfig']);
					if($res){
						$network->rate = $res->first_row()->taux_partage;
						$network->url = $res->first_row()->url;
					}else{
						$network->rate = null;
						$network->url = null;
					}
					$network->is_transmitting_network = $res2 ? true : false;
					$network->rate_transmitting = $res2 ? $res2->first_row()->taux_partage : null;
					$network->url_transmitting = $res2 ? $res2->first_row()->url : null;

					$data['networks'][] = $network;
				}
			}
			$this->load->view('header', $data);
			$this->load->view('gestion_wallet_ilink_config_paying_network');
			$this->load->view('footer');
			return;
		}
		$res = $this->wallet_model->getWalletsCountries();
		$data['countries'] = [];
		if($res){
			$result = $res->result();
			foreach ($result as $country){
				$res = $this->wallet_model->countPayingNetworks($country->id, $data['idConfig']);
				$res2 = $this->wallet_model->countTransmittiongNetworks($country->id, $data['idConfig']);

				$country->total_paying = $res ? $res->first_row()->total : null ;
				$country->total_transmitting = $res ? $res2->first_row()->total : null ;

				$data['countries'][] = $country;
			}
		}
		$taux = $data['hasWallet'];
		switch($config){
			case 'paying_networks':
				$this->load->view('header', $data);
				$this->load->view('gestion_wallet_ilink_config_paying_networks');
				break;
			case 'user_wallet_wallet':
				$data['plr_user_wallet_wallet'] = $this->wallet_model->getPalierConfigWallet("user_wallet_wallet_international", $data['idConfig']);
				$data['plr_user_wallet_wallet_national'] = $this->wallet_model->getPalierConfigWallet("user_wallet_wallet_national", $data['idConfig']);
				$this->load->view('header', $data);
				$this->load->view('config_wallet_ilink_hyp/user_wallet_wallet');
				break;
			case 'user_wallet_carte':
				$data['plr_user_wallet_cart_national'] = $this->wallet_model->getPalierCommissionsWallet("user_wallet_cart_national", $data['idConfig']);
				$data['plr_hyp_user_wallet_cart_national'] = $this->wallet_model->getPalierCommissionsWallet("hyp_user_wallet_cart_national", $data['idConfig']);
				$data['plr_bank_user_wallet_cart_national'] = $this->wallet_model->getPalierCommissionsWallet("bank_user_wallet_cart_national", $data['idConfig']);
				$this->load->view('header', $data);
				$this->load->view('config_wallet_ilink_hyp/user_wallet_carte');
				break;
			case 'user_wallet_cash':
				$data['plr_user_wallet_cash'] = $this->wallet_model->getPalierConfigWallet("user_wallet_cash_international", $data['idConfig']);
				$data['plr_user_wallet_cash_national'] = $this->wallet_model->getPalierConfigWallet("user_wallet_cash_national", $data['idConfig']);
				$this->load->view('header', $data);
				$this->load->view('config_wallet_ilink_hyp/user_wallet_cash');
				break;
			case 'user_carte_wallet':
				$data['plr_user_cart_wallet_national'] = $this->wallet_model->getPalierCommissionsWallet("user_cart_wallet_national", $data['idConfig']);

				$data['plr_user_cart_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("user_cart_cash_national", $data['idConfig']);

				$data['plr_hyp_user_cart_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("hyp_user_cart_cash_national", $data['idConfig']);

				$data['plr_bank_user_cart_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("bank_user_cart_cash_national", $data['idConfig']);

				$this->load->view('header', $data);
				$this->load->view('config_wallet_ilink_hyp/user_carte_wallet');
				break;
						case 'user_cart_autre_wallet':
				$data['plr_user_cart_autre_wallet_national'] = $this->wallet_model->getPalierCommissionsWallet("user_cart_autre_wallet_national", $data['idConfig']);
				$data['plr_user_cart_autre_wallet_international'] = $this->wallet_model->getPalierCommissionsWallet("user_cart_autre_wallet_international", $data['idConfig']);

				$data['plr_bank_user_cart_autre_wallet_national'] = $this->wallet_model->getPalierCommissionsWallet("bank_user_cart_autre_wallet_national", $data['idConfig']);
				$data['plr_bank_user_cart_autre_wallet_international'] = $this->wallet_model->getPalierCommissionsWallet("bank_user_cart_autre_wallet_international", $data['idConfig']);

				$this->load->view('header', $data);
				$this->load->view('config_wallet_ilink_hyp/user_carte_autre_wallet');
				break;
			case 'agent_remove_cash':
				$data['plr_agent_wallet_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("agent_wallet_cash_national", $data['idConfig']);
				$data['plr_agent_wallet_cash_international'] = $this->wallet_model->getPalierCommissionsWallet("agent_wallet_cash_international", $data['idConfig']);

				$data['plr_sup_wallet_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("sup_wallet_cash_national", $data['idConfig']);
				$data['plr_sup_wallet_cash_international'] = $this->wallet_model->getPalierCommissionsWallet("sup_wallet_cash_international", $data['idConfig']);

				$data['plr_customer_wallet_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("customer_wallet_cash_national", $data['idConfig']);
				$data['plr_customer_wallet_cash_international'] = $this->wallet_model->getPalierCommissionsWallet("customer_wallet_cash_international", $data['idConfig']);

				$this->load->view('header', $data);
				$this->load->view('config_wallet_ilink_hyp/agent_remove_cash');
				break;
			case 'agent_remove_carte_cash':
				$data['plr_customer_cart_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("customer_cart_cash_national", $data['idConfig']);

				$data['plr_agent_cart_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("agent_cart_cash_national", $data['idConfig']);

				$data['plr_sup_cart_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("sup_cart_cash_national", $data['idConfig']);

				$data['plr_hyp_cart_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("hyp_cart_cash_national", $data['idConfig']);

				$data['plr_bank_cart_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("bank_cart_cash_national", $data['idConfig']);

				$this->load->view('header', $data);
				$this->load->view('config_wallet_ilink_hyp/agent_remove_carte_cash');
				break;
			case 'agent_send_cash_carte':
				$data['plr_customer_cash_cart_national'] = $this->wallet_model->getPalierCommissionsWallet("customer_cash_cart_national", $data['idConfig']);

				$data['plr_agent_cash_cart_national'] = $this->wallet_model->getPalierCommissionsWallet("agent_cash_cart_national", $data['idConfig']);

				$data['plr_sup_cash_cart_national'] = $this->wallet_model->getPalierCommissionsWallet("sup_cash_cart_national", $data['idConfig']);

				$data['plr_hyp_cash_cart_national'] = $this->wallet_model->getPalierCommissionsWallet("hyp_cash_cart_national", $data['idConfig']);$data['plr_hyp_cash_cart_international'] = $this->wallet_model->getPalierCommissionsWallet("hyp_cash_cart_international", $data['idConfig']);

				$data['plr_bank_cash_cart_national'] = $this->wallet_model->getPalierCommissionsWallet("bank_cash_cart_national", $data['idConfig']);

				$this->load->view('header', $data);
				$this->load->view('config_wallet_ilink_hyp/agent_send_cash_carte');
				break;
			case 'agent_send_cash_canal':
				$data['plr_agent_cash_wallet_or_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("agent_cash_wallet_or_cash_national", $data['idConfig']);
				$data['plr_agent_cash_wallet_or_cash_international'] = $this->wallet_model->getPalierCommissionsWallet("agent_cash_wallet_or_cash_international", $data['idConfig']);
				$data['plr_sup_cash_wallet_or_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("sup_cash_wallet_or_cash_national", $data['idConfig']);
				$data['plr_sup_cash_wallet_or_cash_international'] = $this->wallet_model->getPalierCommissionsWallet("sup_cash_wallet_or_cash_international", $data['idConfig']);
				//				$data['plr_hyp_cash_wallet_or_cash_national'] = $this->wallet_model->getPalierCommissionsWallet("hyp_cash_wallet_or_cash_national", $data['idConfig']);
				//				$data['plr_hyp_cash_wallet_or_cash_international'] = $this->wallet_model->getPalierCommissionsWallet("hyp_cash_wallet_or_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_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']);
				$this->load->view('header', $data);
				$this->load->view('config_wallet_ilink_hyp/agent_send_cash_canal');
				break;
			case 'taxes':
				$data['taxes'] = $this->wallet_model->getTaxes($data['idConfig']);
				$this->load->view('header', $data);
				$this->load->view('config_wallet_ilink_hyp/taxes');
				break;
			case 'customers_accounts':
				$data['types'] = $this->db->select('t.* , p.name as parent')
					->from('customer_account_types t')->join('customer_account_types p', 't.parent_id = p.id','left')->get()->result();
				foreach ($data['types'] as $i => $type){
					$data['types'][$i]->documents = $this->db->get_where('customer_account_type_documents',['account_type_id' => $type->id])->result();
				}
				$this->load->view('header', $data);
				$this->load->view('config_wallet_ilink_hyp/customers_accounts');
				break;
		}
		$this->load->view('footer');
	}

	private function show_config_infos($type)
	{

		$data['active'] = "wallet_wallet";
		$data['alert'] = "";
		$data['pays'] = $this->user_model->getAllCountries();
		$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
		$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
		$data['firstname'] = $this->session->userdata('firstname');
		$data['lastname'] = $this->session->userdata('lastname');
		$data['email'] = $this->session->userdata('email');
		$data['network'] = $this->session->userdata('current_network');
		$data['contact_hyper'] = $this->session->userdata('current_contact_hyper');
		$data['network_id'] = $this->session->userdata('current_network_id');
		$data['country'] = $this->session->userdata('name_current_pays');
		$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));
		$data['currency_code'] = $this->session->userdata('currency_code');

		$data['category'] = $this->session->userdata('category');
		$data['idConfig'] = $data['hasWallet']?->id;
		$res = $this->wallet_model->getWalletPassword($this->session->userdata('current_network_id'));
		$data['walletPassword'] = $res ? $res->first_row() : null;
		$data['networks'] = $this->wallet_model->getPayingNetworksByConfigWallet($data['idConfig']);
		$data['transmitting_networks'] = $this->wallet_model->getTransmittingNetworksByConfigWallet($data['idConfig']);

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

	public function config_sharing_rate(){
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$network_id = $_POST['network_id'];
				$config_id = $_POST['config_id'];
				$rate = $_POST['rate'];
				$url = $_POST['url'];
				$res = $this->wallet_model->setSharingRate($network_id, $config_id, $rate, $url);

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

			}
		}
	}

	public function nano_credit()
	{
		if ($this->isLogged()) {
			$data['network_id'] = $this->session->userdata('current_network_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('config')) {
				$this->config_nano_credit($this->input->get('config'));
			} elseif ($this->input->get('group')) {
				$this->users_group_details($this->input->get('group'));
			} else {
				$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));
				$data['groups'] = $this->nano_credit_model->getUsersGroups($this->session->userdata('current_network_id'));
				$data['idConfig'] = $data['hasWallet']?->id;
				$data['rates'] = $this->nano_credit_model->getNanoCreditRates($data['idConfig']);
				$data['taxes'] = $this->wallet_model->getTaxes($data['idConfig'], 'nano_credit');
				$data['active'] = "nano_credit";
				$data['alert'] = "";
				$data['pays'] = $this->user_model->getAllCountries();
				$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
				$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
				$data['firstname'] = $this->session->userdata('firstname');
				$data['lastname'] = $this->session->userdata('lastname');
				$data['email'] = $this->session->userdata('email');
				$data['network'] = $this->session->userdata('current_network');
				$data['contact_hyper'] = $this->session->userdata('current_contact_hyper');
				$data['network_id'] = $this->session->userdata('current_network_id');
				$data['country'] = $this->session->userdata('name_current_pays');
				$data['currency_code'] = $this->session->userdata('currency_code');
				$data['configWallet'] = $data['hasWallet'];

				$this->load->view('header', $data);
				$this->load->view('nano_credit/gestion_nano_credit_hyp');
				$this->load->view('footer');
			}
		}
	}

	private function config_nano_credit($config)
	{
//		$data['configWallet'] = $this->wallet_model->getConfigWallet($network_id);
		$data['active'] = "nano_credit";
		$data['alert'] = "";
		$data['pays'] = $this->user_model->getAllCountries();
		$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
		$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
		$data['firstname'] = $this->session->userdata('firstname');
		$data['lastname'] = $this->session->userdata('lastname');
		$data['email'] = $this->session->userdata('email');
		$data['network'] = $this->session->userdata('current_network');
		$data['contact_hyper'] = $this->session->userdata('current_contact_hyper');
		$data['network_id'] = $this->session->userdata('current_network_id');
		$data['country'] = $this->session->userdata('name_current_pays');
		$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));
		$data['currency_code'] = $this->session->userdata('currency_code');

		$data['category'] = $this->session->userdata('category');
		$data['idConfig'] = $data['hasWallet']?->id;
		switch ($config) {
			case 'nano_credit':
				$taux = $data['hasWallet'];
				$data['taux_ag_nano_credit'] = $taux->taux_com_ag_nano_credit;
				$data['taux_sup_nano_credit'] = $taux->taux_com_sup_nano_credit;
				$data['taux_hyp_nano_credit'] = $taux->taux_com_hyp_nano_credit;
				$data['rates'] = $this->nano_credit_model->getNanoCreditRates($data['idConfig']);
				$data['taxes'] = $this->wallet_model->getTaxes($data['idConfig'], 'nano_credit');
				$this->load->view('header', $data);
				$this->load->view('nano_credit/config_nano_credit');
				break;

			case 'epargne':
				$data['rates'] = $this->nano_credit_model->getNanoCreditRates($data['idConfig'], 'epargne');
				$data['taxes'] = $this->wallet_model->getTaxes($data['idConfig'], 'epargne');
				$this->load->view('header', $data);
				$this->load->view('nano_credit/config_savings');
				break;
		}
		$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"));
		$data['currency_code'] = $this->session->userdata('currency_code');

		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['pays'] = $this->user_model->getAllCountries();
		$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
		$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
		$data['firstname'] = $this->session->userdata('firstname');
		$data['lastname'] = $this->session->userdata('lastname');
		$data['email'] = $this->session->userdata('email');
		$data['network'] = $this->session->userdata('current_network');
		$data['contact_hyper'] = $this->session->userdata('current_contact_hyper');
		$data['network_id'] = $this->session->userdata('current_network_id');
		$data['country'] = $this->session->userdata('name_current_pays');
		$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));
		$data['currency_code'] = $this->session->userdata('currency_code');

		$data['category'] = $this->session->userdata('category');
		$data['id_network'] = $this->session->userdata('current_network_id');

		$this->load->view('header', $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($group_code)
	{
		$data['active'] = "nano_credit";
		$data['alert'] = "";
		$data['pays'] = $this->user_model->getAllCountries();
		$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
		$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
		$data['firstname'] = $this->session->userdata('firstname');
		$data['lastname'] = $this->session->userdata('lastname');
		$data['email'] = $this->session->userdata('email');
		$data['network'] = $this->session->userdata('current_network');
		$data['contact_hyper'] = $this->session->userdata('current_contact_hyper');
		$data['network_id'] = $this->session->userdata('current_network_id');
		$data['country'] = $this->session->userdata('name_current_pays');
		$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));
		$data['currency_code'] = $this->session->userdata('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', $data);
		$this->load->view('nano_credit/users_group_detail');
		$this->load->view('footer');
	}

	public function operators()
	{

		if ($this->isLogged()) {

			$data['active'] = "operators";
			$data['alert'] = "";
			$data['pays'] = $this->user_model->getAllCountries();
			$data['hyper'] = $this->user_model->getAllHyper($data['pays']->first_row()->id);
			$data['ville'] = $this->user_model->getVilleNetworkByHyper($data['hyper']->first_row()->code_membre);
			$data['firstname'] = $this->session->userdata('firstname');
			$data['lastname'] = $this->session->userdata('lastname');
			$data['email'] = $this->session->userdata('email');
			$data['network'] = $this->session->userdata('current_network');
			$data['contact_hyper'] = $this->session->userdata('current_contact_hyper');
			$data['network_id'] = $this->session->userdata('current_network_id');
			$data['country'] = $this->session->userdata('name_current_pays');
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('current_network_id'));
			$data['currency_code'] = $this->session->userdata('currency_code');
			$data['category'] = $this->session->userdata('category');

			$data['operators'] = $this->wallet_model->getOperatorsForNetwork($this->session->userdata('current_network_id'));


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

	public function documentation($route = null)
	{
		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 (isset($route) && $route = 'page') {
				if ($this->input->get('view')) {
					switch ($this->input->get('view')){
						case 'walletServiceInterne' :
							$data['link'] = WALLET_SERVICE_URL.'/api/documentation';
							break;
						case 'walletServiceExterne' :
							$data['link'] = WALLET_SERVICE_EXTERNE_URL.'/api/documentation';
							break;
						case 'backoffice':
							$data['link'] = base_url('docs/html/index.html');
							break;
						default:
							$data['link'] = '#';
							break;
					}

					$this->load->view('documentation/docs-iframe', $data);
				} else {
					$this->load->view('documentation/docs-page');
				}
			} else {
				$this->load->view('documentation/index');
			}

		}
	}

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

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

			redirect('index.php', $data);
			return false;
		}
		return true;
	}

		public function recharge_wallet()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$password = $_POST['password'];
				$wallet_id = $_POST['wallet_id'];
				$salt = $_POST['salt'];
				$encrypted_password = $_POST['encrypted_password'];
				$montant = $_POST['montant'];

				$hash = base64_encode(sha1($password . $salt, true) . $salt);

				if ($encrypted_password == $hash) {
					$this->wallet_model->updateWalletBalance($montant, $wallet_id);
					$res = $this->wallet_model->addWalletRecharge($montant, $wallet_id , $this->session->userdata('network_id'));
					$code = $res ? '200' : '500';
				} else {
					$code = '400';
				}

				echo json_encode($code);

			}
		}
	}
}
