<?php

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

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

class Superviseur_dash extends CI_Controller
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('wallet_model');
		$this->load->model('nano_credit_model');
		$this->load->model('Users_simple');
		$this->load->model('User_model');
	}

	public function index()
	{
		if (!$this->session->userdata('email')) {

			$this->session->set_flashdata('error', 'log in first');
			$data['alert'] = "ok";
			$data['message'] = "Login first!";
			redirect('index.php', $data);

		} else {

			$count_g = $this->User_model->geolocatedCountByParrain($this->session->userdata('member_code'));
			$count_d = $this->User_model->getCountDemande($this->session->userdata('member_code'));
			$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');

			$data['list_geolocated_users'] = $this->user_model->getUsersGeolocatedForSup($this->session->userdata('member_code'));

			$data['active'] = "dash";
			
			$data['member_code'] = $this->session->userdata('member_code');
			$data['category'] = $this->session->userdata('category');
			$data['network'] = $this->session->userdata('network');
			$data['code_parrain'] = $this->session->userdata('parrain');
			$data['listdem'] = $this->user_model->getAllDemandesForSuper($this->session->userdata('member_code'));
			$data['geolocated_user'] = $this->user_model->getSuperNameAndCodeForSup($this->session->userdata('member_code'));
			$data['count_g_users'] = $count_g;
			$data['count_d_users'] = $count_d;
			$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['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$this->load->view('header_sup', $data);
			$this->load->view('superviseur_dash');
			$this->load->view('footer');
		}
	}

	/**
	 * Affiche la table des points agents du superviseur
	 */
	public function getAllUser_g()
	{

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

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


			redirect('index.php', $data);
		} else {

			$position = $this->user_model->getAllpositions($this->session->userdata('network'), 'geolocated', $this->session->userdata('member_code'));

			$data['active'] = "geolocated";
			$data['positions'] = $position;
			$numberGeo = $this->user_model->getNumberGeoBySuper($this->session->userdata('member_code'));
			if ($numberGeo) {
				$data['numberGeo'] = $numberGeo;
			} else {
				$data['numberGeo'] = "";
			}
			$data['map_title'] = $this->lang->line('Utilisateurs géolocalisés');
			$data['total_points'] = $this->user_model->getCoutGeolocatedUsersForSuper($this->session->userdata('member_code'));
			$data['tab'] = $this->user_model->getUsersGeolocatedForSup($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'] = $this->session->userdata('category');
			$data['network'] = $this->session->userdata('network');
			$data['geolocated_user'] = $this->user_model->getSuperNameAndCodeForSup($this->session->userdata('member_code'));
			$data['alert'] = "";
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$this->load->view('header_sup', $data);
			$this->load->view('listeadmin');
			$this->load->view('footer');
		}
	}

	/**
	 * Affiche les demandes de credits
	 */
	public function getDemandes()
	{

		if (!$this->session->userdata('email')) {
			$this->session->set_flashdata('error', 'log in first');
			$data['alert'] = "ok";
			$data['message'] = "Login first!";
			$this->load->view('login', $data);
		} else {
			$type = $this->input->get("type");
			$data['type'] = $type;

			$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")); // Increment date because SQL BETWEEN

			$network = $this->session->userdata('network');
//			$data['type'] = $this->lang->line('crédits');
			$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');
			if ($type == 'incoming') {
				$data['active'] = "demandes_credits_entrantes";
				$data['tab_fastDemande'] = $this->user_model->getRangeASCDemandes($debut, $fin, $this->session->userdata('member_code'));
				$data['tab_slowDemande'] = $this->user_model->getRangeDESCDemandes($debut, $fin, $this->session->userdata('member_code'));
				$data['temp_moyen'] = $this->user_model->getTempsMoyen($debut, $fin, $this->session->userdata('member_code'));
				$data['list'] = $this->user_model->getDemandesForSuper($debut, $fin, $this->session->userdata('member_code'));

			} else if ($type = 'outgoing') {
				$data['active'] = "demandes_credits_sortantes";
				$data['tab_fastDemande_s'] = $this->user_model->getRangeASCDemandesOut($debut, $fin, $this->session->userdata('member_code'));
				$data['tab_slowDemande_s'] = $this->user_model->getRangeDESCDemandesOut($debut, $fin, $this->session->userdata('member_code'));
				$data['mydem'] = $this->user_model->getDemandesHyperForSuper($debut, $fin, $this->session->userdata('member_code'));
				$data['temp_moyen_mine'] = $this->user_model->getTempsMoyenDemandeSup($this->session->userdata('member_code'));

			}
			$data['geolocated_user'] = $this->user_model->getSuperNameAndCodeForSup($this->session->userdata('member_code'));
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$this->load->view('header_sup', $data);
			$this->load->view('demande_credit');
			$this->load->view('footer');

		}
	}

	/**
	 * Afficher les demandes d'adhesion
	 */
	public function getDemandesAd()
	{

		if (!$this->session->userdata('email')) {
			$this->session->set_flashdata('error', 'log in first');
			$data['alert'] = "ok";
			$data['message'] = "Login first!";
			$this->load->view('login', $data);
		} else {
			$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['active'] = "demandesAd";
			$data['alert'] = "";
			$data['demand_type'] = 'adhesion';
			
			$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['mydem'] = $this->user_model->getDemandesHyperForSuper($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['type'] = $this->lang->line('Adhésion');
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
			$data['geolocated_user'] = $this->user_model->getSuperNameAndCodeForSup($this->session->userdata('member_code'));
			$this->load->view('header_sup', $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["commission"] = "";
			$data["principal"] = "";
			$data["transactions"] = "";
			$agent_id = $this->session->userdata('agent_id');
			$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));

			if ($this->input->get('history')) {
				$this->historique($id_network, $this->input->get('d'), $this->input->get('f'), $this->session->userdata('member_code'),
					$this->input->get('history'));
			} else {
				$context = new AutoContext();
				//Create wallet if it not exist
				$res = $this->wallet_model->getWallet($agent_id);
				if ($res == false) {
					if ($data['hasWallet']) {
						$this->user_model->addWallet($agent_id);
					}
				}

				$res = $this->wallet_model->getWallet($agent_id);
				if ($res != null) {
					$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');
					$agents_g = $this->user_model->getUsersGeolocatedForSup($this->session->userdata('member_code'));
					$data['agents_g'] = $agents_g;

					//Fetch all transactions of any geolocated agent of the network
					$data["transactions"] = array();
					$transactions = [];
					if ($agents_g) {
						foreach ($agents_g->result() as $row) {
							$wallet = $this->wallet_model->getWallet($row->agent_id);
							if ($wallet) {
								if ($data['hasWallet']?->type == 'visa') {
									$transactions = $this->user_model->getAgentTransactions($wallet->first_row()->wallet_id);
								} else if ($data['hasWallet']?->type == 'ilink') {
									$transactions = $this->user_model->getAgentiLinkTransactions($wallet->first_row()->wallet_id);
								}
								if ($transactions) {
									foreach ($transactions->result() as $trans) {
										$trans->agent_id = $row->agent_id; // Add agent id to transaction
										$data['transactions'][] = $trans;
									}
								}
							}
						}
					}
				} else {
					$data["commission"] = "N/A";
					$data["principal"] = "N/A";
					$data["totalCommissionBanque"] = "N/A";
					$data["transactions"] = false;
				}

				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['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['provider_classes'] = $this->nano_health_model->getProviderClasses($data['config_id']);
				}

				$data['country'] = $this->session->userdata('current_pays');
				$data['currency_code'] = $this->session->userdata('currency_code');
				$data['alert'] = "";
				$data['active'] = "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['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));
				$data['pays'] = $this->user_model->getAllGameCountries();
				$data['networks'] = $this->user_model->getActiveNetwork();
				$data['agentWalletInfos'] = $this->user_model->getInfosWalletAgentForHyper($id_network);
//				$data['geolocated_user'] = $this->user_model->getSuperNameAndCodeForSup($this->session->userdata('member_code'));
				$this->load->view('header_sup', $data);
				if ($data['hasWallet']?->type == 'visa')
					$this->load->view('gestion_wallet_sup');
				elseif ($data['hasWallet']?->type == 'ilink')
					$this->load->view('gestion_wallet_sup_ilink');
				elseif ($data['hasWallet']?->type == 'ilink_sante')
					$this->load->view('nano_health/super/gestion_wallet');
				$this->load->view('footer');
			}

		}
	}

	private function historique($network_id, $startDate, $endDate, $codeMembre, $type)
	{
		$data['configWallet'] = $this->wallet_model->getConfigWallet($network_id);
		$format = $this->session->userdata('site_lang') === 'french' ? 'd-m-Y' : 'Y-m-d';
		$data['startDate'] = $startDate ? date($format, strtotime($startDate)) : null;
		$data['endDate'] = $endDate ? date($format, strtotime($endDate)) : null;
		$endDate = Date('Y-m-d', strtotime($endDate . "+1 day"));
		if ($type == 'transaction')
			$data['transactions'] = $this->user_model->getTransactionsSup($startDate, $endDate, $codeMembre);
		else if ($type == 'transaction_ilink')
			$data['transactions'] = $this->wallet_model->getIlinkTransactionsSup($startDate, $endDate, $codeMembre);
		else if ($type == 'commission_transfer')
			$data['transactions'] = $this->wallet_model->getCommissionTransfers($startDate, $endDate, $this->session->userdata('member_code'));
		else if ($type == 'balance_statement')
			$data['wallets'] = $this->user_model->getInfosWalletAgentForSuper($codeMembre);

		$data['active'] = "wallet";
		$data['alert'] = "";
		$data['network'] = $this->session->userdata('network');
		$data['villes'] = $this->user_model->getVilleByUserGeo($data['network'], $this->session->userdata('current_pays'));
		$data['networks'] = $this->user_model->getActiveNetwork();
//		$data['superviseurs'] = $this->user_model->getSuperNameAndCodeForHyp($this->session->userdata('member_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['geolocated_user'] = $this->user_model->getSuperNameAndCodeForSup($this->session->userdata('member_code'));
		$data['id_network'] = $this->session->userdata('network_id');


		$this->load->view('header_sup', $data);
		if ($type == 'transaction')
			$this->load->view('historique_transactions');
		else if ($type == 'transaction_ilink')
			$this->load->view('historique_transactions_ilink');
		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');
		$this->load->view('footer');
	}

	public function nano_credit()
	{
		if ($this->isLogged()) {
			$data['network_id'] = $network_id = $this->session->userdata('network_id');

			$startDate = $this->input->get('d');
			$endDate = $this->input->get('f');

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

			$data['transactions'] = $this->nano_credit_model->getUserDemandesCreditForSuper($startDate, $endDate, $this->session->userdata('member_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['networks'] = $this->user_model->getActiveNetwork();
//			$data['superviseurs'] = $this->user_model->getSuperNameAndCodeForHyp($this->session->userdata('member_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['id_network'] = $this->session->userdata('network_id');
//				$data['geolocated_user'] = $this->user_model->getSuperNameAndCodeForSup($this->session->userdata('member_code'));

			$this->load->view('header_sup', $data);
			$this->load->view('nano_credit/historique_nano_credit');
			$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;
	}

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


			$this->load->view('header_sup', $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';
				}

				$godfather_condition = " AND code_parrain = '".$this->session->userdata('member_code')."'";
				$where_clause = "WHERE " . $phone_condition . ' ' . $transac_condition . ' ' . $code_condition . ' ' . $nom_condition.$godfather_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['networks'] = $this->user_model->getActiveNetwork();
				$data['hasWallet'] = $this->wallet_model->getConfigWallet($this->session->userdata('network_id'));
				$data['country'] = $this->session->userdata('current_pays');
				$data['category'] = $this->session->userdata('category');


				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_sup', $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_sup', $data);
					$this->load->view('gestion_recherche');
					$this->load->view('footer');
				}
			}
		}
	}

}
