<?php 
namespace App\Controllers\Admin;
use App\Views;
use App\Models\CommonModel;
use App\Libraries\MyEncrypt;

class Checkip extends BaseController {

	/**
	 * 
	 * Start 
	 * Create Date: 23 September, 2016
	 * This controller to manage checkip page.
	 * Created karthiga.
	 * @see http://zhyip.com/admin/checkip/
	 * Last Updated: 23 September, 2016
	 * End
	 * 
	 */

	public function __construct() {
		$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');
		}
		// admin login only
		if($session->get('admin_login')) {
			// form validation library
			$this->finance_model = model('finance_model');
			$this->userdash_model = model('userdash_model');

			// custom encryption
			$myencrypt = new MyEncrypt;
			$this->isSubadmin();

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

	}

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

	public function index()
	{
		$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_extra')
		);
		$this->data['module_name'] = 'settings';
        
        $this->data['ip_list'] = $this->common_model->Getdistinct('uusers_online');
		echo view('admin/blockip/checkip',$this->data);


	}

	public function listip($id){
$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_extra')
		);
		$this->data['module_name'] = 'settings';

        $this->data['ip_list'] = $this->common_model->Getdistinct('uusers_online');

	    $myencrypt = new MyEncrypt;
		$ip_address = $myencrypt->decode($id);
		
        $condition = "uusers_ip = '".$ip_address."'";
		$this->data['display_access'] = $this->common_model->getResults('uusers_online',$condition);
		echo view('admin/blockip/checkip',$this->data);
        
	}

	public function view($id='') {
		$this->db = db_connect();
		$this->finance_model = model('finance_model');
			$this->userdash_model = model('userdash_model');
		$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');
		}
	     $myencrypt = new MyEncrypt;
		 $uusersid = $myencrypt->decode($id);
         
		 if($uusersid != 'admin' || $uusersid != 'subadmin'){
		    $deposit_condition = "uusersid = '0' AND type IN ('deposit', 'reinvest')";
		    $total_deposit = $this->userdash_model->MyHistoryData1($deposit_condition);

		    $earnings_condition = "type IN ('interest', 'commissions') AND";
		    $earnings_condition .= " uusersid = '0'";
		    $tot_earn = $this->userdash_model->MyHistoryData1($earnings_condition);

		    $interest_condition = "uusersid = '0' AND type IN ('interest')";
		    $tot_interest = $this->userdash_model->MyHistoryData1($interest_condition);

		    $payout_condition = "uusersid = '0' AND type IN ('withdrawal')";
		    $total_payouts = $this->userdash_model->MyHistoryData1($payout_condition);

		    $pending_payout_condition = "uusersid = '0' AND type IN ('withdraw_request')";
		    $total_pending_payouts = $this->userdash_model->MyHistoryData1($pending_payout_condition);

		    $fund_send_condition = "uusersid = '0' AND type IN ('fund_send')";
		    $total_fund_send = $this->userdash_model->MyHistoryData1($fund_send_condition);

		    $fund_received_condition = "uusersid = '0' AND type IN ('fund_received')";
		    $total_fund_received = $this->userdash_model->MyHistoryData1($fund_received_condition);

		    $bonus_condition = "uusersid = '0' AND type IN ('bonus')";
		    $total_bonus = $this->userdash_model->MyHistoryData1($bonus_condition);

		    $penaly_condition = "uusersid = '0' AND type IN ('penalty')";
		    $total_penalty = $this->userdash_model->MyHistoryData1($penaly_condition);

		    $admin_condition = "id = '1'";
		    $user = $this->common_model->GetRow('admin',$admin_condition);
		    $fullname = $user->name;

		    $balance = $this->check_balance($uusersid);

		    $paymentlogo_condition = "payment_key in('logo','status')";
		    $payment_data_list1 = $this->common_model->GetPaymentsName($paymentlogo_condition);
		    $pay_array = array();
				$pay_array1['payment_name'] = '';
				foreach ($payment_data_list1 as $row) {
					
					if($row->payment_name!=$pay_array1['payment_name']){
						$pay_array1['payment_name'] = $row->payment_name;	
						$pay_array1['payment_logo'] = $row->payment_value;	
					} 
					else {
						$pay_array1['payment_status'] = $row->payment_value;
						$pay_array1['payment_id'] = $row->payment_id;
						$pay_array[]= $pay_array1;
					}
			
				}

		    $payment_data_list = $pay_array;

		}

		else {

			$deposit_condition = "type IN ('deposit', 'reinvest')";
		    $total_deposit = $this->userdash_model->MyHistoryData1($deposit_condition);

		    $earnings_condition = "type IN ('interest', 'commissions')";
		    $tot_earn = $this->userdash_model->MyHistoryData1($earnings_condition);

		    $interest_condition = "type IN ('interest')";
		    $tot_interest = $this->userdash_model->MyHistoryData1($interest_condition);

		    $payout_condition = "type IN ('withdrawal')";
		    $total_payouts = $this->userdash_model->MyHistoryData1($payout_condition);

		    $pending_payout_condition = "type IN ('withdraw_request')";
		    $total_pending_payouts = $this->userdash_model->MyHistoryData1($pending_payout_condition);

		    $fund_send_condition = "type IN ('fund_send')";
		    $total_fund_send = $this->userdash_model->MyHistoryData1($fund_send_condition);

		    $fund_received_condition = "type IN ('fund_received')";
		    $total_fund_received = $this->userdash_model->MyHistoryData1($fund_received_condition);

		    $bonus_condition = "type IN ('bonus')";
		    $total_bonus = $this->userdash_model->MyHistoryData1($bonus_condition);

		    $penaly_condition = "type IN ('penalty')";
		    $total_penalty = $this->userdash_model->MyHistoryData1($penaly_condition);

            $admincondition = "id = '".$session->get('userid')."'";
		    $user = $this->common_model->GetRow('admin',$admincondition);
		    $fullname = $user->name;

		    $balance = $this->check_adminbalance();

		    $paymentlogo_condition = "payment_key in('logo','status')";
		    $payment_data_list1 = $this->common_model->GetPaymentsName($paymentlogo_condition);
		    $pay_array = array();
				$pay_array1['payment_name'] = '';
				foreach ($payment_data_list1 as $row) {
					
					if($row->payment_name!=$pay_array1['payment_name']){
						$pay_array1['payment_name'] = $row->payment_name;	
						$pay_array1['payment_logo'] = $row->payment_value;	
					} 
					else {
						$pay_array1['payment_status'] = $row->payment_value;
						$pay_array1['payment_id'] = $row->payment_id;
						$pay_array[]= $pay_array1;
					}
			
				}

		    $payment_data_list = $pay_array;

		}

            $currency_info = defaultcurrency();

		    $content ='<div class="form-group">
											<div class="row">
												<div class="col-md-6">
												<label class="label border-left-primary label-striped">'.lang('language_lang.account_name').'</label>
												    <label style="float:right;" class="badge badge-primary">'.ucfirst($fullname).'</label>
											    </div>
											    <div class="col-md-6">
											    <label class="label border-left-warning label-striped">'.lang('language_lang.place_username').'</label>
												    <label style="float:right;" class="badge badge-warning">'.ucfirst($user->username).'</label>
										       </div>
										    </div>
										    </div>
                                            <div class="form-group">
											<div class="row">
												<div class="col-md-6">
												<label class="label border-left-primary label-striped">'.lang('language_lang.lbl_user_email').'</label>
												    <label style="float:right;" class="badge badge-primary">'.$user->email.'</label>
											    </div>
											    <div class="col-md-6">
											    <label class="label border-left-warning label-striped">'.lang('language_lang.lbl_available_balance').'</label>
												    <label style="float:right;" class="badge badge-warning">'.$currency_info->currency_symbol.''.number_format($balance,$currency_info->deimal_point, '.', '').'</label>
										       </div>
										    </div>
										    </div>
										    <hr><div class="form-group">
													<div class="row">';


														if($payment_data_list) {
															// pr($payment_data_list);
															$this->load->library('MyEncrypt');
															$myencrypt = new MyEncrypt;
															foreach ($payment_data_list as $row) {
																if($row['payment_status']=='On'){
																	if($row['payment_logo'])
																	{
																		$logo_file = base_url().'content/payment/'.$row['payment_logo'];
																	} else {
																		$logo_file = base_url().'content/payment/placeholder.jpg';
																	}
                                                                    $earnings_type  = "'interest', 'commissions', 'bonus', 'fund_received', 'release_deposit', 'deposit'";
                                                                    if($uusersid == '1'){
																	$condition = "type IN (".$earnings_type.") AND payment_id='".$row['payment_id']."'";
                                                                       
                                                                    }else{
                                                                    $condition = "uusersid = '".$uusersid."' AND type IN (".$earnings_type.") AND payment_id='".$row['payment_id']."'";

                                                                    }
                                                                    $earnings = $this->common_model->GetEarnings('history',$condition);
                                                                    $Earnings = ($earnings->earnamt) ? $earnings->earnamt : '0';
									$content .='<div class="col-md-6">
														<div class="col-md-4">
															<label><img width="80" style="height:40px;" class="img-responsive" src="'.$logo_file.'"/></label></div>
														<div style="float:right;" class="col-md-8">	<label style=" float: right;line-height: 35px;">'.$currency_info->currency_symbol."".number_format($Earnings, $currency_info->deimal_point, '.', '').' '.strtoupper($currency_info->currency_unit).'</label></div>
														</div>';
														 } } } 						
														

                                 $content .='</div></div><hr><div class="form-group">
											<div class="row">
												<div class="col-md-6">
												<label class="label border-left-primary label-striped">'.lang('language_lang.account_tot_deposit').'</label>
												    <label style="float:right;" class="badge badge-primary">'.$currency_info->currency_symbol.''.number_format($total_deposit,$currency_info->deimal_point, '.', '').'</label>
											    </div>
											    <div class="col-md-6">
											    <label class="label border-left-warning label-striped">'.lang('language_lang.account_tot_interet').'</label>
												    <label style="float:right;" class="badge badge-warning">'.$currency_info->currency_symbol.''.number_format($tot_interest,$currency_info->deimal_point, '.', '').'</label>
										       </div>
										    </div>
										    </div><div class="form-group">
											<div class="row">
												<div class="col-md-6">
												<label class="label border-left-primary label-striped">'.lang('language_lang.account_withdrawn').'</label>
												    <label style="float:right;" class="badge badge-primary">'.$currency_info->currency_symbol.''.number_format($total_payouts,$currency_info->deimal_point, '.', '').'</label>
											    </div>
	                                            <div class="col-md-6">
												<label class="label border-left-warning label-striped">'.lang('language_lang.account_pen_withdrawal').'</label>
												    <label style="float:right;" class="badge badge-warning">'.$currency_info->currency_symbol.''.number_format($total_pending_payouts,$currency_info->deimal_point, '.', '').'</label>
											    </div>
											    </div>
											    </div>
											<div class="form-group">
											<div class="row">
											<div class="col-md-6">
												<label class="label border-left-primary label-striped">'.lang('language_lang.account_pen_withdrawal').'</label>
												    <label style="float:right;" class="badge badge-primary">'.$currency_info->currency_symbol.''.number_format($total_pending_payouts,$currency_info->deimal_point, '.', '').'</label>
											</div>
											<div class="col-md-6">
											     <label class="label border-left-warning label-striped">'.lang('language_lang.account_fund_Send').'</label>
										         <label style="float:right;" class="badge badge-warning">'.$currency_info->currency_symbol.''.number_format($total_fund_send,$currency_info->deimal_point, '.', '').'</label>
											</div>
											</div>
											</div>
											<div class="form-group">
											<div class="row">
											<div class="col-md-6">
												<label class="label border-left-primary label-striped">'.lang('language_lang.account_fund_received').'</label>
												    <label style="float:right;" class="badge badge-primary">'.$currency_info->currency_symbol.''.number_format($total_fund_received,$currency_info->deimal_point, '.', '').'</label>
											</div>
											<div class="col-md-6">
											<label class="label border-left-warning label-striped">'.lang('language_lang.account_tot_bonus').'</label>
												    <label style="float:right;" class="badge badge-warning">'.$currency_info->currency_symbol.''.number_format($total_bonus,$currency_info->deimal_point, '.', '').'</label>
										    </div>
										    </div>
										    </div><div class="row">
											<div class="col-md-6">
												<label class="label border-left-primary label-striped">'.lang('language_lang.account_tot_penaly').'</label>
												    <label style="float:right;" class="badge badge-primary">'.$currency_info->currency_symbol.''.number_format($total_penalty,$currency_info->deimal_point, '.', '').'</label>
											</div><div class="col-md-6">
											<label class="label border-left-warning label-striped">'.lang('language_lang.account_tot_earnings').'</label>
												    <label style="float:right;" class="badge badge-warning">'.$currency_info->currency_symbol.''.number_format($tot_earn,$currency_info->deimal_point, '.', '').'</label>
											    </div>
											</div></div>';

          echo $content;
		 
	}

	public function delete($id) {
		$session = session();
		$myencrypt = new MyEncrypt;
		$useronline_id = $myencrypt->decode($id);
		if(isset($useronline_id)){
			
			$this->db->where('users_onlineid',$useronline_id);
			$delete_status = $this->db->delete('uusers_online');
			

			if($delete_status) {
				$session->setFlashData('success_message', lang('language_lang.ip_delete_success'));
				return redirect()->to('admin/checkip');
			} else {
				$session->setFlashData('error_message', lang('language_lang.ip_delete_failed'));
				return redirect()->to('admin/checkip');
			}	
			
		} else {
			return redirect()->to('admin/checkip');
		}
	}

	private function check_balance($userid) {
        $this->common_model = model('CommonModel');
        
        $earnings_type  = "'interest', 'commissions', 'bonus', 'fund_received', 'release_deposit'";
        $expenses_type  = "'reinvest', 'withdrawal', 'withdraw_request', 'penalty', 'fund_send', 'withdraw_fee', 'transfer_fee'";

    	// $uusersid = $session->get('uusersid');

		// calculate user earnings 
        $condition = "uusersid = '".$userid."' AND type IN (".$earnings_type.")";
        $earnings = $this->common_model->GetEarnings('history',$condition);

        // calculate user expenses
        $condition1 = "uusersid = '".$userid."' AND type IN (".$expenses_type.")";
        $expenses = $this->common_model->GetEarnings('history',$condition1);

        $Earnings = ($earnings->earnamt) ? $earnings->earnamt : '0';
        $Expenses = ($expenses->earnamt) ? $expenses->earnamt : '0';
        $AvailableBalance = $Earnings - $Expenses;
        
        return ($AvailableBalance) ? $AvailableBalance : '0';
		

	}

	private function check_adminbalance() {
        $this->common_model = model('CommonModel');

        $earnings_type  = "'interest', 'commissions', 'bonus', 'fund_received', 'release_deposit'";
        $expenses_type  = "'reinvest', 'withdrawal', 'withdraw_request', 'penalty', 'fund_send', 'withdraw_fee', 'transfer_fee'";

    	// $uusersid = $session->get('uusersid');

		// calculate user earnings 
        $condition = "type IN (".$earnings_type.")";
        $earnings = $this->common_model->GetEarnings('history',$condition);

        // calculate user expenses
        $condition1 = "type IN (".$expenses_type.")";
        $expenses = $this->common_model->GetEarnings('history',$condition1);

        $Earnings = ($earnings->earnamt) ? $earnings->earnamt : '0';
        $Expenses = ($expenses->earnamt) ? $expenses->earnamt : '0';
        $AvailableBalance = $Earnings - $Expenses;
        
        return ($AvailableBalance) ? $AvailableBalance : '0';
	}
	
}

