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

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

use function PHPSTORM_META\type;

/**
 * Created by PhpStorm.
 * User: Hanry Nzale
 * Date: 03/08/2018
 * Time: 02:03
 */
class Hyperviseur_dash extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->model('wallet_model');
		$this->load->model('nano_credit_model');
	}

	public function index()
	{
		if ($this->isLogged()) {
			$count_d_traite = $this->user_model->getCountDemandeByStatut($this->session->userdata('member_code'), '1');
			$count_d_no_traite = $this->user_model->getCountDemandeByStatut($this->session->userdata('member_code'), '0');
			$count_d_no_canceled = $this->user_model->getCountDemandeByStatut($this->session->userdata('member_code'), '2');
			$count_d = $this->user_model->getCountDemande($this->session->userdata('member_code'));

			$data['active'] = "dash";
			$data['list_geolocated_users'] = $this->user_model->getAllGeolocatedUsersForHyp($this->session->userdata('member_code'));
			$data['listdem'] = $this->user_model->getDemandes($this->session->userdata('member_code'));
			$data['allGeo'] = $this->user_model->getAllUserGeoForHyp($this->session->userdata('member_code'));
			$data['allDem'] = $this->user_model->getDemandes($this->session->userdata('member_code'));
			$data['member_code'] = $this->session->userdata('member_code');
			$data['category'] = $this->session->userdata('category');
			$data['network'] = $this->session->userdata('network');

			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));
			$data['count_geo'] = $this->user_model->countUserGeoForHyp($this->session->userdata('member_code'));
			$data['count_sup'] = $this->user_model->countUser("super", 'all', $this->session->userdata('member_code'));
			$data['count_d_traite'] = $count_d_traite;
			$data['count_d_no_traite'] = $count_d_no_traite;
			$data['count_d_no_canceled'] = $count_d_no_canceled;
			$data['count_d_users'] = $count_d;
			$data['networks'] = $this->user_model->getNetworkByHyp($this->session->userdata('member_code'));
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$this->load->view('header_hyp', $data);
			$this->load->view('hyperviseur_dash');
			$this->load->view('footer');
		}
	}

	public function getAllUser_g()
	{

		if ($this->isLogged()) {
			if ($this->input->post('ville')) {
				$town = $this->db->get_where('towns',['id' => $this->input->post('ville')])->first_row();
				$this->session->set_userdata('current_ville', $town->name);
			}
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));

			$data['active'] = "geolocated";
			$data['total_points'] = $this->user_model->getCoutGeolocatedUsersForHyper($this->session->userdata('member_code'), $this->session->userdata('current_ville'));
			$data['map_title'] = $this->lang->line($data['hasWallet']?->type == 'ilink_sante' ? 'service_providers_to' :'utilisateurs géolocalisés à') . " " . $this->session->userdata('current_ville');
			$data['positions'] = $this->user_model->getUsersGeolocatedPositionByVilleForHyp($this->session->userdata('current_ville'), $this->session->userdata('member_code'));
			$data['latitude'] = $this->session->userdata('latitude');
			$data['longitude'] = $this->session->userdata('longitude');
			$data['code_parrain'] = $this->session->userdata('code_parrain');
			$data['category'] = 'geolocated';
			$data['network'] = $this->session->userdata('network');
			$data['network_id'] = $this->session->userdata('network_id');
			$data['town_id'] = isset($town) ? $town->id : null;

			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));
			$data['networks'] = $this->user_model->getNetworkByHyp($this->session->userdata('member_code'));
			$data['alert'] = "";


			if($data['hasWallet']?->type == 'ilink_sante'){
				$nh_config = $this->nano_health_model->getConfig($data['network_id']);
				$data['nh_config'] = $nh_config ? $nh_config->first_row() : null ;
				$data['provider_classes'] = $this->nano_health_model->getProviderClasses($data['nh_config'] ? $data['nh_config']->id : null);

				$this->load->view('header_hyp', $data);
				$this->load->view('nano_health/hyper/listeadmin');
			}else{

				$data['tab'] = $this->user_model->getUsersGeolocatedByVilleForHyp($this->session->userdata('current_ville'), $this->session->userdata('member_code'));
				$this->load->view('header_hyp', $data);
				$this->load->view('listeadmin');
			}
			$this->load->view('footer');
		}

	}

	public function fetchSuper(){
		if ($this->isLogged()) {
			$code_membre = $this->input->post('code_membre');
			$super = $this->db->get_where('agent_plus',['code_membre' => $code_membre])->first_row();
			echo json_encode($super);
		}
	}

	public function getAllSupervisor()
	{
		if ($this->isLogged()) {
			/*$this->db->select('*');
			$this->db->from('users');
			$this->db->where('category','super');
			$this->db->where('network',$this->session->userdata('network'));
			$this->db->where('code_parrain',$this->session->userdata('code_parrain'));*/
			$query = $this->user_model->getSupervisorsForHyp($this->session->userdata('member_code'));

			$network = $this->session->userdata('network');
			$category = 'super';
			$position = $this->user_model->getAllpositions($network, $category, $this->session->userdata('member_code'));
//			if ($position != null) {
				//var_dump($position);
				//echo json_encode($position);
//			}
			$data['total_points'] = $this->user_model->getCoutSuperForHyper($this->session->userdata('member_code'));
			$data['positions'] = $position;
			$data['active'] = "super";
			$data['map_title'] = $this->lang->line('Superviseurs');
			$data['tab'] = $query;
			$data['latitude'] = $this->session->userdata('latitude');
			$data['longitude'] = $this->session->userdata('longitude');
			$data['code_parrain'] = $this->session->userdata('code_parrain');
			$data['category'] = $this->session->userdata('category');
			$data['network'] = $this->session->userdata('network');
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

			$data['networks'] = $this->user_model->getNetworkByHyp($this->session->userdata('member_code'));
			$data['alert'] = "";
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$this->load->view('header_hyp', $data);
			$this->load->view('listeadmin');
			$this->load->view('footer');
		}
	}

	public function getAllSupervisorPositions()
	{
		if ($this->isLogged()) {
			$network = $this->session->userdata('network');
			$category = 'super';

			$position = $this->user_model->getAllpositions($network, $category, $this->session->userdata('member_code'));
			if ($position != null) {
				return $position;
			}
		}
	}

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

			$debut = $this->input->get("d");
			$fin = $this->input->get("f");
			$format = $this->session->userdata('site_lang') === 'french' ? 'd-m-Y' : 'Y-m-d';
			$data['debut'] = $debut ? date($format, strtotime($debut)) : null;
			$data['fin'] = $fin ? date($format, strtotime($fin)) : null;
			$fin = Date('Y-m-d', strtotime($fin . "+1 day"));

			$ville = $this->session->userdata('ville');
			$data['active'] = "demandes_credits_entrantes";
			$data['type'] = 'incoming';
			$data['demand_type'] = 'credit';
			$data['alert'] = "";
			$data['code_parrain'] = $this->session->userdata('code_parrain');
			$data['category'] = $this->session->userdata('category');
			$data['network'] = $this->session->userdata('network');
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

			$data['tab_fastDemande'] = $this->user_model->getRangeASCDemandesByNetwork($debut, $fin, $this->session->userdata('member_code'), $this->session->userdata('current_demande_ville'));
			$data['tab_slowDemande'] = $this->user_model->getRangeDESCDemandesByNetwork($debut, $fin, $this->session->userdata('member_code'), $this->session->userdata('current_demande_ville'));
			$data['list'] = $this->user_model->getDemandesBySuper($debut, $fin, $this->session->userdata('member_code'));
			$data['temp_moyen'] = $this->user_model->getTempsMoyenByVille($this->session->userdata('member_code'), $this->session->userdata('network'));
			$data['networks'] = $this->user_model->getNetworkByHyp($this->session->userdata('member_code'));
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$this->load->view('header_hyp', $data);
			$this->load->view('demande_credit');
			$this->load->view('footer');

		}
	}

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

			$show = $this->input->get("show");

			$debut = $this->input->get("d");
			$fin = $this->input->get("f");
			$format = $this->session->userdata('site_lang') === 'french' ? 'd-m-Y' : 'Y-m-d';
			$data['debut'] = $data['startDate'] = $debut ? date($format, strtotime($debut)) : null;
			$data['fin'] =  $data['endDate'] =$fin ? date($format, strtotime($fin)) : null;
			$fin = Date('Y-m-d', strtotime($fin . "+1 day"));


			$data['active'] = "demandes_credits_annulation";
			$data['type'] = 'incoming';
			$data['demand_type'] = 'credit';
			$data['alert'] = "";
			$data['code_parrain'] = $this->session->userdata('code_parrain');
			$data['category'] = $this->session->userdata('category');
			$data['network'] = $this->session->userdata('network');
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));
			$data['id_network'] = $this->session->userdata('network_id');

			if($show == 'history'){
				$data['list'] = $this->user_model->getAllCanceledCreditsDemands($debut, $fin, $this->session->userdata('network_id'));
			}else{
				$data['temp_moyen'] = $this->user_model->getTempsMoyenByNetwork($this->session->userdata('network_id'));
			}
			$data['networks'] = $this->user_model->getNetworkByHyp($this->session->userdata('member_code'));
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$this->load->view('header_hyp', $data);
			if($show == 'history'){
				$this->load->view('historique_demande_credit_annulation');
			}else{
				$this->load->view('demande_credit_annulation');
			}

			$this->load->view('footer');

		}
	}

	public function cancelCreditRequest(){
		if ($this->isLogged()) {
			$datetime = $this->user_model->getCurrentTimeByNetworkID($this->session->userdata('network_id'));
			$data = array(
				'canceled_by_hypervisor' => 1 ,
				'cancellation_date' => $datetime
			);
			$id = $this->input->post('id_demand');
			$query = $this->db->get_where('info_demandeCredits', ['demande_id' => $id]);

			if($query->num_rows()>0){
				$demand = $query->first_row();

				// Debiter le compte de l'agent
				$this->db->set('balance_princ', 'balance_princ-'.$demand->montant,false);
				$this->db->where('id_networkAgent',$demand->network_agent_id);
				$this->db->update('wallets');

				// Credit le compte du parrain
				$this->db->set('balance_princ', 'balance_princ+'.$demand->montant,false);
				$this->db->where('id_networkAgent',$demand->network_parrain_id);
				$this->db->update('wallets');

				$this->db->where('id', $id);
				$query = $this->db->update('demandeCredits', $data);

				try {
					$message = line_with_arguments($this->lang->line('credit_request_canceled_by_hypervisor_message'), array($id,$demand->montant));
					//Send email
//					$this->load->library('email');
//					$this->email->from('noreply@ilink-app.com', 'iLink World');
//					$this->email->to(array($demand->email_agent,$demand->email_parrain));
//
//					$this->email->subject($this->lang->line('credit_request_canceled_by_hypervisor'));
//					$this->email->message($message);
//					$this->email->send() ;

					/* API URL */
					$url = NOTIFICATION_SERVICE_URL . '/onesignal/pushToAgent' ;

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

					curl_setopt($ch, CURLOPT_POST, 1);

					/* set the content type json */
					curl_setopt($ch, CURLOPT_HTTPHEADER, array(
						'Content-Type:application/json',
						'Authorization:'.NOTIFICATION_SERVICE_TOKEN,
						'X-localization:'. $this->session->userdata('site_lang') == 'french' ? 'fr' : 'en'
					));

					$data = new \stdClass();
					$data->screen = "Historique";
					$data->data = new \stdClass();
					$data->data->id = $id;

					$body = new \stdClass();
					$body->agent_code = $demand->codeMembre;
					$body->message = $message;
					$body->data = $data;
					$body->date = $datetime;

					curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));

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

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

					$body->agent_code = $demand->codeParrain;

					curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));

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

				}catch (\Throwable $e){

				}

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

			}else{
				echo json_encode("404");
			}

		}
	}

	public function addvilles()
	{
		$id = 1;
		$date = "2018-08-29";
		for ($i = 1; $i <= 267; $i++) {
			$newdate = date("Y-m-d", strtotime($date . " + 1 day + 1 hour"));
			$data = array(
				'dateAjout' => $date,
				'dateModif' => $newdate,
			);


			$newdate = date("Y-m-d", strtotime($date . " + 1 day + 3 hour"));
			$date = $newdate;

			$this->db->update('demande_superviseur', $data);
		}
	}

	public function getDemandesAd()
	{
		if ($this->isLogged()) {
			$network = $this->session->userdata('network');
			$debut = $this->input->get("d");
			$fin = $this->input->get("f");
			$format = $this->session->userdata('site_lang') === 'french' ? 'd-m-Y' : 'Y-m-d';
			$data['debut'] = $debut ? date($format, strtotime($debut)) : null;
			$data['fin'] = $fin ? date($format, strtotime($fin)) : null;
			$data['demand_type'] = 'adhesion';
			$data['active'] = "demandesAd";
			$data['alert'] = "";
			$data['code_parrain'] = $this->session->userdata('code_parrain');
			$data['category'] = $this->session->userdata('category');
			$data['network'] = $this->session->userdata('network');
			$data['tab_fastDemande'] = $this->user_model->getRangeASCDemandesAd($debut, $fin, $this->session->userdata('member_code'));
			$data['tab_slowDemande'] = $this->user_model->getRangeDESCDemandesAd($debut, $fin, $this->session->userdata('member_code'));
			$data['temp_moyen'] = $this->user_model->getTempsMoyenAd($debut, $fin, $this->session->userdata('member_code'));
			$data['list'] = $this->user_model->getDemandesAdForSuper($debut, $fin, $this->session->userdata('member_code'));
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

			$data['networks'] = $this->user_model->getNetworkByHyp($this->session->userdata('member_code'));
			$data['type'] = $this->lang->line('Adhésion');
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$this->load->view('header_hyp', $data);
			$this->load->view('demande_adhesion');
			$this->load->view('footer');
		}
	}

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

			$res = $this->wallet_model->getWalletPassword($id_network);
			$data['walletPassword'] = $res ? $res->first_row() : null;
			$data['alert'] = "";
			$data['active'] = "wallet_wallet";
			$data['code_parrain'] = $this->session->userdata('code_parrain');
			$data['category'] = $this->session->userdata('category');
			$data['network'] = $this->session->userdata('network');
			$data['network_id'] = $id_network;
			$data['country'] = $this->session->userdata('current_pays');
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

			if ($data['hasWallet']) {

				if ($this->input->get('history')) {
					if($this->input->get('id') !== null){
						$history = $this->input->get('history');
						if($history == 'insurance-insured'){
							$data['active'] = "wallet_insured";
							$data['insured_id'] = $this->input->get('id');
							$data['insurance'] = $this->nano_health_model->getInfosInsuredById($this->input->get('id'));
							$data['beneficiaries'] = $this->nano_health_model->getInsuranceBeneficiaries($data['insurance']->id ?? null);
							$data['user'] = $this->db->get_where('user_infos',['user_id' => $data['insurance']->user_id ?? null])->first_row();
							$data['payments'] = $this->nano_health_model->getInsurancePaymentTransactions($data['insurance']->id ?? null);
							// Le montant payé de toutes les factures de l'assurance
							$data['insurance_invoices_total_paid_amount'] = $this->nano_health_model->getInsuranceInvoiceTotalPaidAmount($data['insurance']->id ?? null);
							$data['insurance_invoices_total_amount'] = $this->nano_health_model->getInsuranceInvoiceTotalAmount($data['insurance']->id ?? null);
							$data['invoices'] = $this->nano_health_model->getInsuranceInvoices($this->input->get('id'));
							$data['deletion_of_beneficiaries'] = $this->nano_health_model->getBeneficiariesDeletionHistory($data['insurance']->id ?? null);

							$this->load->view('header_hyp', $data);
							$this->load->view('nano_health/hyper/infos_insurance');
						}else if($history == 'insurance-subscriptions'){
							$data['insurance_subscription_id'] = $this->input->get('id');
							$data['subscription'] = $this->nano_health_model->getInfosInsuranceSubscriptionById($this->input->get('id'));
							$data['beneficiaries'] = $this->nano_health_model->getSubscriptionBeneficiaries($data['subscription']->id ?? null);
							$data['user'] = $this->db->get_where('user_infos',['user_id' => $data['subscription']->user_id ?? null])->first_row();
							$this->load->view('header_hyp', $data);
							$this->load->view('nano_health/hyper/infos_insurance_subscription');
						}else if($history == 'insurance-health_care_sheets'){
							$data['active'] = "wallet_health_care_sheets";
							$data['health_care_sheet_id'] = $this->input->get('id');
							$data['health_care_sheet'] = $this->nano_health_model->getInfosHealthCareSheetById($this->input->get('id'));
							$data['performances'] = $this->nano_health_model->getHealthCareSheetPerformances($data['health_care_sheet']->id ?? null);
							$data['exams'] = $this->nano_health_model->getHealthCareSheetExams($data['health_care_sheet']->id ?? null);
							$data['prescriptions'] = $this->nano_health_model->getHealthCareSheetPrescriptions($data['health_care_sheet']->id ?? null);
							// Calcul par assuré et assurance
							//							$data['amounts'] = $this->nano_health_model->calculateSheetAmountsParts($data['health_care_sheet']->id ?? null, $data['health_care_sheet']->type ?? null);

							$this->load->view('header_hyp', $data);
							$this->load->view('nano_health/hyper/infos_health_care_sheet');
						}
						$this->load->view('footer');
						return;
					}else{
						$this->historique($id_network, $this->input->get('d'), $this->input->get('f'), $this->input->get('history'), $this->input->get('parrainId'));
					}
				} 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('agent_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');

						$data['superviseurs'] = $this->user_model->getSuperNameAndCodeForHyp($this->session->userdata('member_code'));
						$data['agentWalletInfos'] = $this->user_model->getInfosWalletAgentForHyper($id_network);

					} else if ($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');

						$data['superviseurs'] = $this->user_model->getSuperNameAndCodeForHyp($this->session->userdata('member_code'));
						$data['agentWalletInfos'] = $this->user_model->getInfosWalletAgentForHyper($id_network);

					}else if($data['hasWallet']?->type == 'ilink_sante'){
						$nh_config = $this->nano_health_model->getConfig($id_network);
						$data['nh_config'] = $nh_config ? $nh_config->first_row() : null ;
						$data['config_id'] = $data['nh_config'] ? $data['nh_config']->id : null ;
						$data['provider_billing_periods'] = $this->user_model->getEnumValues('nh_networks_configs','provider_billing_period');
						$data['password_validation_types'] = $this->user_model->getEnumValues('nh_networks_configs','password_validation');
						$data['payment_periods'] = $this->user_model->getEnumValues('nh_months_prices_grid','payment_period');
						$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']);
						$data['billing_types'] = $this->user_model->getEnumValues('nh_acts','billing_type');
						$data['acts_types'] = $this->user_model->getEnumValues('nh_acts','type');
						$data['authorization_types'] = $this->user_model->getEnumValues('nh_acts','authorization_type');
						$data['provider_classes'] = $this->nano_health_model->getProviderClasses($data['config_id']);
					}

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

					$this->load->view('header_hyp', $data);
					if ($data['hasWallet']?->type == 'visa')
						$this->load->view('gestion_wallet_hyp');
					elseif ($data['hasWallet']?->type == 'ilink')
						$this->load->view('gestion_wallet_ilink_hyp');
					elseif ($data['hasWallet']?->type == 'ilink_sante')
						$this->load->view('nano_health/hyper/gestion_wallet');
					$this->load->view('footer');
				}
			}
		}
	}

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

	private function historique($network_id, $startDate, $endDate, $type , $parrainId = null)
	{
		$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 == 'transaction_ilink') {
			$networkDetails = $this->user_model->getNetworkDetails($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('network_id'));
		else if ($type == 'commission_transfer')
			$data['transactions'] = $this->wallet_model->getCommissionTransfersByNetwork($startDate, $endDate, $this->session->userdata('network_id'));
		else if ($type == 'balance_statement'){
			$res = $this->wallet_model->getWalletPassword($this->session->userdata('network_id'));
			$data['walletPassword'] = $res ? $res->first_row() : null;

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

		} else if ($type == 'refund_history')
			$data['refunds'] = $this->wallet_model->getRefunds($startDate, $endDate, $network_id);
		else if ($type == 'commission_payments')
			$data['payments'] = $this->wallet_model->getCommissionPayments($startDate, $endDate, $network_id);
		else if (strpos($type, 'insurance') !== false){
			/// Historique de l'assurance
		}
		else{
			$data['transactions'] = $this->wallet_model->getRecharges($startDate, $endDate, $network_id);
			$data['superviseurs'] = $this->user_model->getSuperNameAndCodeForHyp($this->session->userdata('member_code'));
			$data['parrain'] = isset($parrainId) ? $this->user_model->getAgentInfos($parrainId) : null ;
		}

		$data['active'] = "wallet_wallet";
		$data['alert'] = "";

		$data['network'] = $this->session->userdata('network');
		$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

		$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
		$data['country'] = $this->session->userdata('current_pays');
		$data['category'] = $this->session->userdata('category');
		$data['id_network'] = $network_id;
		$data['parrain_id'] = $parrainId;

		if(strpos($type, 'insurance') !== false){
			$array = explode('-',$type);
			$data['active'] = "wallet_".$array[1];
		}

		$this->load->view('header_hyp', $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 if ($type == 'insurance-subscriptions')
			$this->load->view('nano_health/hyper/insurances_subscriptions.php');
		else if ($type == 'insurance-insured')
			$this->load->view('nano_health/hyper/insurances_insured.php');
		else if ($type == 'insurance-expired-insured')
			$this->load->view('nano_health/hyper/insurances_expired_insured.php');
		else if ($type == 'insurance-health_care_sheets')
			$this->load->view('nano_health/hyper/insurances_health_care_sheets.php');
		else if ($type == 'insurance-invoices')
			$this->load->view('nano_health/hyper/insurances_invoices.php');
		else
			$this->load->view('historique_recharges');
		$this->load->view('footer');
	}

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

				$parrain_id = $this->input->post('parrain_id');
				$start = $this->input->post('start');
				$end = $this->input->post('end');

				$config = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'))->first_row();

				if(isset($start) && isset($end)){
					$start = date('Y-m-d', strtotime($start));
					$end = date('Y-m-d', strtotime($end. "+1 day"));

					$sql = "SELECT id, type_transac, numCarte, montant, 0 as bank_deposit , commission_banque, commission_hyp, commission_sup, commission_ag,
			agent,parrain,date_created FROM infos_transaction WHERE deleted = 0 AND  parrain_id = ? AND date_created >= ? AND date_created < ? ORDER BY agent ASC";
					$query = $this->db->query($sql, array($parrain_id,$start,$end));
				}else{
					$sql = "SELECT id, type_transac, numCarte, montant, 0 as bank_deposit , commission_banque, commission_hyp, commission_sup, commission_ag,
			agent,parrain,date_created FROM infos_transaction WHERE deleted = 0 AND  parrain_id = ? ORDER BY agent ASC";
					$query = $this->db->query($sql, array($parrain_id));
				}

				$data = [['ID', 'Type' , $this->lang->line('cart_number'),$this->lang->line('customer_net_amount'),$this->lang->line('bank_deposit_amount'),
					$this->lang->line('Commission de la banque'),$this->lang->line('Commission de l\'hyperviseur'),$this->lang->line('Commission du superviseur'),
					$this->lang->line('Commission de l\'agent'),$this->lang->line('agent_name'),$this->lang->line('Superviseur'),'Date']];

				$oldAgent = '';
				foreach ($query->result() as $r){
					if($oldAgent != $r->agent)
						$data[] = [];

					$row = [];

					if($r->type_transac == 'credit'){
						if($r->montant < 0){
							$commission = (-$r->montant * $config->taux_com_client_depot / 100 ) + $config->frais_min_banque_depot;
							$net = $r->montant + $commission;
						}else{
							$commission = ( $r->montant * $config->taux_com_client_depot / 100 ) + $config->frais_min_banque_depot;
							$net = $r->montant - $commission;
						}
						$r->bank_deposit = $r->montant * (1 - ($config->taux_com_client_depot / 100));
					}else{
						$net = $r->montant ;
					}
					$r->montant = $net;
					$r->commission_banque = intval($r->commission_banque);
					$r->numCarte = join(" ", str_split($r->numCarte, 4));

					foreach ($r as $k => $val){
						if($k == 'type_transac'){
							$row[] = $val == 'credit' ? $this->lang->line('DEPOT') : $this->lang->line('RETRAIT');
						} else
							$row[] = $val;
					}
					$data[] = $row;
					$oldAgent = $r->agent;
				}
				echo json_encode($data);
			}
		}
	}

	public function delete_wallet_transaction(){
		if ($this->isLogged()) {
			$datetime = $this->user_model->getCurrentTimeByNetworkID($this->session->userdata('network_id'));
			$id = $this->input->post('id_transaction');
			$query = $this->db->get_where('infos_transaction', ['id' => $id]);
			if($query->num_rows()>0) {
				$transaction = $query->first_row();

				// Debiter le compte de l'agent de sa commission
				$this->db->set('balance_com', 'balance_com-'.$transaction->commission_ag,false);
				$this->db->where('id',$transaction->wallet_id);
				$this->db->update('wallets');

				// Debiter le compte du superviseur de sa commission
				$this->db->set('balance_com', 'balance_com-'.$transaction->commission_sup,false);
				$this->db->where('id',$transaction->id_wallet_sup);
				$this->db->update('wallets');

				// Debiter le compte de l'hyperviseur de sa commission
				$this->db->set('balance_com', 'balance_com-'.$transaction->commission_hyp,false);
				$this->db->where('id',$transaction->id_wallet_hyp);
				$this->db->update('wallets');

				$data = array(
					'deleted' => 1 ,
					'deleted_at' => $datetime
				);
				// Changer l'etat de la transaction
				$this->db->where('id',$id);
				$query = $this->db->update('wallet_transaction',$data);

				try {
					$message = line_with_arguments($this->lang->line('wallet_transaction_deleted_message'), array($id,$transaction->agent));

					$url = NOTIFICATION_SERVICE_URL . '/onesignal/pushToAgent' ;

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

					curl_setopt($ch, CURLOPT_POST, 1);

					/* set the content type json */
					curl_setopt($ch, CURLOPT_HTTPHEADER, array(
						'Content-Type:application/json',
						'Authorization:'.NOTIFICATION_SERVICE_TOKEN,
						'X-localization:'. $this->session->userdata('site_lang') == 'french' ? 'fr' : 'en'
					));

					$data = new \stdClass();
					$data->screen = "notificationview";
					$data->data = new \stdClass();
					$data->data->id = $id;

					$body = new \stdClass();
					$body->agent_code = $transaction->codeMembre;
					$body->message = $message;
					$body->data = $data;
					$body->date = $datetime;
					//Send to agent
					curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
					curl_exec($ch);

					//Send to supervisor
					$body->agent_code = $transaction->codeParrain;
					curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
					curl_exec($ch);

					//Send to hypervisor
					$body->agent_code = $transaction->code_membre_hyp;
					curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
					curl_exec($ch);

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

				}catch (\Throwable $e){

				}

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

	public function walletPassword()
	{
		if ($this->isLogged()) {
			$data['active'] = "wallet_password";
			$data['alert'] = "";
			$data['network'] = $this->session->userdata('network');
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));


			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$data['country'] = $this->session->userdata('current_pays');
			$data['network_id'] = $this->session->userdata('network_id');
			$res = $this->wallet_model->getWalletPassword($this->session->userdata('network_id'));
			$data['walletPassword'] = $res ? $res->first_row() : null;
			$this->load->view('header_hyp', $data);
			$this->load->view('wallet_password');
			$this->load->view('footer');
		}
	}

	public function generate_wallet_password()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$network_id = isset($_POST['network_id']) ? $_POST['network_id'] : null;
				$email = $_POST['email'];
				//$size = $_POST['size'];
				$wallet_password_id = isset($_POST['wallet_password_id']) ? $_POST['wallet_password_id'] : null;
				$network = $_POST['network'];
				$country = $_POST['country'];

				$password = $this->generate_string();
				$hash = $this->hashSSHA($password);
				$encrypted_password = $hash['encrypted'];
				$salt = $hash['salt'];

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

				$this->email->subject($this->lang->line('wallet_password') . ' ' . $network . ' - ' . $country);
				$this->email->message($this->lang->line('mot de passe') . ' : ' . $password);

				if ($this->email->send()) {
					if ($wallet_password_id == null)
						$this->wallet_model->addWalletPassword($network_id, $encrypted_password, $salt, $email);
					else
						$this->wallet_model->updateWalletPassword($wallet_password_id, $encrypted_password, $salt, $email);
					$res = true;
				} else {
				//show_error($this->email->print_debugger());
					$res = false;
				}

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

	private function generate_string($length = 10)
	{
		$chars = 'abcdefghjkmnpqrstuvwxyz' .
			'23456789';

		$str = '';
		$max = strlen($chars) - 1;

		for ($i = 0; $i < $length; $i++)
			$str .= $chars[mt_rand(0, $max)];

		return $str;
	}

	private function hashSSHA($password)
	{
		$salt = sha1(rand());
		$salt = substr($salt, 0, 10);
		$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
		$hash = array("salt" => $salt, "encrypted" => $encrypted);
		return $hash;
	}

	public function resetWalletPassword()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$email = $_POST['email'];
				$wallet_password_id = isset($_POST['wallet_password_id']) ? $_POST['wallet_password_id'] : null;
				$network = $_POST['network'];
				$country = $_POST['country'];

				$password = $this->generate_string();
				$hash = $this->hashSSHA($password);
				$encrypted_password = $hash['encrypted'];
				$salt = $hash['salt'];

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

				$this->email->subject($this->lang->line('reset_wallet_password') . ' ' . $network . ' - ' . $country);
				$this->email->message($this->lang->line('mot de passe') . ' : ' . $password);

				if ($this->email->send()) {
					$this->wallet_model->updateWalletPassword($wallet_password_id, $encrypted_password, $salt);
					$res = true;
				} else {
			//show_error($this->email->print_debugger());
					$res = false;
				}

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

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

			}
		}
	}

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

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

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

				echo json_encode($code);

			}
		}
	}


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

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

				if ($encrypted_password == $hash) {
					$res = $this->wallet_model->insertRembourssementCompensation($montant, $id_network, $id_config);
					$code = $res ? '200' : '401';
				} else {
					$code = '400';
				}

				echo json_encode($code);

			}
		}
	}

	public function calculator()
	{
		if ($this->isLogged()) {
			$data['active'] = "wallet_calculator";
			$data['alert'] = "";
			$data['network'] = $this->session->userdata('network');
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));


			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$data['idConfig'] = $data['hasWallet']?->id;
			$data['country'] = $this->session->userdata('current_pays');
			$data['network_id'] = $this->session->userdata('network_id');
			$data['countries'] = $this->wallet_model->getWalletsCountries();
			$showResult = false;
			$frais = 0;
			$taxe = 0;
			$config = $data['hasWallet'];

			//Simulateur
			$com_ag =  $this->session->userdata('com_ag') ? $this->session->userdata('com_ag') : 0 ;
			$com_sup =  $this->session->userdata('com_sup') ? $this->session->userdata('com_sup') : 0 ;
			$com_hyp =  $this->session->userdata('com_hyp') ? $this->session->userdata('com_hyp') : 0 ;
			$com_bq =  $this->session->userdata('com_bq') ? $this->session->userdata('com_bq') : 0 ;
			//$frais_retrait =  $this->session->userdata('frais_retrait') ? $this->session->userdata('frais_retrait') : 0 ;

			if (isset($_POST)) {
				$operation =  $this->input->post('operation');
				$montant =  $this->input->post('montant');
				$init_country =  $this->input->post('init_country');
				$final_country =  $this->input->post('final_country');
				$save =  $this->input->post('save');
				$code =  $this->input->post('code');


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

				$plr_user_wallet_wallet = $this->wallet_model->getPalierConfigWallet("user_wallet_wallet_international", $data['idConfig']);
				$plr_user_wallet_cash = $this->wallet_model->getPalierConfigWallet("user_wallet_cash_international", $data['idConfig']);
				$plr_agent_depot_wallet_ilink = $this->wallet_model->getPalierConfigWallet("agent_depot_wallet_ilink_international" , $data['idConfig']);
				$plr_agent_depot_autre_wallet = $this->wallet_model->getPalierConfigWallet("agent_depot_autre_wallet_international" , $data['idConfig']);
				$plr_agent_cash_cash = $this->wallet_model->getPalierConfigWallet("agent_cash_cash_international", $data['idConfig']);

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

				$plr_user_wallet_wallet = $plr_user_wallet_wallet ? $plr_user_wallet_wallet->result() : [];
				$plr_user_wallet_cash = $plr_user_wallet_cash ? $plr_user_wallet_cash->result() : [];
				$plr_agent_depot_wallet_ilink = $plr_agent_depot_wallet_ilink ? $plr_agent_depot_wallet_ilink->result() : [];
				$plr_agent_depot_autre_wallet = $plr_agent_depot_autre_wallet ? $plr_agent_depot_autre_wallet->result() : [];
				$plr_agent_cash_cash = $plr_agent_cash_cash ? $plr_agent_cash_cash->result() : [];

				$plr_user_wallet_wallet_national = $plr_user_wallet_wallet_national ? $plr_user_wallet_wallet_national->result() : [];
				$plr_user_wallet_cash_national = $plr_user_wallet_cash_national ? $plr_user_wallet_cash_national->result() : [];
				$plr_agent_depot_wallet_ilink_national = $plr_agent_depot_wallet_ilink_national ? $plr_agent_depot_wallet_ilink_national->result() : [];
				$plr_agent_depot_autre_wallet_national = $plr_agent_depot_autre_wallet_national ? $plr_agent_depot_autre_wallet_national->result() : [];
				$plr_agent_cash_cash_national = $plr_agent_cash_cash_national ? $plr_agent_cash_cash_national->result() : [];

				$taxes = $taxes ? $taxes->result() : [];
				$taxesNationales = array_filter($taxes, function ($tax) {
					return $tax->destination == 'national';
				});

				$taxesInternationales = array_filter($taxes, function ($tax) {
					return $tax->destination == 'international';
				});

				if (isset($save)) {
					$showResult = true;
					switch ($operation) {
						case 1: //Envoi wallet à wallet
							$frais = ($init_country != $final_country) ? $this->calculateFees1($plr_user_wallet_wallet, $montant) : $this->calculateFees1($plr_user_wallet_wallet_national, $montant);
							$taxe = ($init_country != $final_country) ? $this->calculateTax($taxesInternationales, $frais) : $this->calculateTax($taxesNationales, $frais);

							$com_hyp = $frais;
							$this->session->set_userdata('com_hyp', $com_hyp);
							break;
						case 2: //Envoi de wallet à carte
							$frais = $montant * $config->taux_com_user_wallet_carte / 100;
							//taxe = ($init_country != $final_country) ? $this->calculateTax($taxesInternationales , $frais) : $this->calculateTax($taxesNationales ,$frais);
							$com_hyp = $frais * $config->taux_com_hyp_envoi_wallet_carte_ilink / 100;
							$com_bq = $frais * $config->taux_com_banque_envoi_wallet_carte_ilink / 100;
							$this->session->set_userdata('com_hyp', $com_hyp);
							$this->session->set_userdata('com_bq', $com_bq);
							break;
						case 3: //Envoi de wallet à cash
							$frais = ($init_country != $final_country) ? $this->calculateFees1($plr_user_wallet_cash, $montant) : $this->calculateFees1($plr_user_wallet_cash_national, $montant);
							$taxe = ($init_country != $final_country) ? $this->calculateTax($taxesInternationales, $frais) : $this->calculateTax($taxesNationales, $frais);

							$com_hyp = $frais;
							$this->session->set_userdata('com_hyp', $com_hyp);
							//$this->session->set_userdata('frais_retrait',$frais);
							$code = $this->random_string();
							$data['message_code'] = '' . $code;
							//							$this->user_model->insertSimulateur($frais,$montant-$frais-$taxe,$code,$montant);
							break;
						case 4: //Envoi de wallet à banque
							// Non disponible
							//Pas de taxes
							break;
							//		case 5: //Envoi de carte à wallet
							//			$frais =$montant * $config->taux_com_user_carte_wallet / 100;
							////			$taxe = ($init_country != $final_country) ? $this->calculateTax($taxesInternationales , $frais) : $this->calculateTax($taxesNationales ,$frais);
							//			break;
							//		case 6: //Envoi de carte à cash
							//			$frais =$montant * $config->taux_com_user_carte_cash / 100;
							////			$taxe = ($init_country != $final_country) ? $this->calculateTax($taxesInternationales , $frais) : $this->calculateTax($taxesNationales ,$frais);
							//			break;
						case 9: // Retrait de wallet en cash
							$frais = ($init_country != $final_country) ? $this->calculateFees1($plr_user_wallet_cash, $montant) : $this->calculateFees1($plr_user_wallet_cash_national, $montant);
							$taxe = ($init_country != $final_country) ? $this->calculateTax($taxesInternationales, $frais) : $this->calculateTax($taxesNationales, $frais);

							$com_hyp = $frais;
							$this->session->set_userdata('com_hyp', $com_hyp);
							$code = $this->random_string();
							$data['message_code'] = '' . $code;
//							$this->user_model->insertSimulateur($frais,$montant-$frais-$taxe,$code,$montant);
							break;
						case 10: //Retrait de carte vers wallet
							$frais = $montant * $config->taux_com_user_carte_wallet / 100;

							$com_hyp = $frais * $config->taux_com_hyp_retrait_carte_cash_ilink / 100;
							$com_bq = $frais * $config->taux_com_banque_retrait_carte_cash_ilink / 100;
							$this->session->set_userdata('com_hyp', $com_hyp);
							$this->session->set_userdata('com_bq', $com_bq);
							break;
						case 11: // Retrait de carte vers cash
							$frais = $montant * $config->taux_com_user_carte_cash / 100;

							$com_hyp = $frais * $config->taux_com_hyp_retrait_carte_cash_ilink / 100;
							$com_bq = $frais * $config->taux_com_banque_retrait_carte_cash_ilink / 100;
							$this->session->set_userdata('com_hyp', $com_hyp);
							$this->session->set_userdata('com_bq', $com_bq);
							$code = $this->random_string();
							$data['message_code'] = '' . $code;
//							$this->user_model->insertSimulateur($frais * $config->taux_com_hyp_retrait_carte_cash_ilink / 100,$montant-$frais-$taxe,$code,$montant);
							break;
						case 12: // Agent  - Retrait en cash
//			empty
//Sauvegarder les frais lors de chaque operation d'envoi
							if(isset($code)){
								$simulateur = $this->user_model->getSimulateur($code);
								if($simulateur) {
									$part_ag = $simulateur->first_row()->com_hyp * $config->taux_com_ag_retrait_cash / 100;
									$part_sup = $simulateur->first_row()->com_hyp * $config->taux_com_sup_retrait_cash / 100;
									$com_ag = $part_ag;
									$com_sup = $part_sup;
									$com_hyp -= ($part_ag + $part_sup);
									$data['montant_retrait'] = $simulateur->first_row()->montant_retrait;
									$data['frais_retrait'] = $simulateur->first_row()->com_hyp;
									$data['montant_init'] = $simulateur->first_row()->montant;
									$this->session->set_userdata('com_ag', $com_ag);
									$this->session->set_userdata('com_sup', $com_sup);
									$this->session->set_userdata('com_hyp', $com_hyp);
								}else{
									$data['error_simulateur'] = 'Code de retrait incorrect';
								}
							}else{
								$data['error_simulateur'] = 'Code de retrait incorrect';
							}


							break;
						case 13: // Agent - Retrait de la carte vers cash
							$frais = $montant * $config->taux_com_wallet_ag_carte_cash / 100;

							$com_ag = $frais * $config->taux_com_ag_retrait_carte_cash / 100;
							$com_sup = $frais * $config->taux_com_sup_retrait_carte_cash / 100;
							$com_hyp = $frais * $config->taux_com_hyp_retrait_carte_cash / 100;
							$com_bq = $frais * $config->taux_com_banque_retrait_carte_cash / 100;
							$this->session->set_userdata('com_ag', $com_ag);
							$this->session->set_userdata('com_sup', $com_sup);
							$this->session->set_userdata('com_hyp', $com_hyp);
							$this->session->set_userdata('com_bq', $com_bq);
							break;
						case 14: // Agent - Envoi de cash vers wallet iLink
							$frais = ($init_country != $final_country) ? $this->calculateFees1($plr_agent_depot_wallet_ilink, $montant) : $this->calculateFees1($plr_agent_depot_wallet_ilink_national, $montant);
							$taxe = ($init_country != $final_country) ? $this->calculateTax($taxesInternationales, $frais) : $this->calculateTax($taxesNationales, $frais);
							$com_ag = $frais * $config->taux_com_ag_envoi_cash / 100;
							$com_sup = $frais * $config->taux_com_sup_envoi_cash / 100;
							$com_hyp = $frais * $config->taux_com_hyp_envoi_cash / 100;
							$this->session->set_userdata('com_ag', $com_ag);
							$this->session->set_userdata('com_sup', $com_sup);
							$this->session->set_userdata('com_hyp', $com_hyp);
							break;
						case 15: // Agent - Envoi de cash vers autre wallet
							$frais = ($init_country != $final_country) ? $this->calculateFees1($plr_agent_depot_autre_wallet, $montant) : $this->calculateFees1($plr_agent_depot_autre_wallet_national, $montant);
							$taxe = ($init_country != $final_country) ? $this->calculateTax($taxesInternationales, $frais) : $this->calculateTax($taxesNationales, $frais);
							$com_ag = $frais * $config->taux_com_ag_envoi_cash / 100;
							$com_sup = $frais * $config->taux_com_sup_envoi_cash / 100;
							$com_hyp = $frais * $config->taux_com_hyp_envoi_cash / 100;
							$this->session->set_userdata('com_ag', $com_ag);
							$this->session->set_userdata('com_sup', $com_sup);
							$this->session->set_userdata('com_hyp', $com_hyp);
							break;
						case 16: // Agent - Envoi de cash vers une carte visa
							$frais = $montant * $config->taux_com_wallet_ag_envoi_cash_carte / 100;
							$com_ag = $frais * $config->taux_com_ag_depot_cash_carte / 100;
							$com_sup = $frais * $config->taux_com_sup_depot_cash_carte / 100;
							$com_hyp = $frais * $config->taux_com_hyp_depot_cash_carte / 100;
							$com_bq = $frais * $config->taux_com_banque_depot_cash_carte / 100;
							$this->session->set_userdata('com_ag', $com_ag);
							$this->session->set_userdata('com_sup', $com_sup);
							$this->session->set_userdata('com_hyp', $com_hyp);
							$this->session->set_userdata('com_bq', $com_bq);
							break;
						case 17: // Agent - Envoi de cash vers cash
							$frais = ($init_country != $final_country) ? $this->calculateFees1($plr_agent_cash_cash, $montant) : $this->calculateFees1($plr_agent_cash_cash_national, $montant);
							$taxe = ($init_country != $final_country) ? $this->calculateTax($taxesInternationales, $frais) : $this->calculateTax($taxesNationales, $frais);
							$com_ag = $frais * $config->taux_com_ag_envoi_cash / 100;
							$com_sup = $frais * $config->taux_com_sup_envoi_cash / 100;
							$com_hyp = $frais * $config->taux_com_hyp_envoi_cash / 100;
							$this->session->set_userdata('com_ag', $com_ag);
							$this->session->set_userdata('com_sup', $com_sup);
							$this->session->set_userdata('com_hyp', $com_hyp);
							$code = $this->random_string();
							$data['message_code'] = '' . $code;
//							$this->user_model->insertSimulateur($frais,$montant-$frais-$taxe,$code,$montant);
							break;
						case 18: // Agent - Envoi de cash vers banque
							// Indisponible
							break;
					}
				}
			}

			$data['showResult'] = $showResult;
			$data['frais'] = $frais;
			$data['taxe'] = $taxe;

			$data['operation'] =  $operation;
			$data['init_country'] =  $init_country;
			$data['final_country'] =  $final_country;
			$data['montant'] = $montant;


			$data['com_ag'] =  $com_ag;
			$data['com_sup'] =  $com_sup;
			$data['com_hyp'] =  $com_hyp;
			$data['com_bq'] =  $com_bq;

			$operations = [
				new Operation(1, $this->lang->line('op1')),
				new Operation(2, $this->lang->line('op2')),
				new Operation(3, $this->lang->line('op3')),
				new Operation(4, $this->lang->line('op4')),
//				new Operation(5, $this->lang->line('op5')),
//				new Operation(6, $this->lang->line('op6')),
//				new Operation(7, $this->lang->line('op7')),
//				new Operation(8, $this->lang->line('op8')),
				new Operation(9, $this->lang->line('op9')),
				new Operation(10, $this->lang->line('op10')),
				new Operation(11, $this->lang->line('op11')),
				new Operation(12, $this->lang->line('op12')),
				new Operation(13, $this->lang->line('op13')),
				new Operation(14, $this->lang->line('op14')),
				new Operation(15, $this->lang->line('op15')),
				new Operation(16, $this->lang->line('op16')),
				new Operation(17, $this->lang->line('op17')),
				new Operation(18, $this->lang->line('op18')),
			];
			$data['operations'] = $operations;
//			if (isset($_POST)) {
//				$data['montant'] = isset($_POST['montant']) ? $_POST['montant'] : 0 ;
//			}

			$this->load->view('header_hyp', $data);
			$this->load->view('calculator');
			$this->load->view('footer');
		}
	}

	//Calcul des frais internationaux
	function calculateFees1(array $paliers, $montant)
	{
		$size = sizeof($paliers);
		if($size > 0){
			$min = $paliers[0]->min;
			$max = $size > 0 ? $paliers[$size - 1]->max : 0;
			$palier = null;
			foreach ($paliers as $p) {
				if ($montant >= $p->min && $montant <= $p->max) {
					$palier = $p;
					break;
				}
			}

			if ($palier) {
				return (($palier->min + $palier->max) / 2 * $palier->taux / 100);
			} else {
				if ($montant < $min)
					return $min * $paliers[0]->taux / 100;
				else if ($montant > $max)
					return $max * $paliers[$size - 1]->taux / 100;
			}
		}
	}

//Calcul des frais nationaux
	function calculateFees2($min, $max, $taux, $montant)
	{
		if ($montant < $min)
			return $min * $taux / 100;
		else if ($montant > $max)
			return $max * $taux / 100;
		else
			return $montant * $taux / 100;
	}

//Calcul des taxes
	function calculateTax(array $taxes, $frais)
	{
		$sommeTaux = 0;
		$sommeFixe = 0;
		foreach ($taxes as $tax) {
			if ($tax->type == '%')
				$sommeTaux += $tax->valeur;

			if ($tax->type == 'fixe')
				$sommeFixe += $tax->valeur;
		}
		return ($frais * $sommeTaux / 100) + $sommeFixe;
	}

	public function random_string()
	{
		$character_set_array = array();
		$character_set_array[] = array('count' => 12, 'characters' => 'abcdefghjkmnpqrstuvwxyz');
		$character_set_array[] = array('count' => 4, 'characters' => '23456789');
		$temp_array = array();
		foreach ($character_set_array as $character_set) {
			for ($i = 0; $i < $character_set['count']; $i++) {
				$temp_array[] = $character_set['characters'][rand(0, strlen($character_set['characters']) - 1)];
			}
		}
		shuffle($temp_array);
		return implode('', $temp_array);
	}

	private function config_wallet($config , $country)
	{
//		$data['configWallet'] = $this->wallet_model->getConfigWallet($network_id);
		$data['active'] = "wallet_wallet";
		$data['alert'] = "";

		$data['network'] = $this->session->userdata('network');
		$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

		$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
		$data['country'] = $this->session->userdata('current_pays');
		$data['category'] = $this->session->userdata('category');
		$data['idConfig'] = $data['hasWallet']?->id;
		$data['network_id'] = $this->session->userdata('network_id');
		$data['currency_code'] = $this->session->userdata('currency_code');
		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('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_hyp', $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_hyp', $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_hyp', $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']);
//				$data['plr_user_wallet_cart_international'] = $this->wallet_model->getPalierCommissionsWallet("user_wallet_cart_international", $data['idConfig']);
//				$data['plr_hyp_user_wallet_cart_international'] = $this->wallet_model->getPalierCommissionsWallet("hyp_user_wallet_cart_international", $data['idConfig']);
//				$data['plr_bank_user_wallet_cart_international'] = $this->wallet_model->getPalierCommissionsWallet("bank_user_wallet_cart_international", $data['idConfig']);
				$this->load->view('header_hyp', $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_hyp', $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_wallet_international'] = $this->wallet_model->getPalierCommissionsWallet("user_cart_wallet_international", $data['idConfig']);

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

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

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

				$this->load->view('header_hyp', $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_hyp', $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']);

				$this->load->view('header_hyp', $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_customer_cart_cash_international'] = $this->wallet_model->getPalierCommissionsWallet("customer_cart_cash_international", $data['idConfig']);

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

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

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

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

				$this->load->view('header_hyp', $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_customer_cash_cart_international'] = $this->wallet_model->getPalierCommissionsWallet("customer_cash_cart_international", $data['idConfig']);

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

				$data['plr_sup_cash_cart_national'] = $this->wallet_model->getPalierCommissionsWallet("sup_cash_cart_national", $data['idConfig']);
//				$data['plr_sup_cash_cart_international'] = $this->wallet_model->getPalierCommissionsWallet("sup_cash_cart_international", $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']);
//				$data['plr_bank_cash_cart_international'] = $this->wallet_model->getPalierCommissionsWallet("bank_cash_cart_international", $data['idConfig']);

				$this->load->view('header_hyp', $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_hyp', $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_hyp', $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_hyp', $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['network'] = $this->session->userdata('network');
		$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));
//
		$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
		$data['country'] = $this->session->userdata('current_pays');
		$data['category'] = $this->session->userdata('category');
		$data['idConfig'] = $data['hasWallet']?->id;
		$res = $this->wallet_model->getWalletPassword($this->session->userdata('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_hyp', $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('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('network_id'));
				$data['groups'] = $this->nano_credit_model->getUsersGroups($this->session->userdata('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['network'] = $this->session->userdata('network');
				$data['country'] = $this->session->userdata('current_pays');
				$data['currency_code'] = $this->session->userdata('currency_code');
				$data['configWallet'] = $data['hasWallet'];
				$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));
				$this->load->view('header_hyp', $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['network'] = $this->session->userdata('network');
		$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));
		$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
		$data['country'] = $this->session->userdata('current_pays');
		$data['category'] = $this->session->userdata('category');
		$data['idConfig'] = $data['hasWallet']?->id;
		$data['network_id'] = $this->session->userdata('network_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_hyp', $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_hyp', $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['network'] = $this->session->userdata('network');
		$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

//
		$data['hasWallet'] = $data['configWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
		$data['country'] = $this->session->userdata('current_pays');
		$data['category'] = $this->session->userdata('category');
		$data['id_network'] = $this->session->userdata('network_id');

		$this->load->view('header_hyp', $data);
		if ($type == 'savings')
			$this->load->view('nano_credit/historique_savings');
		else
			$this->load->view('nano_credit/historique_nano_credit');
		$this->load->view('footer');
	}

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

				$this->nano_credit_model->insertCreditLimit($limit_min, $limit_max, '1', $id_network);
				$res = true;

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

	public function saveNanoCreditSharedRates()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$taux_ag = $_POST['taux_ag'];
				$taux_sup = $_POST['taux_sup'];
				$taux_hyp = $_POST['taux_hyp'];
				$id_network = $_POST['id_network'];

				$this->nano_credit_model->insertNanoCreditSharedRates($taux_ag, $taux_sup, $taux_hyp, $id_network);
				$res = true;

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

	public function saveNanoCreditRates()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$idConfig = $_POST['id_config'];
				$rates = isset($_POST['rates']) ? $_POST['rates'] : null;
				$type = isset($_POST['type']) ? $_POST['type'] : 'nano_credit';

				$this->insertNanoCreditRates($rates, $idConfig, $type);
				$res = true;

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

	private function insertNanoCreditRates($palier, $idConfig, $type)
	{

		$exist = $this->nano_credit_model->getNanoCreditRates($idConfig, $type);
		if ($exist) {
			$this->nano_credit_model->deleteNanoCreditRates($idConfig, $type);
		}

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

	private function users_group_details($group_code)
	{
		$data['active'] = "nano_credit";
		$data['alert'] = "";

		$data['network'] = $this->session->userdata('network');
		$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

		$data['currency_code'] = $this->session->userdata('currency_code');

		$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
		$data['country'] = $this->session->userdata('current_pays');
		$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_hyp', $data);
		$this->load->view('nano_credit/users_group_detail');
		$this->load->view('footer');
	}

	public function generateQRCode(){
		if ($this->isLogged()) {
			$url = WALLET_SERVICE_URL.'/qrcode/generate';
			$data = http_build_query($_POST);
			$ch = curl_init($url."?".$data);
			curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
			/* 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'
			));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			/* execute request */
			$result = curl_exec($ch);
			/* close cURL resource */
			curl_close($ch);
			if ($result) {
				echo $result;
			} else {
				echo json_encode(['status' => 500]);
			}
		}
	}

	public function recherche()
	{

		if ($this->isLogged()) {

			$data['active'] = "recherche";
			$data['alert'] = "";
			$data['network'] = $this->session->userdata('network');
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

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

			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$data['result_search'] = 0;
			$data['default_phone'] = '';
			$data['default_transac'] = '';
			$data['default_code'] = '';
			$data['default_nom'] = '';


			$this->load->view('header_hyp', $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,$this->session->userdata('current_pays'));
				} elseif ($phone != '' && $nom == '') {
					$phone_condition = "phone LIKE '" . $phone . "%'";
					$nom_condition = 'AND lastname IS NOT NULL';
					$simple_users = $this->user_model->get_simple_user($phone, '%',$this->session->userdata('current_pays'));
				} elseif ($phone == '' && $nom != '') {
					$phone_condition = 'phone IS NOT NULL';
					$nom_condition = "AND lastname LIKE '%" . $nom . "%'";
					$simple_users = $this->user_model->get_simple_user('%', $nom,$this->session->userdata('current_pays'));
				} 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';
				}

				$network_condition = ' AND network_id = '.$this->session->userdata('network_id');
				$where_clause = "WHERE " . $phone_condition . ' ' . $transac_condition . ' ' . $code_condition . ' ' . $nom_condition.$network_condition;

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

				$data['active'] = "recherche";
				$data['alert'] = "";
				$data['network'] = $this->session->userdata('network');
				$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

				$data['currency_code'] = $this->session->userdata('currency_code');
				$data['category'] = $this->session->userdata('category');
				$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));


				if ($res) {

					$count_users = $res->num_rows();
					if ($simple_users != null) {
						$count_users = $res->num_rows() + $simple_users->num_rows();
					}

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


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

					$data['result_search'] = 2;
					$data['res_simple_users'] = $simple_users;
					$data['default_phone'] = '';
					$data['default_transac'] = '';
					$data['default_code'] = '';
					$data['default_nom'] = '';

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

	public function operators()
	{

		if ($this->isLogged()) {

			$data['active'] = "operators";
			$data['alert'] = "";
			$data['network'] = $this->session->userdata('network');
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

			$data['currency_code'] = $this->session->userdata('currency_code');
			$data['category'] = $this->session->userdata('category');
			$data['network_id'] = $this->session->userdata('network_id');

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


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

	public function active_operator()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$data = array(
					'id_operator_country' => $this->input->post('id_operator_country'),
					'id_network' => $this->input->post('id_network')
				);

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

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

	public function deactive_operator()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$data = array(
					'id_operator_country' => $this->input->post('id_operator_country'),
					'id_network' => $this->input->post('id_network')
				);

				$query = $this->db->delete('networks_operators', $data);

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

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

				if($this->input->post('is_enabled')){
					$data = array(
						'url' => $this->input->post('url'),
						'taux_partage' => $this->input->post('rate')
					);

					$this->db->where('id_configWallet', $this->input->post('config_id'));
					$this->db->where('id_network', $this->input->post('network_id'));
					$query = $this->db->update('transmitting_networks', $data);
				}else{
					$data = array(
						'id_configWallet' => $this->input->post('config_id'),
						'id_network' => $this->input->post('network_id'),
						'url' => $this->input->post('url'),
						'taux_partage' => $this->input->post('rate')
					);
					$query = $this->db->insert('transmitting_networks', $data);
				}

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

	public function deactive_transmitting_network()
	{
		if ($this->isLogged()) {
			if (isset($_POST)) {
				$data = array(
					'id_configWallet' => $this->input->post('config_id'),
					'id_network' => $this->input->post('network_id')
				);

				$query = $this->db->delete('transmitting_networks', $data);

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

	public function documentation()
	{
		if ($this->isLogged()) {
			$view = $this->input->get('view');
			if ($view) {
				switch ($view){
					case 'walletServiceExterne' :
						$data['link'] = WALLET_SERVICE_EXTERNE_URL.'/api/documentation';
						break;
					default:
						$data['link'] = '#';
						break;
				}

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

	public function validating_agents($role = null){
		if ($this->isLogged()) {
			$data['alert'] = "";
			if($role == 'doctors') {
				$data['active'] = "wallet_validating_doctors";
				$data['role'] = 'DOCTOR';
			}else if($role == 'controllers'){
				$data['active'] = "wallet_validating_controllers";
				$data['role'] = 'CONTROLLER';
			}else if($role == 'account_opening_agents'){
				$data['active'] = "wallet_validating_account_opening_agents";
				$data['role'] = 'OPENING_ACCOUNT_AGENT';
			}else{
				$data['active'] = "wallet_validating_agents";
				$data['role'] = 'AGENT';
			}

			$data['network'] = $this->session->userdata('network');
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

			$data['currency_code'] = $this->session->userdata('currency_code');
			$data['category'] = $this->session->userdata('category');
			$data['network_id'] = $this->session->userdata('network_id');

			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$data['agents'] = $this->db->get_where('nh_validating_agents',['network_id' => $data['network_id'] , 'role' => $data['role']]);

			$this->load->view('header_hyp', $data);
			$this->load->view('nano_health/hyper/validating_agents');
			$this->load->view('footer');
		}
	}

	public function exclusions(){
		if ($this->isLogged()) {
			$data['alert'] = "";
			$data['active'] = "wallet_exclusions";
			$data['network'] = $this->session->userdata('network');
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

			$data['currency_code'] = $this->session->userdata('currency_code');
			$data['category'] = $this->session->userdata('category');
			$data['network_id'] = $this->session->userdata('network_id');

			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$exclusion = $this->nano_health_model->getExclusion($data['network_id']);
			$data['exclusion'] = $exclusion ? $exclusion->first_row() : null ;

			$this->load->view('header_hyp', $data);
			$this->load->view('nano_health/hyper/exclusions');
			$this->load->view('footer');
		}
	}

	public function drugs_and_devices(){
		if ($this->isLogged()) {
			$data['active'] = "wallet_drugs_and_devices";
			$data['network'] = $this->session->userdata('network');
			$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));

			$data['currency_code'] = $this->session->userdata('currency_code');
			$data['category'] = $this->session->userdata('category');
			$data['network_id'] = $this->session->userdata('network_id');

			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$data['types'] = $this->user_model->getEnumValues('nh_drugs_and_devices','type');

			$this->load->view('header_hyp', $data);
			$this->load->view('nano_health/hyper/drugs_and_devices');
			$this->load->view('footer');
		}
	}

	public function storeCustomerAccountType(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$id = $_POST['id'] ?? null ;

				$exist = $this->db->get_where('customer_account_types', ['id !=' => $id ,'network_id' => $_POST['network_id'] , 'name' => $_POST['name']]);
				if ($exist->num_rows() == 0) {
					foreach ($_POST as $key => $value){
						if(empty($value)){
							$_POST[$key] = null;
						}
					}
					if(!empty($id)){
						$documents = $_POST['documents'] ?? [] ;
						unset($_POST['documents']);
						$this->db->where('id',$id);
						$this->db->update('customer_account_types',$_POST);
						$this->db->delete('customer_account_type_documents',['account_type_id' => $id]);
						if(sizeof($documents) > 0){
							$data = array_map(function ($document) use($id){
								$row = [];
								$row['name'] = $document[0];
								$row['description'] = $document[1];
								$row['account_type_id'] = $id;
								return $row;
							},$documents);
							$this->db->insert_batch('customer_account_type_documents',$data);
						}
					}else{
						$this->db->insert('customer_account_types',$_POST);
					}
					echo json_encode(['code' => 200]);

				}else{
					echo json_encode(['code'=> 419 , 'message' => $this->lang->line("name_already_used")]);
				}
			}
		}
	}

	public function deleteCustomerAccountType(){
		if($this->isLogged()) {
			if (isset($_POST)) {
				$this->db->delete('customer_account_types', ['id' => $_POST['id']]);
				$this->db->delete('customer_account_type_documents', ['account_type_id' => $_POST['id']]);
				echo json_encode(['code' => 200]);
			}
		}
	}
}

class Operation
{
	public $name;
	public $id;

	public function __construct($id, $name)
	{
		$this->name = $name;
		$this->id = $id;
	}
}
