<?php 
namespace App\Controllers\Admin;
use App\Views;
use App\Models\CommonModel;
use App\Libraries\MyEncrypt;
use App\Libraries\PHPMailer;
use App\Libraries\PDF;
// use App\ThirdParty\fpdf18\fpdf;

class Reports extends BaseController {

	/**
	* 
	* Start 
	* Create Date: 15 July, 2016
	* This controller to manage all transactions.
	* Created saravanan.
	* @see http://zhyip.com/
	* Last Updated: 7 September, 2016
	* End
	* 
	*/

	public function __construct() {
        $this->session = session();
		// admin login only
		if($this->session->get('admin_login')) {
   
			// form validation library
			// $this->load->library('form_validation');
			// $this->load->model('finance_model');
			$this->finance_model = model('finance_model');
			helper('download');
			// $this->load->helper('download');
			$this->isSubadmin();

			
		} else {
			if(isset($_COOKIE['remember_token'])) {

				$myencrypt = new MyEncrypt;
				$token_value = $myencrypt->decode($this->input->cookie('remember_token'));
				$this->isCookie($token_value);	

			} else {
				$this->session->set('last_page', current_url());
				return redirect()->to('admin/login');
			}
		}

	}

	private function isSubadmin() {
      $this->router = service('router');
      $this->session = session();
		if($this->session->get('user_type') == 'subadmin') {
			$controller = $this->router->controllerName().'/'.$this->router->methodName();
			$pages = json_decode($this->session->get('permission'));
		
			if(!in_array(ucfirst($controller), $pages)) {
				return redirect()->to('admin');
			}
		}
	}

	// 
	private function isCookie($values) {
      $this->session = session();
		$value = explode('|', $values);
		$result = $this->common_model->getPassword($value[0]);
		$hashed_password = $result->password;

		if(crypt(urlencode($value[1]), $hashed_password)) {

			$array = array(
				"logged_in" => TRUE,
				"userid" => $result->id,
				"admin_login" => TRUE
			);
			$this->session->set($array);

		} else {
			return redirect()->to('admin/login');
		}
	}

	public function index()
	{
		return redirect()->to('admin');
		// echo view('admin/finance/multtiselect');
	}

	public function checkusertypes($usertype){

		$this->db = db_connect();
		$session = \Config\Services::session();

		 $this->common_model = model('CommonModel');
		switch ($usertype) {
			case '0':
				$condition = "status ='" . $usertype . "'";
				break;
			case '1':
				$condition = "status ='" . $usertype . "'";
				break;
			default:
				$condition = "status IN ('0', '1', '2', '3')";
				break;
		}

		$condition='';
		if($usertype!='all')
		{
			$condition = "status ='" . $usertype . "'";
		}

		$admin_login=$session->get('userid');
		$group=$this->request->getPost('group');
		$get_admin=$this->db->query("select * from admin where id='".$admin_login."'")->getRow();

		$user_group = $get_admin->user_group;
        
		if($group!='all')
		{		
			if($condition=='')
				$condition="new_entry = '".$group."'";
			else
				$condition.=" and new_entry = '".$group."'";
		}
		else
		{
			if($user_group=='1')
			{
				if($condition=='')
					$condition= "new_entry= '0'";
				else
				 $condition.=" and new_entry='0'";
			}
			else if($user_group=='2')
			{
				if($condition=='')
					$condition="new_entry= '1'";
				else
				 $condition.= " and new_entry='1'";
			}
        }

		$users=$this->db->query("select * from uusers where $condition order by username Asc")->getResult();
		//$users = $this->common_model->GetResults('uusers', $condition);
	
		// $select = '<option value="0"> -- Select User -- </option>';
		$select = '';
		foreach ($users as $row) { 
			if($row->username!='')
			{
				$select .= '<option value="'.$row->uusersid.'">'.ucfirst($row->username).'</option>';
			}
		}
		echo $select;
	}


	// deposit reports
	public function deposit()
	{
	    
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_reports')
		);

		$this->data['user_list'] = $this->common_model->GetResults('uusers'); 

		/*$condition = "payment_key in('status') AND payment_value = 'on'";
		$this->data['payment_list'] = $this->common_model->GetPaymentsName($condition);*/

		$this->data['page_title'] = lang('language_lang.deposit_report_page_title');
		// $this->data['action'] = base_url().'admin/reports/exportdeposit';
		$this->data['action'] = '';
		$this->data['module_name'] = 'finance';

		$this->data['all_coin'] = $this->common_model->GetResults('coin_info');		
		
		if($this->request->getPost()) {

			$post_data = $this->request->getPost();
			
			$post_data['types'] = "history.type in ('deposit')";
			$post_data['type'] = false;
			$post_data['ftype'] = false;

			$this->exportdeposit($post_data);
			return redirect()->to('reports/deposit');
		}
		
		echo view('admin/finance/reports',$this->data);

	}

	


	public function exchange()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_reports')
		);

		$this->data['user_list'] = $this->common_model->GetResults('uusers'); 

		$condition = "payment_key in('status') AND payment_value = 'on'";
		$this->data['payment_list'] = $this->common_model->GetPaymentsName($condition);

		$this->data['exchange_type'] = array('1' => 'Buy','2' => 'Sell','3' => 'Tradebuy','4' =>'Tradesell');		

		$this->data['exchange_status'] = array('1' => 'opened','2' => 'Requested','3' => 'Completed','4' =>'Deleted');		

		$this->data['all_coin'] = $this->common_model->GetResults('coin_info');		

		$this->data['page_title'] = lang('language_lang.exchange_report_page_title');
		// $this->data['action'] = base_url().'admin/reports/exportdeposit';
		$this->data['action'] = '';
		$this->data['module_name'] = 'finance';
		
		if($this->input->post()) {

			$post_data = $this->input->post();
			
			$post_data['types'] = "exchange.cid != '' ";
			$post_data['type'] = false;
			$post_data['ftype'] = false;
			$this->exportexchange($post_data);
			return redirect()->to('reports/exchange');
		}
		
		echo view('admin/finance/reports',$this->data);

	}


	// expiredeposit reports
	public function expiredeposit()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_reports')
		);

		$this->data['user_list'] = $this->common_model->GetResults('uusers'); 

		$condition = "payment_key in('status') AND payment_value = 'on'";
		$this->data['payment_list'] = $this->common_model->GetPaymentsName($condition);

		$this->data['page_title'] = lang('language_lang.exp_report_page_title');
		// $this->data['action'] = base_url().'admin/reports/exportdeposit';
		$this->data['action'] = '';
		$this->data['module_name'] = 'finance';

		$this->data['all_coin'] = $this->common_model->GetResults('coin_info');		

		if($this->input->post()) {
			$post_data = $this->input->post();
			$post_data['types'] = "deposit.status in ('matured')";
			$post_data['type'] = false;
			$post_data['ftype'] = false;
			$this->exportexpiredeposit($post_data);
		}
		
		echo view('admin/finance/reports',$this->data);

	}




	// fundtransfer reports
	public function fundtransfer()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_reports')
		);

		$this->data['user_list'] = $this->common_model->GetResults('uusers'); 

		$condition = "payment_key in('status') AND payment_value = 'on'";
		$this->data['payment_list'] = $this->common_model->GetPaymentsName($condition);

		$this->data['page_title'] = lang('language_lang.fundtransfer_report_page_title');
		// $this->data['action'] = base_url().'admin/reports/exportdeposit';
		$this->data['action'] = '';
		$this->data['module_name'] = 'finance';

		if($this->request->getPost()) {

			$post_data = $this->request->getPost();
			$post_data['types'] = "history.type in ('fund_send')";
			$post_data['type'] = false;
			$post_data['ftype'] = false;
			$this->exportdeposit($post_data);
		}
		
		echo view('admin/finance/reports',$this->data);

	}

	// payouts reports
	public function payouts()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->common_model = model('CommonModel');
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_reports')
		);

		$this->data['user_list'] = $this->common_model->GetResults('uusers'); 
		$this->data['page_title'] = lang('language_lang.payouts_report_page_title');
		$condition = "payment_key in('status') AND payment_value = 'on'";
		$this->data['payment_list'] = $this->common_model->GetPaymentsName($condition);
		$this->data['action'] = 'admin/reports/payouts';
		$this->data['module_name'] = 'finance';


		if($this->request->getPost()) {
			$post_data = $this->request->getPost();
			$post_data['types'] = "history.type in ('withdrawal', 'withdraw_request')";
			$post_data['type'] = true;
			$post_data['ftype'] = false;
			$this->exportdeposit($post_data);
		}
		
		echo view('admin/finance/reports',$this->data);

	}

	// earnings reports
	public function bonus()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->common_model = model('CommonModel');
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_reports')
		);

		$this->data['user_list'] = $this->common_model->GetResults('uusers'); 
		$this->data['page_title'] = lang('language_lang.bonus_report_page_title');
		$condition = "payment_key in('status') AND payment_value = 'on'";
		$this->data['payment_list'] = $this->common_model->GetPaymentsName($condition);
		$this->data['action'] = 'admin/reports/bonus';
		$this->data['module_name'] = 'finance';

		$this->data['all_coin'] = $this->common_model->GetResults('coin_info');		

		if($this->request->getPost()) {
			$post_data = $this->request->getPost();
			$post_data['types'] = "history.type in ('bonus', 'penalty')";
			$post_data['type'] = true;
			$post_data['ftype'] = false;
			$this->exportdeposit($post_data);
		}
		
		echo view('admin/finance/reports',$this->data);

	}

	// earnings reports
	public function earnings()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->common_model = model('CommonModel');
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_reports')
		);

		$this->data['user_list'] = $this->common_model->GetResults('uusers'); 
		$this->data['page_title'] = lang('language_lang.earnings_report_page_title');
		$condition = "payment_key in('status') AND payment_value = 'on'";
		$this->data['payment_list'] = $this->common_model->GetPaymentsName($condition);
		$this->data['action'] = 'admin/reports/earnings';
		$this->data['module_name'] = 'finance';

		if($this->request->getPost()) {
			$post_data = $this->request->getPost();
			$post_data['types'] = "history.type in ('interest', 'fund_received', 'commissions')";
			$post_data['type'] = true;
			$post_data['ftype'] = false;
			$this->exportdeposit($post_data);
		}
		
		echo view('admin/finance/reports',$this->data);

	}

	// adminearnings reports
	public function adminearnings()
	{
		$this->db = db_connect();
		$myencrypt = new MyEncrypt(true);
		$this->common_model = model('CommonModel');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!$session->get('admin_login')) {
			return redirect()->to('admin/login');
		}
		$this->common_model = model('CommonModel');
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_reports')
		);

		$this->data['user_list'] = $this->common_model->GetResults('uusers'); 
		$this->data['page_title'] = lang('language_lang.adminearnings_report_page_title');
		$condition = "payment_key in('status') AND payment_value = 'on'";
		$this->data['payment_list'] = $this->common_model->GetPaymentsName($condition);
		$this->data['action'] = 'admin/reports/adminearnings';
		$this->data['module_name'] = 'finance';

		if($this->request->getPost()) {
			$post_data = $this->request->getPost();
			$post_data['types'] = "history.type in ('withdraw_fee', 'transfer_fee')";
			$post_data['type'] = true;
			$post_data['ftype'] = false;
			$this->exportdeposit($post_data);
		}
		
		echo view('admin/finance/reports',$this->data);

	}

	
	// common file for export data
	public function exportdeposit($post_data='') {
		$this->db = db_connect();
       $this->finance_model = model('finance_model');
		if(!$post_data) {
			$post_data = $this->request->getPost();
		}

		$format = $post_data['format'];
		$types = $post_data['types'];
		$type = $post_data['type'];
		$ftype = $post_data['ftype'];

		$condition = $types;

		if($post_data['start_date'] && $post_data['end_date'])
			$condition .= " AND DATE(history.date) >=" . "'" . date('Y-m-d', strtotime($post_data['start_date'])) . "' AND DATE(history.date) <= " . "'" . date('Y-m-d',strtotime($post_data['end_date'])) . "'";
		else if($post_data['start_date'])
			$condition .= " AND DATE(history.date) >=" . "'" . date('Y-m-d', strtotime($post_data['start_date'])) . "'";
		else if($post_data['end_date'])
			$condition .= " AND DATE(history.date) <=" . "'" . date('Y-m-d', strtotime($post_data['end_date'])) . "'";

		if($post_data['min_amount'] && $post_data['max_amount'])
			$condition .= " AND history.amount >=" . "'" . $post_data['min_amount'] . "' AND history.amount <= " . "'" . $post_data['max_amount'] . "'";
		else if($post_data['min_amount'])
			$condition .= " AND history.amount >=" . "'" . $post_data['min_amount'] . "'";
		else if($post_data['max_amount'])
			$condition .= " AND history.amount <=" . "'" . $post_data['max_amount'] . "'";

		if(isset($post_data['user_list'])){
			$user = '';
			foreach ($post_data['user_list'] as $key) {
				$user .= "'".$key[0]."',";
			}
			$user = rtrim($user, ',');
			$condition .= " AND history.uusersid in (" . $user . ")";
		}

		if(isset($post_data['payment_id'])){
			$payment_id = '';
			foreach ($post_data['payment_id'] as $key) {
				$payment_id .= "'".$key."',";
			}
			$payment_id = rtrim($payment_id, ',');
			$condition .= " AND history.currency in (" . $payment_id . ")";
		}

		$condition .= " AND history.is_delete = '0'";
		$currency_info = defaultcurrency();
		
		$history = $this->finance_model->GetTransactions($condition);

		if($format!='PDF')
		{
			$content_body = '
			<table width="100%" cellspacing="0" cellpadding="0">
				<thead>
					<tr style="background-color:#eee;">
						<th width="120" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_date").'</th>
						<th width="110" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_id").'</th>
						<th width="100" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_user_name").'</th>';

						if($type) {
							$content_body .= '<th width="100" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_type").'</th>';
						}

						if($ftype) {
							$content_body .= '<th width="100" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_btc_amount").'</th>';
						}


						$content_body .= '<th width="80" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_amount").'</th>
						<th width="80" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_payment").'</th>
					</tr>
				</thead>
				<tbody>';

					if($history) {
						
						// $this->load->library('MyEncrypt');
						$myencrypt = new MyEncrypt;
						foreach ($history as $row) {
							$condition1 = "payment_key in('status') AND payment_id = '".$row->payment_id."'";
							$payment = $this->finance_model->PaymentName($condition1);
							if($payment) {
								$payment_name = ucfirst($payment->payment_name);
							} else {
								$payment_name = "----";
							}
					
							$content_body .= '<tr>
								<td width="120" style="text-align:center;padding: 10px 5px;font-size:12px;">'.date("Y-m-d H:i:s", strtotime($row->date)).'</td>
								<td width="110" style="text-align:center;padding: 10px 5px;font-size:12px;">'.$row->transactionid.'</td>
								<td width="100" style="text-align:center;padding: 10px 5px;font-size:12px;">'.ucfirst($row->username).'</td>';
								if($type) {
									$content_body .= '<td width="100" style="text-align:center;padding: 10px 5px;font-size:10px;">'.ucfirst($row->type).'</td>';
								}
								if($ftype) {
									$content_body .= '<td width="100" style="text-align:center;padding: 10px 5px;font-size:10px;">'.ucfirst($row->btc_amount).'</td>';
								}
								$content_body .= '<td width="80" style="text-align:center;padding: 10px 5px;font-size:12px;">'.$row->amount.' '.$row->coin_symbol.'</td>
								<td width="80" style="text-align:center;padding: 10px 5px;font-size:12px;">'.$payment_name.'</td>
							</tr>';
						}
					}  
					else { 
						if($type) {
							$content_body .= '<tr><td colspan="6"  width="590" style="text-align:center;padding: 10px 5px;font-size:12px;">'.strtoupper(lang("language_lang.lbl_no_records")).'</td></tr>';
						}
						else if($ftype)
						{
							$content_body .= '<tr><td colspan="6"  width="590" style="text-align:center;padding: 10px 5px;font-size:12px;">'.strtoupper(lang("language_lang.lbl_no_records")).'</td></tr>';
						}	
						else
						{
							$content_body .= '<tr><td colspan="5"  width="590" style="text-align:center;padding: 10px 5px;font-size:12px;">'.strtoupper(lang("language_lang.lbl_no_records")).'</td></tr>';
						}
					}
		$content_body .= '
				</tbody>
			</table> ';

			$this->exportdoc('history', $condition, $format, $type, $content_body);
			}
			else
			{

				$data_cnt = array();
				$i=0;
				if($history)
				{
					foreach ($history as $row) 
					{
						if($row->coin_symbol!="")						
						{
							$curr = $row->coin_symbol;
						}
						else
						{
							$curr = 'BTC';
						}

						$i++;
						$condition1 = "payment_key in('status') AND payment_id = '".$row->payment_id."'";

						$payment = $this->finance_model->PaymentName($condition1);
						if($payment) {
							$payment_name = ucfirst($payment->payment_name);
						} else {
							$payment_name = "----";
						}
							$data_cnt[$i][0] =$row->transactionid;
						    $data_cnt[$i][1] =$row->date;
						    $data_cnt[$i][2] =$row->username;
						    $data_cnt[$i][3] =strtoupper($row->type);
						    $data_cnt[$i][4] =$row->amount.' '.$curr;
						    if($ftype)
						    {
						    	$data_cnt[$i][5] =$row->btc_amount.' '.'BTC';
							}
					}


						$this->exportdoc('history', $condition, $format, $type, $data_cnt,$ftype);
				}
				else
				{
					echo "No Datas Found";
					exit;
				}
			}
	}


	public function exportexchange($post_data='') {
        $this->db = db_connect();
        $this->finance_model = model('finance_model');
		if(!$post_data) {
			$post_data = $this->input->getPost();
		}

		$format = $post_data['format'];
		$types = $post_data['types'];
		$type = $post_data['type'];

		$condition = $types;

		if($post_data['start_date'] && $post_data['end_date'])
		{
			$condition .= " AND DATE(exchange.date) >=" . "'" . date('Y-m-d', strtotime($post_data['start_date'])) . "' AND DATE(exchange.date) <= " . "'" . date('Y-m-d',strtotime($post_data['end_date'])) . "'";
		}
		else if($post_data['start_date'])
		{
			$condition .= " AND DATE(exchange.date) >=" . "'" . date('Y-m-d', strtotime($post_data['start_date'])) . "'";
		}
		else if($post_data['end_date'])
		{
			$condition .= " AND DATE(exchange.date) <=" . "'" . date('Y-m-d', strtotime($post_data['end_date'])) . "'";
		}

		if($post_data['min_amount'] && $post_data['max_amount'])
		{
			$condition .= " AND exchange.price >=" . "'" . $post_data['min_amount'] . "' AND exchange.price <= " . "'" . $post_data['max_amount'] . "'";
		}
		else if($post_data['min_amount'])
		{
			$condition .= " AND exchange.price >=" . "'" . $post_data['min_amount'] . "'";
		}
		else if($post_data['max_amount'])
		{
			$condition .= " AND exchange.price <=" . "'" . $post_data['max_amount'] . "'";
		}

		if(isset($post_data['user_list'])){
			$user = '';
			foreach ($post_data['user_list'] as $key) {
				$user .= "'".$key[0]."',";
			}
			$user = rtrim($user, ',');
			$condition .= " AND exchange.userid in (" . $user . ")";
		}

		if(isset($post_data['payment_id'])){
			$payment_id = '';
			foreach ($post_data['payment_id'] as $key) {
				$payment_id .= "'".$key."',";
			}
			$payment_id = rtrim($payment_id, ',');
			$condition .= " AND exchange.pair in (" . $payment_id . ")";
		}

		if(isset($post_data['exchange_type'])){
			$exchange_type = '';
			foreach ($post_data['exchange_type'] as $key) {
				$exchange_type .= "'".$key."',";
			}
			$exchange_type = rtrim($exchange_type, ',');
			$condition .= " AND exchange.type in (" . $exchange_type . ")";
		}

		if(isset($post_data['exchange_status'])){
			$exchange_status = '';
			foreach ($post_data['exchange_status'] as $key) {
				$exchange_status .= "'".$key."',";
			}
			$exchange_status = rtrim($exchange_status, ',');
			$condition .= " AND exchange.status in (" . $exchange_status . ")";
		}

		//$condition .= " AND history.is_delete = '0'";
		// $currency_info = defaultcurrency();
		
		$history = $this->finance_model->Getuserexchange($condition);
				
		if($format!='PDF')
		{
			$content_body = '
			<table width="100%" cellspacing="0" cellpadding="0">
				<thead>
					<tr style="background-color:#eee;">
						<th width="120" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_date").'</th>
						<th width="110" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_user_name").'</th>
						<th width="100" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_type").'</th>';
						$content_body .= '<th width="80" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_market_pair").'</th>
						<th width="80" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_market_price").'</th>
						<th width="80" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.trans_amnt").'</th>
						<th width="80" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_total_amnt").'</th>
						<th width="80" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.exchange_receiver_Mode").'</th>
						<th width="80" style="text-align:center;padding:15px 5px;font-size:14px;font-weight:bold;text-transform:uppercase;">'.lang("language_lang.lbl_status").'</th>

					</tr>
				</thead>
				<tbody>';

					if($history) {
						
						$this->load->library('MyEncrypt');
						$myencrypt = new MyEncrypt;
						foreach ($history as $row) {
								


								$payment_name = "----";
								
								$users = $this->db->query("select * from uusers where uusersid = '".$row->userid."'");
								$user_det=$users->getResult();

								$receive  = $this->db->query("select * from uusers where uusersid = '".$row->rec_user."'");
								$receiver =$receive->getResult();

								$mark   = $this->db->query("select * from coin_info where coid = '".$row->market_type."'");
								$market = $mark->getResult();

								
								// exit;

								$par  = $this->db->query("select * from coin_info where coid = '".$row->pair."'");
								$pair = $par->getResult();

									
								if($receiver[0]->username!="")
								{
									$receive = $receiver[0]->username;
								} 
								else
								{
									$receive = '------';
								}


								if($row->type=='1')
								{
									$type = lang('language_lang.lbl_exchange_buy');
								}
								elseif($row->type=='2')
								{
									$type = lang('language_lang.lbl_exchange_sell');
								}	
								elseif($row->type=='3')
								{
									$type = 'Ask';
								}
								elseif($row->type=='4')
								{
									$type = 'Bid';
								}
								
								if($row->status=='1')
								{
									$status = lang('language_lang.lbl_exchange_opened');
								}
								elseif($row->status=='2')
								{
									$status = lang('language_lang.lbl_exchange_requested');
								}	
								elseif($row->status=='3')
								{
									$status = lang('language_lang.lbl_exchange_completed');
								}
								elseif($row->status=='4')
								{
									$status = lang('language_lang.lbl_exchange_deleted');
								}	 

								// echo

					
							$content_body .= '<tr>
								<td width="120" style="text-align:center;padding: 10px 5px;font-size:12px;">'.date("Y-m-d H:i:s", strtotime($row->date)).'</td>
								<td width="110" style="text-align:center;padding: 10px 5px;font-size:12px;">'.$row->username.'</td>
								<td width="100" style="text-align:center;padding: 10px 5px;font-size:12px;">'.ucfirst($type).'</td>';
								
								$content_body .= '<td width="100" style="text-align:center;padding: 10px 5px;font-size:12px;">'.$market[0]->coin_symbol.'/'.$pair[0]->coin_symbol.'</td>';

								$content_body .= '<td width="100" style="text-align:center;padding: 10px 5px;font-size:12px;">'.$row->price.' '.$market[0]->coin_symbol.'</td>';
								$content_body .= '<td width="100" style="text-align:center;padding: 10px 5px;font-size:12px;">'.$row->amount.' '.$pair[0]->coin_symbol.'</td>';
								$content_body .= '<td width="100" style="text-align:center;padding: 10px 5px;font-size:12px;">'.$row->total.' '.$market[0]->coin_symbol.'</td>';

								$content_body .= '<td width="100" style="text-align:center;padding: 10px 5px;font-size:12px;">'.$receive.'</td>';

								$content_body .= '<td width="80" style="text-align:center;padding: 10px 5px;font-size:12px;">'.$status.'</td>
							</tr>';

						}
					}  
					else { 
						if($type) {
							$content_body .= '<tr><td colspan="6"  width="590" style="text-align:center;padding: 10px 5px;font-size:12px;">'.strtoupper(lang("language_lang.lbl_no_records")).'</td></tr>';
						} else {
							$content_body .= '<tr><td colspan="5"  width="590" style="text-align:center;padding: 10px 5px;font-size:12px;">'.strtoupper(lang("language_lang.lbl_no_records")).'</td></tr>';
						}

					}
		$content_body .= '
				</tbody>
			</table> ';

			$this->exportdoc1('exchange', $condition, $format, $type, $content_body);
			}
			else
			{

				$data_cnt = array();
				$i=0;
				if($history)
				{
					foreach ($history as $row) 
					{
						$users = $this->db->query("select * from uusers where uusersid = '".$row->userid."'");
						$user_det=$users->getResult();

						$receive  = $this->db->query("select * from uusers where uusersid = '".$row->rec_user."'");
						$receiver =$receive->getResult();

						$mark   = $this->db->query("select * from coin_info where coid = '".$row->market_type."'");
						$market = $mark->getResult();

						$par  = $this->db->query("select * from coin_info where coid = '".$row->pair."'");
						$pair = $par->getResult();

						if($row->type=='1')
						{
							$type = lang('language_lang.lbl_exchange_buy');
						}
						elseif($row->type=='2')
						{
							$type = lang('language_lang.lbl_exchange_sell');
						}	
						elseif($row->type=='3')
						{
							$type = 'Ask';
						}
						elseif($row->type=='4')
						{
							$type = 'Bid';
						}
						
						if($row->status=='1')
						{
							$status = lang('language_lang.lbl_exchange_opened');
						}
						elseif($row->status=='2')
						{
							$status = lang('language_lang.lbl_exchange_requested');
						}	
						elseif($row->status=='3')
						{
							$status = lang('language_lang.lbl_exchange_completed');
						}
						elseif($row->status=='4')
						{
							$status = lang('language_lang.lbl_exchange_deleted');
						}	 

						$i++;
						$payment='';

						if($payment) {
							$payment_name = ucfirst($payment->payment_name);
						} else {
							$payment_name = "----";
						}
						    $data_cnt[$i][0] =$row->date;
						    $data_cnt[$i][1] =$row->username;
						    $data_cnt[$i][2] =strtoupper($type);
						    $data_cnt[$i][3] = $market[0]->coin_symbol.' / '.$pair[0]->coin_symbol;
						    $data_cnt[$i][4] = $row->price.' '.$market[0]->coin_symbol;
							$data_cnt[$i][5] = $row->amount.' '.$pair[0]->coin_symbol;
							$data_cnt[$i][6] = $row->total.' '.$market[0]->coin_symbol;
							$data_cnt[$i][7] = $receiver[0]->username!="" ? $receiver[0]->username : '-----';
							$data_cnt[$i][8] = $status;


						}

						$this->exportdoc1('exchange', $condition, $format, $type, $data_cnt);
				}
				else
				{
					echo "No Datas Found";
					exit;
				}
				
			}

	}

	

	function exportdoc($tableName, $condition, $format, $type, $content_body='',$ftype='')
	{
		$this->db = db_connect();
		helper('download_helper');
		switch (strtolower($format)) {
			case 'csv':
				// $filename = $tableName;

				$filename = $tableName.'.xls';
				$db = db_connect();

				$this->dbutil = (new \CodeIgniter\Database\Database())->loadUtils($db);
				// $this->load->dbutil();		        
				force_download($filename, $content_body);
				$f = fopen($filename, "w");
				foreach ($content_body as $line) {
				    fputcsv($f, $line);
				}
				header('Content-type: application/vnd.ms-excel');
		        header('Content-Disposition: attachment; filename='.$filename.'.xls');
				break;
			case 'xml':

				$filename = $tableName;
				$db = db_connect();

				$this->dbutil = (new \CodeIgniter\Database\Database())->loadUtils($db);
		        $config = array (
					'root'    => 'root',
					'element' => 'element', 
					'newline' => "\n", 
					'tab'    => "\t"
		        );
		        $filename = $tableName.'.xml';
		        //SELECT `history`.*, `uusers`.`username` FROM (`history`) INNER JOIN `uusers` ON `history`.`uusersid` = `uusers`.`uusersid` WHERE `history`.`type` in ('deposit') AND history.uusersid in ('3','4') AND history.payment_name in ('skrill','payeer','okpay','pexpay','solidtrustpay','webmoney','payza','paypal','perfectmoney')

		        if($condition)
		        {
		        	$query = "SELECT ".$tableName.".*, uusers.username FROM ".$tableName." INNER JOIN uusers ON ".$tableName.".uusersid = uusers.uusersid WHERE ".$condition;
		        }
		        else
		        {
		        	$query = "SELECT ".$tableName.".*, uusers.username FROM ".$tableName." INNER JOIN uusers ON ".$tableName.".uusersid = uusers.uusersid";
		        
		        }
		        $result = $this->db->query($query);

		        $data = $this->dbutil->getXMLFromResult($result, $config);
        		force_download($filename, $data);
				break;
			case 'pdf':
				$filename = date('Y-m-d').'_'.$tableName.'.pdf';
				$logo=base_url("/content/site/logo.png");
				//load mPDF library
				// $this->load->library('PDF');
				$pdf = new PDF();
			

			

				
				$pdf->AddPage();



				if($ftype)
				{
					$header = array('Transaction ID', 'Date', 'UserName', 'Type','Amount','BTC Amount');
				}
				else
				{
					$header = array('Transaction ID', 'Date', 'UserName', 'Type','Amount');	
				}
				$pdf->SetFont('Arial','',8);
				$pdf->AliasNbPages();
				$lines = $content_body;
				
				if($lines)
				{
					$data = array();
			    	foreach($lines as $line)
			    	{
			        	$data[] =$line;
			    	}

			    	if($ftype)
			    	{
				    	$pdf->FancyTable($header,$data,$ftype='true');
				    }
				    else
				    {
				    	$pdf->FancyTable($header,$data);	
				    }
				    	
					$pdf->Output($filename,'D');
					//$pdf->Output();
				    // }
				}
				exit;
				break;
			}

		// return redirect()->to('admin/reports/deposit');
	}

	function exportdoc1($tableName, $condition, $format, $type, $content_body='')
	{	

		switch (strtolower($format)) {
			case 'csv':
				// $filename = $tableName;

				$filename = $tableName.'.xls';
					// $this->load->dbutil();		        
				$db = db_connect();

				$this->dbutil = (new \CodeIgniter\Database\Database())->loadUtils($db);
				force_download($filename, $content_body);
				// $f = fopen($filename, "w");
				// foreach ($content_body as $line) {
				//     fputcsv($f, $line);
				// }
				// header('Content-type: application/vnd.ms-excel');
		  //       header('Content-Disposition: attachment; filename='.$filename.'.xls');
				break;
			case 'xml':

				$filename = $tableName;
				$db = db_connect();

				$this->dbutil = (new \CodeIgniter\Database\Database())->loadUtils($db);

				// $this->load->dbutil();
		        $config = array (
					'root'    => 'root',
					'element' => 'element', 
					'newline' => "\n", 
					'tab'    => "\t"
		        );
		        $filename = $tableName.'.xml';
		        //SELECT `history`.*, `uusers`.`username` FROM (`history`) INNER JOIN `uusers` ON `history`.`uusersid` = `uusers`.`uusersid` WHERE `history`.`type` in ('deposit') AND history.uusersid in ('3','4') AND history.payment_name in ('skrill','payeer','okpay','pexpay','solidtrustpay','webmoney','payza','paypal','perfectmoney')
		        $query = "SELECT ".$tableName.".*, uusers.username FROM ".$tableName." INNER JOIN uusers ON ".$tableName.".userid = uusers.uusersid WHERE ".$condition;
		        $result = $this->db->query($query);

		        $data = $this->dbutil->xml_from_result($result, $config);
        		force_download($filename, $data);
				break;
			case 'pdf':
				$filename = date('Y-m-d').'_'.$tableName.'.pdf';
				$logo=base_url()."/content/site/logo.png";
				//load mPDF library
				$this->load->library('PDF_new');
				$pdf = new PDF_new();
			
				/*$header = array('Transaction ID', 'Date', 'UserName', 'Type','Amount','Payment');
				$pdf->SetFont('Arial','',8);
				$pdf->WriteHTML($html);
				$pdf->AliasNbPages();
				$pdf->AddPage();
				$lines = $content_body;
				$data = array();
			    foreach($lines as $line)
			    {
			        $data[] =$line;
			    }
			    $pdf->FancyTable($header,$data);*/
				//$pdf->Output($filename,'D');

				$pdf->AddPage();
				$header = array('Date', 'UserName', 'Type','MarketPair','Market Price','Amount','Total Amount','Receiver','status');
				$pdf->SetFont('Arial','',8);
				$pdf->AliasNbPages();
				$lines = $content_body;

				if($lines)
				{
					$data = array();
			    	foreach($lines as $line)
			    	{
			        	$data[] =$line;
			    	}

			    	$pdf->FancyTable($header,$data);
					$pdf->Output($filename,'D');
					
				}
				

				exit;
				break;
			}

		// return redirect()->to('admin/reports/deposit');

	}

	public function ReferralEarnings()
	{
		$this->data['breadcrumbs'] = array();
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url().'admin'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_transaction')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_reports')
		);

		// $this->data['user_list'] = $this->common_model->GetResults('uusers'); 
		$this->data['page_title'] = lang('language_lang.earnings_report_page_title');
		$condition = "payment_key in('status') AND payment_value = 'on'";
		$this->data['payment_list'] = $this->common_model->GetPaymentsName($condition);
		$this->data['action'] = base_url().'admin/reports/ReferralEarnings';
		$this->data['module_name'] = 'finance';

		if($this->input->post()) {

			$post_data = $this->input->post();
			
			$condition = "type = 'commissions'";

			if($post_data['start_date'] && $post_data['end_date'])
				$condition .= " AND DATE(history.date) >=" . "'" . date('Y-m-d', strtotime($post_data['start_date'])) . "' AND DATE(history.date) <= " . "'" . date('Y-m-d',strtotime($post_data['end_date'])) . "'";
			else if($post_data['start_date'])
				$condition .= " AND DATE(history.date) >=" . "'" . date('Y-m-d', strtotime($post_data['start_date'])) . "'";
			else if($post_data['end_date'])
				$condition .= " AND DATE(history.date) <=" . "'" . date('Y-m-d', strtotime($post_data['end_date'])) . "'";
			

			// if(isset($post_data['user_list'])){
			// 	$user = '';
			// 	foreach ($post_data['user_list'] as $key) {
			// 		$user .= "'".$key[0]."',";
			// 	}
			// 	$user = rtrim($user, ',');
			// 	$condition .= " AND history.uusersid in (" . $user . ")";
			// }

			// if(isset($post_data['payment_id'])){
			// 	$payment_id = '';
			// 	foreach ($post_data['payment_id'] as $key) {
			// 		$payment_id .= "'".$key."',";
			// 	}
			// 	$payment_id = rtrim($payment_id, ',');
			// 	$condition .= " AND history.payment_id in (" . $payment_id . ")";
			// }

			$condition .= " AND history.is_delete = '0' GROUP BY uusersid LIMIT 0, 50";
			
			
			$this->data['referralhis_res'] = $this->finance_model->Getsumof($condition);

			
			echo view('admin/finance/referral_earnings_list',$this->data);	
			
		} else {
			echo view('admin/finance/referral_earnings',$this->data);	
		}
		

	}

	

	function csvToTable($csv_content){
	  $table = "<table>";
	  $rows = str_getcsv($csv_content, "\n");
	  foreach($rows as &$row){
	    $table .= "<tr>";
	    $cells = str_getcsv($row);
	    foreach($cells as &$cell){
	      $table .= "<td>$cell</td>";
	    }
	    $table .= "</tr>";
	  }
	  $table .= "</table>";
	  return $table;
	}
	

}

