<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * Created by PhpStorm.
 * User: capp
 * Date: 29/05/2018
 * Time: 15:49
 */


class Wallet_model extends CI_Model
{

	public function __construct()
	{
		parent::__construct();
		$this->load->model('nano_health_model');
	}
	// Wallet

	public function getAllActivatedNetworks(){
		$query = $this->db->query("SELECT networks.name AS network,networks.status AS status,networks.id,countries.name AS country,networks.country_id ,
       configWallet.id_network , configWallet.type , configWallet.enabled FROM `networks`
 		INNER JOIN countries ON networks.country_id=countries.id LEFT JOIN configWallet ON configWallet.id_network = networks.id WHERE status = 1");
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getConfigWallet($id_network){
		$query = $this->db->get_where('configWallet' , ['id_network' => $id_network]);
		return $query->num_rows() > 0 ? $query->first_row() : null ;
	}

	public function verifyConfigWalletInCountry($type, $country_id){
		$sql='SELECT * FROM `configWallet` cw JOIN networks n ON cw.id_network = n.id 
			WHERE cw.type = ? AND n.country_id = ?;' ;
		$query = $this->db->query($sql , array($type,$country_id));
		return $query->num_rows()>0 ;
	}

	public function addConfigWallet($network_id , $type){
		$this->db->trans_start();
		$existQuery = $this->db->get_where('configWallet' , ['id_network' => $network_id]);
		if($existQuery->num_rows() > 0){
			$this->db->where('id_network', $network_id);
			$this->db->update('configWallet', ['enabled' => 1 , 'type' => $type]);
			$query = $nhConfigExist = $this->db->get_where('nh_networks_configs' , ['network_id' => $network_id]);
			if($nhConfigExist->num_rows() == 0 && $type == 'ilink_sante'){
				$this->createNanoHealthWalletConfig($network_id);
			}
			$this->db->trans_complete();
			return $query;
		}else{
			$query = $this->db->insert('configWallet' , ['id_network' => $network_id, 'type' => $type]);
			if($query && $type == 'ilink_sante'){
				$this->createNanoHealthWalletConfig($network_id);
			}
			$this->db->trans_complete();
			return $query;
		}
	}

	private function createNanoHealthWalletConfig($network_id){
		// Creer la config du nano santé
		$configID = $this->nano_health_model->createConfig($network_id);
		$this->db->where('id_network', $network_id);
		$this->db->update('configWallet', ['nh_network_config_id' => $configID]);
	}

	public function updateConfigWallet($config_id , $taux_client_r , $taux_client_d,  $taux_ag_r , $taux_ag_d ,  $taux_sup_r , $taux_sup_d , $taux_bq_r , $taux_bq_d , $frais_d ){
		$sql= 'UPDATE `configWallet` SET  `taux_com_client_retrait` = ?, `taux_com_client_depot` = ?, `taux_com_ag_retrait` = ?, `taux_com_ag_depot` = ?, 
        `taux_com_sup_retrait` = ? , `taux_com_sup_depot` =  ?,  `part_banque_retrait` = ?, `part_banque_depot` = ?, `frais_min_banque_depot` = ? WHERE (`id` = ?);';
		$query = $this->db->query($sql , array($taux_client_r,$taux_client_d,$taux_ag_r,$taux_ag_d,$taux_sup_r,$taux_sup_d, $taux_bq_r , $taux_bq_d , $frais_d , $config_id));
		return $query;
	}

	public function disableConfigWallet($network_id){
		$query = $this->db->query("UPDATE `configWallet` SET enabled = 0 , type = null WHERE `configWallet`.`id_network` = '".$network_id."'");
		return $query;
	}

	public function deleteConfigWallet($network_id){
		$query = $this->db->query("DELETE FROM `configWallet` WHERE `configWallet`.`id_network` = '".$network_id."'");
		return $query;
	}

	public function getWallet($id_agent){
		$query = $this->db->get_where('wallet_agent' , ['agent_id' => $id_agent]);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function addWallet($id_agent)
	{
		$sql = "SELECT id FROM networks_agents WHERE agent_id = ?";
		$query = $this->db->query($sql, [$id_agent]);

		if ($query->num_rows() === 0) {
			return false;
		}
		$id_networkAgent = $query->first_row()->id;

		// Vérifier si un wallet existe déjà pour ce id_networkAgent
		$check = $this->db->query(
			"SELECT id FROM wallets WHERE id_networkAgent = ?",
			[$id_networkAgent]
		);
		if ($check->num_rows() > 0) {
			return true;
		}

		// Insérer un nouveau wallet sinon
		$query = $this->db->query(
			"INSERT INTO wallets (id_networkAgent) VALUES (?)",
			[$id_networkAgent]
		);

		return $query;
	}


	public function getAgentTransactions($id_wallet){
		$query = $this->db->get_where('wallet_transaction' , ['id_wallet' => $id_wallet]);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getAgentiLinkTransactions($id_wallet){
		$query = $this->db->get_where('infos_ilink_transaction' , ['id_wallet_ag' => $id_wallet]);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getNetworkHyper($id_network){
		$query = $this->db->get_where('hyper_infos' , ['network_id' => $id_network]);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getAllAgentsForNetwork($id_network){
		$query = $this->db->get_where('hyper_infos' , ['network_id' => $id_network]);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function reinitializeWallet($id_wallet){
		$sql = "UPDATE `wallets` SET `balance_princ` = '0', `balance_com` = '0', `created_date` = ? WHERE (`id` = ?)";
		$query = $this->db->query($sql , array(new DateTime(),$id_wallet));
		return $query;
	}

	// Mot de passe du wallet
	public function getAllActivatedWalletNetworks(){
		$query = $this->db->query("SELECT n.id AS id_network , n.name AS network,n.status AS status,c.name AS country,c.currency_name_fr, c.currency_name_en , c.currency_code, wp.id AS wallet_password FROM networks n
 												INNER JOIN countries_currencies c ON n.country_id=c.id INNER JOIN configWallet cw ON cw.id_network = n.id
                                                LEFT JOIN walletsPassword wp ON wp.network_id = n.id WHERE status = 1;");
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function addWalletPassword($network_id, $encrypted_password, $salt, $email)
	{
		$sql = "INSERT INTO `walletsPassword` (`network_id`, `encrypted_password`, `salt`, `email`) VALUES ( ?, ?, ?, ?);";
		$query = $this->db->query($sql, array($network_id, $encrypted_password, $salt, $email));
		return $query;
	}

	public function updateWalletPassword($wallet_password_id, $encrypted_password, $salt)
	{
		$sql = "UPDATE `walletsPassword` SET `encrypted_password` = ? , `salt` = ? WHERE (`id` = ?);";
		$query = $this->db->query($sql, array($encrypted_password, $salt, $wallet_password_id));
		return $query;
	}

	public function getWalletPassword($network_id)
	{
		$sql = "SELECT * FROM walletsPassword WHERE network_id = ?";
		$query = $this->db->query($sql, array($network_id));
		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}
	}

	public function getRecharges($debut ,  $fin , $id_network){
		$chain = $debut ?  " AND date BETWEEN '".$debut."' AND '".$fin."'" : "";
		$query = $this->db->query("SELECT *
                                    FROM infos_recharges
                                    WHERE `network_id`=".$id_network.$chain);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function addWalletRecharge($montant,$wallet_id , $id_network){
		$datetime = $this->getCurrentTimeByNetworkID($id_network);
		$sql = "INSERT INTO `wallet_recharge` (`montant`, `wallet_id`, `date`) VALUES (?, ?, ?);";
		$query = $this->db->query($sql , array($montant,$wallet_id,$datetime));
		return $query;
	}

	public function updateWalletBalance($montant,$wallet_id){
		$sql = "UPDATE `wallets` SET balance_princ = balance_princ + ? WHERE (`id` = ? );";
		$query = $this->db->query($sql , array($montant,$wallet_id));
		return $query;
	}

	// Wallet ilink
	public function addPalierConfigWallet($type, $idConfig, $min, $max, $taux)
	{
		$sql = "INSERT INTO `paliersConfigWallet` (`type`, `min`, `max`, `taux`, `idConfig`) VALUES (?,?,?,?,?);";
		$query = $this->db->query($sql, array($type, $min, $max, $taux, $idConfig));
		return $query;
	}

	public function addTaxe($idConfig, $nom, $type, $valeur, $destination, $categorie = 'wallet')
	{
		$sql = "INSERT INTO `taxes` (`nom`, `type`, `valeur`, `destination`,`categorie`, `idConfig`) VALUES (?,?,?,?,?,?);";
		$query = $this->db->query($sql, array($nom, $type, $valeur, $destination, $categorie, $idConfig));
		return $query;
	}

	public function updatePalierConfigWallet($id, $min, $max, $taux)
	{
		$sql = "UPDATE `paliersConfigWallet` SET `min` = ? , `max` =  ? , `taux` = ?  WHERE (`id` = ?);";
		$query = $this->db->query($sql, array($min, $max, $taux, $id));
		return $query;
	}

	public function getPalierConfigWallet($type, $idConfig)
	{
		return $this->db->get_where('paliersConfigWallet',['type' => $type , 'idConfig' => $idConfig]);
	}

	public function getPalierCommissionsWallet($type, $idConfig)
	{
		return $this->db->get_where('paliers_commissions_wallet',['type' => $type , 'idConfig' => $idConfig]);
	}


	public function getTaxes($idConfig, $categorie = 'wallet')
	{
		return $this->db->get_where('taxes',['categorie' => $categorie , 'idConfig' => $idConfig]);
	}

	public function getOnePalierConfigWallet($id)
	{
		$sql = "SELECT *  FROM `paliersConfigWallet` WHERE (`id` = ?);";
		$query = $this->db->query($sql, array($id));
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function deletePalierConfigWallet($type, $idConfig)
	{
		$sql = "DELETE FROM `paliersConfigWallet` WHERE (`type` = ? AND `idConfig` = ? );";
		$query = $this->db->query($sql, array($type, $idConfig));
		return $query;

	}

	public function deleteTaxes($idConfig, $categorie = 'wallet')
	{
		$sql = "DELETE FROM `taxes` WHERE (`idConfig` = ? AND `categorie` = ? );";
		$query = $this->db->query($sql, array($idConfig, $categorie));
		return $query;

	}

	// La liste des monnaies pour les pays actifs
	public function getCurrencies($code){
		$sql= "SELECT * FROM currencies WHERE id IN(
					SELECT idCurrency FROM countries WHERE id IN (
					 SELECT distinct country_id FROM networks WHERE status = 1
					)
					) AND code <> ? ;";
		$query = $this->db->query($sql, array($code));
		return $query->num_rows() > 0 ? $query : false ;
	}

	//Liste des monnaies pour les pays dont un wallet est actif
	public function getWalletsCountriesCurrencies($code){
		$sql= "SELECT * FROM currencies WHERE id IN(
					SELECT idCurrency FROM countries WHERE id IN (
					 SELECT distinct c.id FROM networks n INNER JOIN countries_currencies c ON n.country_id=c.id INNER JOIN configWallet cw ON cw.id_network = n.id WHERE status = 1
					)
					) AND code <> ? ;";
		$query = $this->db->query($sql, array($code));
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function insertExchangeRate($currency,$rate){
		return $this->db->insert('exchange_rate',['target_currency' => $currency, 'exchange_rate' => $rate]);
	}

	public function getExchangeRate($currency){
		$this->db->where('target_currency',$currency);
		$query = $this->db->get('exchange_rate');
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function updateExchangeRate($currency,$rate){
		$this->db->where('target_currency',$currency);
		$this->db->update('exchange_rate',['target_currency' => $currency, 'exchange_rate' => $rate]);
	}

	//Liste des pays dont un wallet est actif
	public function getWalletsCountries(){
		$sql= "SELECT id , name , currency_code FROM countries_currencies WHERE id IN (
					 SELECT distinct c.id FROM networks n INNER JOIN countries_currencies c ON n.country_id=c.id INNER JOIN configWallet cw ON cw.id_network = n.id WHERE status = 1
					);";
		$query = $this->db->query($sql);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getActiveCountries(){
		$sql= "SELECT id , name FROM countries WHERE id IN (
					 SELECT distinct n.country_id FROM networks n WHERE n.status = 1
					);";
		$query = $this->db->query($sql);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getCountry($id){
		$sql= "SELECT name FROM countries WHERE id = $id";
		$query = $this->db->query($sql);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function cancelCreditRequest($id_demand){
		$sql = "SELECT *  FROM `info_demandeCredits` WHERE `demande_id` =  ?;";
		$query = $this->db->query($sql , array($id_demand));
		if($query->num_rows()>0){
			$demand = $query->first_row();
			$sql = "SELECT *  FROM `wallet_agent` WHERE `codeMembre` =  ?;";
			$query = $this->db->query($sql , array($demand->codeMembre));
			$query2 = $this->db->query($sql , array($demand->codeParrain));
			$result = $query->num_rows()>0;
			if($result){
				$result =$query2->num_rows()>0;
				if($result){
					$sql = "UPDATE wallets SET balance_princ = ? WHERE (`id` =  ?);";
					$montant = $demand->montant;
					$montantAgent = $query->first_row()->balance_princ - $montant;
					$montantParrain = $query2->first_row()->balance_princ + $montant;

					$this->db->query($sql , array($montantAgent , $query->first_row()->wallet_id ));
					$this->db->query($sql , array($montantParrain , $query2->first_row()->wallet_id));

					$sql = "UPDATE `demandeCredits` SET `status` = '2' WHERE (`id` = ?);";
					$this->db->query($sql , array($demand->demande_id));
					return true;
				}
			}
			return false;
		}else{
			return false;
		}
	}

	public function insertSimulateur($frais , $montant ,$code , $montant_init){
		$sql = "INSERT INTO `simulateur` (`com_hyp` , `montant_retrait`, `code` ,`montant` ) VALUES ( ?, ?, ? , ?);";
		$query = $this->db->query($sql , array($frais,$montant,$code,$montant_init));
		return $query;
	}

	public function getSimulateur($code){
		$sql = "SELECT *  FROM `simulateur` WHERE `code` =  ?;";
		$query = $this->db->query($sql , array($code));
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function setSharingRate($network_id,$config_id,$rate, $url){
		$sql = "SELECT *  FROM `paying_networks` WHERE `id_network` =  ? AND id_configWallet = ? ;";
		$query = $this->db->query($sql , array($network_id,$config_id));
		if($query->num_rows()>0){
			$sql = "UPDATE `paying_networks` SET `taux_partage` =  ? ,`url` =  ? WHERE `id_network` =  ? AND id_configWallet = ? ;";
			$this->db->query($sql , array($rate, $url, $network_id,$config_id));
		}else{
			$sql = "INSERT INTO `paying_networks` (`id_network`, `taux_partage`, `url`, `id_configWallet`) VALUES ( ?, ?, ? ,?); ;";
			$this->db->query($sql , array($network_id,$rate,$url,$config_id));
		}
		return true;
	}

	public function getSharingRate($id_network ,$idConfig){
		$sql = "SELECT taux_partage , url FROM `paying_networks` WHERE `id_network` =  ? AND id_configWallet = ? ;";
		$query = $this->db->query($sql , array($id_network,$idConfig));
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getSharingRateByNetwork($id_network){
		$sql = "SELECT balance_com FROM `paying_networks` WHERE `id_network` =  ? ;";
		$query = $this->db->query($sql , array($id_network));
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function countPayingNetworks($id_country ,$idConfig){
		$sql = "SELECT count(id) as total FROM `paying_networks` WHERE `id_network` IN (SELECT distinct n.id  FROM countries c INNER JOIN
					  networks n ON n.country_id = c.id WHERE  n.status = 1 AND c.id = ?
					) AND id_configWallet = ? ;";
		$query = $this->db->query($sql , array($id_country, $idConfig));
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getActiveNetworksByCountry($country_id , $network_id){
		$query = $this->db->query("SELECT networks.name , networks.id , configWallet.type FROM `networks` INNER JOIN countries ON networks.country_id=countries.id 
									INNER JOIN configWallet ON configWallet.id_network = networks.id WHERE status = 1 AND networks.id <> $network_id AND countries.id = $country_id");
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getPayingNetworksByConfigWallet($id_config)
	{
		$query = $this->db->query("SELECT n.name , n.id , cw.type , c.name as country ,c.currency_code, pw.taux_partage as rate , pw.balance_com , pw.balance_compensation, pw.id_configWallet as config_id FROM networks n INNER JOIN countries_currencies c ON n.country_id=c.id 
				INNER JOIN configWallet cw ON cw.id_network = n.id INNER JOIN paying_networks pw ON pw.id_network = n.id WHERE pw.id_configWallet = $id_config ");
		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}
	}

	public function getNetworkIlinTransactions($id_network){
		$query = $this->db->query("SELECT *
                                    FROM infos_ilink_transaction
                                    WHERE `network_emetteur`= '".$id_network."'");
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getCurrency($id_network){
		$query = $this->db->query("SELECT cc.currency_code as code FROM networks n INNER JOIN countries_currencies cc ON cc.id = n.country_id
                                    WHERE n.id = '".$id_network."'");
		if($query->num_rows()>0){
			return $query->first_row();
		}else{
			return false;
		}
	}

	public function getCommissionTransfers($debut ,  $fin , $codeMembre){
		$chain = $debut ?  " AND date BETWEEN '".$debut."' AND '".$fin."'" : "";
		$query = $this->db->query("SELECT *
                                    FROM infos_transferts_commission
                                    WHERE `codeParrain`='".$codeMembre."'".$chain);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getCommissionTransfersByNetwork($debut ,  $fin , $id_network){
		$chain = $debut ?  " AND date BETWEEN '".$debut."' AND '".$fin."'" : "";
		$query = $this->db->query("SELECT *
                                    FROM infos_transferts_commission
                                    WHERE `network_id`='".$id_network."'".$chain);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getIlinkTransactionsSup($debut ,  $fin , $codeMembre){
		$chain = $debut ?  " AND date BETWEEN '".$debut."' AND '".$fin."'" : "";
		$query = $this->db->query("SELECT *
                                    FROM infos_ilink_transaction
                                    WHERE `code_parrain`='".$codeMembre."'".$chain);
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getInfosWalletAgentForSuper($codeMembre)
	{
		$query = $this->db->query("SELECT *
                                    FROM wallet_agent
                                    WHERE `codeParrain`='" . $codeMembre . "'");
		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}
	}

	public function insertRembourssementCompensation($montant, $id_network, $id_config)
	{
		$sql = "SELECT *  FROM `paying_networks` WHERE `id_network` =  ? AND id_configWallet = ? ;";
		$query = $this->db->query($sql, array($id_network, $id_config));
		if ($query->num_rows() > 0) {
			$montant_init = $query->first_row()->balance_compensation;
			if (($montant_init - $montant) < 0)
				return false;
			$sql = "UPDATE `paying_networks` SET balance_compensation = ? WHERE `id_network` =  ? AND id_configWallet = ?;";
			$this->db->query($sql, array($montant_init - $montant, $id_network, $id_config));
			$datetime = $this->getCurrentTimeByNetworkID($id_network);
			$sql = "INSERT INTO `remboursemment_compensation` (`montant` , `montant_restant`,`id_paying_network` , `id_network` , `date`) VALUES ( ?, ?, ? ,?, ?);";
			$this->db->query($sql, array($montant, $montant_init - $montant, $id_network, $this->session->userdata('network_id'),$datetime));
			return true;
		}
		return false;
	}

	public function getRefunds($debut, $fin, $id_network)
	{
		$chain = $debut ? " AND date BETWEEN '" . $debut . "' AND '" . $fin . "'" : "";
		$query = $this->db->query("SELECT rp.* , n.name as network , cc.name as country , cc.currency_code FROM remboursemment_compensation rp 
				INNER JOIN networks n ON n.id = id_paying_network INNER JOIN countries_currencies cc ON cc.id = n.country_id 
				WHERE rp.id_network =" . $id_network . $chain);
		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}
	}

	// Gestion reglementaire

	public function getRegulationsCountries(){
		$query = $this->db->query("SELECT distinct cc.id , cc.name as country , cc.currency_code,  r.id_country, r.montant_max_jour_national, r.montant_max_hebdo_national, r.montant_max_mensuel_national,
 		r.montant_max_jour_international, r.montant_max_hebdo_international, r.montant_max_mensuel_international FROM networks n
INNER JOIN countries_currencies cc ON n.country_id= cc.id INNER JOIN configWallet cw ON cw.id_network = n.id LEFT JOIN regulations r ON r.id_country = cc.id;");
		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}
	}

	public function getRegulationsLimits($id_country){
		$query = $this->db->query("SELECT * FROM regulations WHERE id_country ='" . $id_country . "'");
		if ($query->num_rows() > 0) {
			return $query->first_row();
		} else {
			return false;
		}
	}

	public function insertRegulationsLimits($id_country, $max_day_national , $max_week_national , $max_month_national, $max_day_international , $max_week_international , $max_month_international){
		$sql = "INSERT INTO `regulations` (`id_country`, `montant_max_jour_national`, `montant_max_hebdo_national`, `montant_max_mensuel_national`,
	`montant_max_jour_international`, `montant_max_hebdo_international`, `montant_max_mensuel_international`) VALUES (?,?, ?, ?,?,?,?);";
		$query = $this->db->query($sql , array($id_country,$max_day_national,$max_week_national,$max_month_national,$max_day_international,$max_week_international,$max_month_international));
		return $query;
	}

	public function updateRegulationsLimits($id_country, $max_day_national , $max_week_national , $max_month_national, $max_day_international , $max_week_international , $max_month_international){
		$sql = "UPDATE `regulations` SET `montant_max_jour_national` = ? , `montant_max_hebdo_national` = ? , `montant_max_mensuel_national` = ?,
 	`montant_max_jour_international` = ? , `montant_max_hebdo_international` = ? , `montant_max_mensuel_international` = ?  WHERE (`id_country` = ?);";
		$query = $this->db->query($sql , array($max_day_national,$max_week_national,$max_month_national,$max_day_international,$max_week_international,$max_month_international,$id_country));
		return $query;
	}

	// Operateurs
	public function getAllOperatorsCountries(){
		$query = $this->db->query("SELECT b.id, b.nom as operator_name , bc.adresse as operator_address , bc.code as operator_code , bc.status, c.name as country , c.id as country_id , top.description_fr as type_fr, top.description_en as type_en
			FROM operators_countries bc INNER JOIN operators b ON b.id = bc.id_operator INNER JOIN type_operators top ON b.type = top.code INNER JOIN countries c ON c.id = bc.id_country ");
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getAllOperators(){
		$query = $this->db->query("SELECT o.* , top.description_fr ,top.description_en FROM operators o INNER JOIN type_operators top ON o.type = top.code");
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function checkIfOperatorAssignationExist($id_country,$id_operator){
		$query = $this->db->query("SELECT * FROM operators_countries WHERE id_country ='".$id_country."' AND id_operator='".$id_operator."'");
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getOperator($id_operator){
		$query = $this->db->query("SELECT * FROM operators WHERE id='".$id_operator."'");
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function updateOperator($id_operator,$id_country, $name , $address , $code){
		$sql = "UPDATE `operators` SET `nom` = ? WHERE (`id` = ?);";
		 $this->db->query($sql , array($name,$id_operator));

		$sql = "UPDATE `operators_countries` SET `adresse` = ? , `code` = ? WHERE (`id_operator` = ? AND `id_country` = ?);";
		return $this->db->query($sql , array($address,$code,$id_operator,$id_country));
	}

	public function deleteOperatorCountry($id_operator, $id_country){
		$sql = "DELETE FROM `operators_countries` WHERE `id_operator` = ? AND  `id_country` = ?";
		$query = $this->db->query($sql, array($id_operator,$id_country));
		return $query;
	}

	//Obtenir uniquement les operateurs qui sont dans le meme pays que le reseau0
	public function getOperatorsForNetwork($id_network){
		$sql = "SELECT b.type , n.country_id as network_country_id , bc.id, b.nom as operator_name , bc.adresse as operator_address, bc.code as operator_code , c.name as country , c.id as country_id , nb.id_network , top.description_fr as type_fr, top.description_en as type_en
FROM networks n CROSS JOIN operators_countries bc  INNER JOIN operators b ON b.id = bc.id_operator INNER JOIN countries c ON c.id = bc.id_country INNER JOIN type_operators top ON b.type = top.code
LEFT JOIn networks_operators nb ON nb.id_operator_country = bc.id AND nb.id_network = n.id WHERE  bc.status = 1 AND n.id = ?";
		$query = $this->db->query($sql , array($id_network));
		return $query->num_rows() > 0 ? $query : false ;
	}

	// Reseaux emetteurs
	public function getTransmittingNetwork($id_network ,$idConfig){
		$sql = "SELECT * FROM `transmitting_networks` WHERE `id_network` =  ? AND id_configWallet = ? ;";
		$query = $this->db->query($sql , array($id_network,$idConfig));
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function countTransmittiongNetworks($id_country ,$idConfig){
		$sql = "SELECT count(id) as total FROM `transmitting_networks` WHERE `id_network` IN (SELECT distinct n.id  FROM countries c INNER JOIN
					  networks n ON n.country_id = c.id WHERE  n.status = 1 AND c.id = ?
					) AND id_configWallet = ? ;";
		$query = $this->db->query($sql , array($id_country, $idConfig));
		return $query->num_rows() > 0 ? $query : false ;
	}

	public function getTransmittingNetworksByConfigWallet($id_config)
	{
		$query = $this->db->query("SELECT n.name , n.id , cw.type , c.name as country ,c.currency_code, pw.taux_partage as rate , pw.balance_com , pw.balance_compensation, pw.id_configWallet as config_id FROM networks n INNER JOIN countries_currencies c ON n.country_id=c.id 
				INNER JOIN configWallet cw ON cw.id_network = n.id INNER JOIN transmitting_networks pw ON pw.id_network = n.id WHERE pw.id_configWallet = $id_config ");
		return $query->num_rows() > 0 ? $query : false ;
	}

	// Obtenir l'heure en fonction de l'id du reseau
	function getCurrentTimeByNetworkID($id_network)
	{
		$query= $this->db->query("SELECT code_country FROM countries c INNER JOIN networks n on n.country_id = c.id WHERE n.id = '$id_network'");
		if ($query->num_rows() > 0) {
			$country_code = isset($query->first_row()->code_country) ? $query->first_row()->code_country : 'GA';
			$timezone = \DateTimeZone::listIdentifiers(\DateTimeZone::PER_COUNTRY, $country_code);
			$date = (sizeof($timezone) > 0) ? new \DateTime('now', new \DateTimeZone($timezone[0])) : new \DateTime();
			return $date->format('Y-m-d H:i:s');
		} else {
			return date('Y-m-d H:i:s');
		}
	}

	public function payCommissionInCash($montant, $id_wallet_agent,$id_network){
		try{
			$this->db->trans_begin();

			$datetime = $this->getCurrentTimeByNetworkID($id_network);

			$walletAgent = $this->db->get_where('wallets',['id' => $id_wallet_agent])->first_row();
			// Mise à jour du compte
			$sql = "UPDATE `wallets` SET balance_com = balance_com - ? WHERE (`id` = ? );";
			$this->db->query($sql , array($montant,$id_wallet_agent));

			$data = array('amount' => $montant , 'initial_commission' => $walletAgent->balance_com ,
				'final_commission' => $walletAgent->balance_com + $montant, 'id_wallet_agent' => $id_wallet_agent , 'date'=> $datetime);
		    $this->db->insert('commission_payments', $data);

			$this->db->trans_commit();
			return true;

		}catch (Throwable $e){
			$this->db->trans_rollback();
			return false;
		}
	}

	public function getCommissionPayments($debut, $fin, $id_network)
	{
		$chain = $debut ? " AND date BETWEEN '" . $debut . "' AND '" . $fin . "'" : "";
		$query = $this->db->query("SELECT cp.* , wa.lastname, wa.currency_code FROM commission_payments cp
				INNER JOIN wallet_agent wa ON cp.id_wallet_agent = wa.wallet_id WHERE wa.network_id =" . $id_network . $chain);
		if ($query->num_rows() > 0) {
			return $query;
		} else {
			return false;
		}
	}
}
