<?php

namespace App\Controllers\User;
use App\Views;
use App\Models\CommonModel;

class RewardBalance extends BaseController
{
	public function __construct(){
		// $CommonModel = new CommonModel();
		$CommonModel = model('CommonModel');
		$this->db = db_connect();
		$session = \Config\Services::session();
	}
   public function index() {
   		$this->db = db_connect();
		$this->common_model = model('CommonModel');
		$this->finance_model = model('finance_model');
	    $this->userdash_model = model('userdash_model');
		$session = \Config\Services::session();
		$validation = \Config\Services::validation();
		$uri = service('uri');
		if(!($session->get('user_login') || $session->get('admin_login')))
		{			
			return redirect()->to('login');
		}
		$this->indexpage();
    }
	
	public function indexpage() {
		$this->session = session();
		$uusersid = $this->session->get('uusersid');

        $CommonModel = model('CommonModel');
		$condition = "payment_key in('logo','status')";
		$payment_data_list = $CommonModel->GetPaymentsName($condition);
		$site_data = $CommonModel->GetSettingall('infobox');
		if($site_data) {
			
			foreach ($site_data as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}

		} else {
			$site_data_default = $CommonModel->defaultlangSettingall('infobox');
			foreach ($site_data_default as $row) {
				$this->data[$row->site_key] = $row->site_value;
			}
		}

		$site_lang_data = $CommonModel->GetSiteSettings('site');
		
		if($site_lang_data){	
			$site_data = array_merge($site_data, $site_lang_data);
		}

		foreach ($site_data as $row) {
			$this->data[$row->site_key] = $row->site_value;
		}
        $type = ['trade_profit','commissions','fuel'];
      
		$this->data['transaction_history'] = $this->db->table('history')->where('uusersid',$uusersid)->whereNotIn('type',$type)->orderBy('historyid','DESC')->get()->getResult();

		$curdate = date('Y-m-d');

		// $this->data['today_reward_profit'] = curbalancetoday($uusersid);
		// $this->data['total_reward_profit'] = curbalance($uusersid);


		$this->data['today_profit'] = $CommonModel->today_profit($uusersid);

		$this->data['total_profit'] = $CommonModel->total_profit($uusersid);

	 //    $this->data['total_activation_reward'] = $CommonModel->today_reward_profit($uusersid);
		// $this->data['today_activation_reward'] = $CommonModel->total_reward_profit($uusersid);

		$curdate = date('Y-m-d');


	$this->data['total_activation_reward'] = $this->db->query("SELECT SUM(amount) as profit FROM `history` WHERE  `type` = 'commissions'  AND (`description` LIKE '%Reward Activation%' OR `description` LIKE '%Direct commission%' OR `description` LIKE '%Rank Activation%')  AND uusersid = '".$uusersid."' ORDER BY `uusersid` DESC ")->getRow();

	$this->data['today_activation_reward'] = $this->db->query("SELECT SUM(amount) as profit FROM `history` WHERE uusersid = '".$uusersid."' AND `date` LIKE '%$curdate%' AND  `type` = 'commissions' AND (`description`LIKE '%Reward Activation%' OR `description` LIKE '%Direct commission%' OR `description` LIKE '%Rank Activation%') ORDER BY `uusersid` DESC")->getRow();

	$this->data['total_reward_profit'] = $this->db->query("SELECT SUM(amount) as profit FROM `history` WHERE  `type` = 'commissions'  AND uusersid = '".$uusersid."'  ORDER BY `historyid` DESC ")->getRow();

	$this->data['today_reward_profit'] = $this->db->query("SELECT SUM(amount) as profit FROM `history` WHERE `type` = 'commissions'  AND uusersid = '".$uusersid."' AND `date` LIKE '%$curdate%' ORDER BY `historyid` DESC ")->getRow();

		

      $this->data['total_team_reward'] = $this->db->query("SELECT SUM(amount) as profit FROM `history` WHERE uusersid = '".$uusersid."' AND `type` = 'commissions' AND (`description` LIKE '%Direct trading profit%' OR  `description` LIKE '%Trading profit Level%') ORDER BY `historyid` DESC ")->getRow();
      $this->data['today_team_reward'] = $this->db->query("SELECT SUM(amount) as profit FROM `history` WHERE `date` LIKE '%$curdate%' AND uusersid = '".$uusersid."' AND `type` = 'commissions' AND (`description` LIKE '%Direct trading profit%' OR  `description` LIKE '%Trading profit Level%') ORDER BY `historyid` DESC")->getRow();

       $this->data['total_peer_reward'] = $this->db->query("SELECT SUM(amount) as profit FROM `history` WHERE uusersid = '".$uusersid."' AND `type` = 'commissions' AND `description` LIKE '%Same Rank%' ORDER BY `historyid` DESC ")->getRow();

		$this->data['today_peer_reward'] = $this->db->query("SELECT SUM(amount) as profit FROM `history`  WHERE `date` LIKE '%$curdate%' AND uusersid = '".$uusersid."' AND `type` = 'commissions' AND `description` LIKE '%Same Rank%' ORDER BY `historyid` DESC ")->getRow();

		$this->data['total_fuel_deduction'] = $this->db->query("SELECT SUM(amount) as profit FROM `history` WHERE uusersid = '".$uusersid."' AND `type` = 'fuel' ORDER BY `historyid` DESC ")->getRow();

		$this->data['today_fuel_deduction'] = $this->db->query("SELECT SUM(amount) as profit FROM `history` WHERE uusersid = '".$uusersid."' AND `type` = 'fuel' and `date` > DATE(now()) ORDER BY `historyid` DESC ")->getRow();
		
		$this->data['datewis_profit'] = $this->db->query("SELECT date(date) as Time,SUM(amount) as profit FROM `history` WHERE uusersid = '".$uusersid."' AND (type = 'trade_profit' OR type = 'circle_profit') GROUP BY cast(date as date) ORDER BY historyid DESC LIMIT 30 ")->getResult();

		$this->data['sell'] = $this->db->query("SELECT * FROM `api_trade_history` WHERE uuserid = '".$uusersid."' AND `type` = '2' ORDER BY `id` DESC ")->getResult();
	
		$this->data['all_rewards'] = $this->db->query("SELECT * FROM `history` WHERE uusersid = '".$uusersid."' AND `type` IN('commissions')  ORDER BY `historyid` DESC ")->getResult();

		$this->data['activation_reward'] = $this->db->query("SELECT * FROM `history` WHERE uusersid = '".$uusersid."' AND  `type` = 'commissions'  AND (`description` LIKE '%Reward Activation%' OR `description` LIKE '%Direct Commission%' OR `description` LIKE '%Rank Activation%') ORDER BY `historyid`  DESC")->getResult();
        $this->data['team_reward'] = $this->db->query("SELECT * FROM `history` WHERE uusersid = '".$uusersid."' AND `type` = 'commissions' AND (`description` LIKE '%Direct trading profit%' OR `description` LIKE '%Trading profit Level%') ORDER BY `historyid` DESC ")->getResult();

		$this->data['peer_reward'] = $this->db->query("SELECT * FROM `history` WHERE uusersid = '".$uusersid."' AND `type` = 'commissions' AND `description` LIKE '%Same Rank%' ORDER BY `historyid` DESC ")->getResult();

		$this->data['fuel_deduction'] = $this->db->query("SELECT * FROM `history` WHERE uusersid = '".$uusersid."' AND `type` = 'fuel' AND amount > 0 ORDER BY `historyid` DESC ")->getResult();


	

		echo view('user/rewardbalance',$this->data);
	}


	public function revenue_details()
	{

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

        $CommonModel = model('CommonModel');
      
		$this->data['today_profit'] = $CommonModel->today_profit($uusersid);

		$this->data['total_profit'] = $CommonModel->total_profit($uusersid);

		//$this->data['datewis_profit'] = $this->db->query("SELECT date(date) as Time,SUM(amount) as profit FROM `history` WHERE uusersid = '".$uusersid."' AND (type = 'trade_profit' OR type = 'circle_profit') GROUP BY cast(date as date) ORDER BY historyid DESC LIMIT 30 ")->getResult();


        //$this->data['datewis_profit'] = $this->db->query("SELECT * FROM `api_trade_history` WHERE uuserid = '".$uusersid."' AND `type` = '2' GROUP BY date ORDER BY `id` DESC")->getResult();

		//$this->data['datewis_profit_count'] = $this->db->query("SELECT * FROM `api_trade_history` WHERE uuserid = '".$uusersid."' AND `type` = '2' GROUP BY date ORDER BY `id` DESC")->getNumRows();

		$this->data['sell'] = $this->db->query("SELECT * FROM `api_trade_history` WHERE uuserid = '".$uusersid."' AND `type` = '2' ORDER BY `id` DESC ")->getResult();

		echo view('user/revenue_details',$this->data);
	}


	function revenue_records()
	{
	$this->common_model = model('CommonModel');
	$session = \Config\Services::session();
	//print_r($this->request->getpost());

    $uusersid = $this->request->getPost('uusersid');
	$page = $this->request->getPost('page');
	$itemsPerPage = $this->request->getPost('itemsPerPage');
	$offset = ($page - 1) * $itemsPerPage;
	$start_date = $this->request->getPost('start_date');
	$end_date = $this->request->getPost('end_date');

	// print_r($page);
	// echo "<br>";

	if($start_date!='' && $end_date!='')
	{

	
		   $totalItems = $this->db->query("select * from `api_trade_history`  WHERE date between '".$start_date."' and '".$end_date."' and  uuserid = '".$uusersid."' AND `type` = '2' GROUP BY date ORDER BY `id` DESC ")->getNumRows();

		   $get_records = $this->db->query("select * from `api_trade_history` WHERE  date between '".$start_date."' and '".$end_date."' and  uuserid = '".$uusersid."' AND `type` = '2' GROUP BY date ORDER BY `id` DESC limit $offset,$itemsPerPage")->getResult();
          
		  
			
	}
	else
	{
		// echo 'ok1';
		 $totalItems = $this->db->query("select * from `api_trade_history` WHERE uuserid = '".$uusersid."' AND `type` = '2' GROUP BY date ORDER BY `id` DESC ")->getNumRows();

		 $get_records = $this->db->query("select * from `api_trade_history` WHERE uuserid = '".$uusersid."' AND `type` = '2' GROUP BY date ORDER BY `id` DESC limit $offset,$itemsPerPage")->getResult();

	}
	
	$totalPages = ceil($totalItems / $itemsPerPage);

	// print_r($totalItems);
	// echo "<br>";
	// print_r($itemsPerPage);
	// echo "<br>";
	// print_r($totalPages);

	$items = array();

	if($get_records)
	{
		foreach($get_records as $row)
		{
			$profit=$this->db->query("select sum(comm_price) as profit from `api_trade_history` where date='".$row->date."' and uuserid = '".$uusersid."' AND `type` = '2'  ORDER BY `id` DESC")->getRow();
			if($profit)
			{
				$profit_amount=$profit->profit;
			}
			else
			{
				$profit_amount='0';
			}
			

			$date=date("d-M-Y",strtotime($row->date));
          

			$items[] = [
				'profit' =>  number_format($profit_amount,4),
				'date' => date("d-M-Y",strtotime($row->date))
			];

		}
	}
	echo json_encode([
		'items' => $items,
		'hasPrev' => $page > 1,
		'hasNext' => $page < $totalPages,
		'totalPages' => $totalPages,
		'totalitems' => $totalItems
	]);

	}

 public function profit_details($date)
 {
	$this->session = session();
	$uusersid = $this->session->get('uusersid');
	$CommonModel = model('CommonModel');
	

	$date1 = date('Y-m-d',strtotime($date));

	$this->data['sell'] = $this->db->query("SELECT * FROM `api_trade_history` WHERE uuserid = '".$uusersid."' AND `type` = '2' and `date` = '".$date1."' ORDER BY `id` DESC ")->getResult();

	$this->data['datee'] = $date;

	
    echo view('user/profit_details',$this->data);
 }

 public function profit_records($date)
 {
    $this->common_model = model('CommonModel');
	$session = \Config\Services::session();

    $uusersid = $this->request->getPost('uusersid');
	$page = $this->request->getPost('page');
	$itemsPerPage = $this->request->getPost('itemsPerPage');
	$offset = ($page - 1) * $itemsPerPage;
	$date1 = date('Y-m-d',strtotime($date));

		 $totalItems =$this->db->query("SELECT * FROM `api_trade_history` WHERE uuserid = '".$uusersid."' AND `type` = '2' and `date` = '".$date1."' ORDER BY `id` DESC ")->getNumRows();


		 $get_records = $this->db->query("SELECT * FROM `api_trade_history` WHERE uuserid = '".$uusersid."' AND `type` = '2' and `date` = '".$date1."' ORDER BY `id` DESC limit $offset,$itemsPerPage ")->getResult();



	
	
	$totalPages = ceil($totalItems / $itemsPerPage);

	// print_r($totalItems);
	// echo "<br>";
	// print_r($itemsPerPage);
	// echo "<br>";
	// print_r($totalPages);
	// 	print_r($get_records);
	// echo "<br>";
	// exit;

	$items = array();

	if($get_records)
	{
		foreach($get_records as $row)
		{
			
		
           
		
				$get_gas=0;
				if($row->order_id!='')
				{
					
				 $description="fuel fee deduction for order no ".$row->order_id;
			
				
				   $get_gas_fee=$this->db->query("select * from history where description like '%$description%' and uusersid='".$uusersid."' and type in('deducted_gaswallet','fuel')")->getRow();
					if($get_gas_fee)
					{
					 $get_gas=$get_gas_fee->amount;
					}
				}

				if($row->order_id != '')
				{ 
					$order_id = $row->order_id; 
				}
				else{ 
					$order_id = '---'; 
				}
				if($row->time)
				{
					$date = date('Y-m-d H:i:s',(substr($row->time,0,-3)));
				}
				else
				{ 
					$date ='---' ;
				} 

			    $base = substr($row->pair, 0, -4);
                $pair=$base.'/USDT';

				$items[] = [
					'orderNumber' => $order_id  ,
					'exchange' => $pair,
					'profit' => $row->comm_price,
					'gas_fee' => $get_gas ,
					'dateTime' => $date
				];

				
			
			   
			
         }
	}
   echo json_encode([
		'items' => $items,
		'hasPrev' => $page > 1,
		'hasNext' => $page < $totalPages,
		'totalPages' => $totalPages,
		'totalitems' => $totalItems
	]);
 }

}
