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

/**
	 * 
	 * Start 
	 * Create Date: 20 July, 2024
	 * This controller to manage trade pairs list.
	 * Created Jeyasri A.G.
     * Last Updated: 20 July, 2024
	 * End
	 * 
	 */


class Tradestrategy extends BaseController {


    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')) {
		    $myencrypt = new MyEncrypt;
			$this->isSubadmin();

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

	}

    private function isSubadmin() {
        $session = session();
        $this->router = service('router');
		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($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' => 'Settings',
			
		);
		

		$this->data['module_name'] = 'settings';
		$this->data['action'] =  'admin/tradestrategy';

        $this->data['strategy'] = $this->db->table('suggested_strategy')->where('id','1')->get()->getRow();

		// print_r($this->request->getPost());
	

        if($this->request->getPost()) {
			$validation->setRules([
				'first_buy_amount' =>['label'=>'First buy amount', 'rules'=>'trim|required|numeric|decimal'],
                'open_position_doubled' =>['label'=>'Double open position', 'rules'=>'trim|required'],
                'margin_column_limit' =>['label'=>'Margin cloumn limit', 'rules'=>'trim|required|numeric|decimal'],
                'whole_profit_ratio' =>['label'=>'Whole profit ratio', 'rules'=>'trim|required|numeric|decimal'],
                'whole_profit_callback' =>['label'=>'Whole profit callback', 'rules'=>'trim|required|numeric|decimal'],
                'buyin_callback' =>['label'=>'Buyin callback', 'rules'=>'trim|required|numeric|decimal'],
                'sub_position_callback' =>['label'=>'Sub position callback', 'rules'=>'trim|required|numeric|decimal'],
				
			
				
			 
			]);
			if($this->request->getPost('call_time'))
			{
				$validation->setRules([
					
					'call_time.*' => ['label' => 'Call time ','rules' => 'trim|required|numeric|decimal'],
				 
				]);
			}
			if($this->request->getPost('order_time'))
			{
				$validation->setRules([
					
					'order_time.*' => ['label' => 'Order time ','rules' => 'trim|required|numeric|decimal'],
				 
				]);
			}
              
			if($this->request->getPost('rep_time'))
			{
				$validation->setRules([
					
					'rep_time.*' => ['label' => 'Sup position ','rules' => 'trim|required|numeric|decimal'],
				 
				]);
			}
	
			

		 if ($validation->withRequest($this->request)->run() == TRUE) {

			
   
            $trade1 = $this->request->getPost('call_time');
			$buyin_ratio_times = $this->request->getPost('order_time');
			$num=$this->request->getPost('margin_column_limit');
				
			if($num >= 5)
			{
				$j=0;
				$sub_positon =  $this->request->getPost('rep_time');
				$buyin_ratio_times = $this->request->getPost('order_time');
				$trade2 =array(implode(',',$buyin_ratio_times));		
				$trade3 =array(implode(',',$sub_positon));						
			}
			else
			{							
				$trade2 = $buyin_ratio_times;	
			}




			$tade1=implode(',',$trade1);
			$tade2=implode(',',$trade2);
			
			if(!empty($trade3))
			{
			 $tade3=implode(',',$trade3);
			}
			else
			{
			$tade3 = 0;
			}

			   $strategydata = array(
                    "first_buy_amount"	=>	$this->request->getPost('first_buy_amount'),
                    "open_position_doubled"	=>	$this->request->getPost('open_position_doubled'),
                    "margin_column_limit"   =>  $this->request->getPost('margin_column_limit'),
                    "whole_profit_ratio"     => $this->request->getPost('whole_profit_ratio'),
                    "whole_profit_callback"	=>	$this->request->getPost('whole_profit_callback'),
                    "buyin_callback"	=>	$this->request->getPost('buyin_callback'),
                    "sub_position_callback"	=>	$this->request->getPost('sub_position_callback'),
                    "margincall_drop"		=> 	$tade1,
			        "buyin_ratio_times"		=>	$tade2,
			        "sub_position"           => $tade3
                );
							
				$query_status = $this->db->table('suggested_strategy')->where('id','1')->update($strategydata);
						
				if($query_status) {
					$session->setFlashData('success_message', 'Startegy detail updated successfylly.');
					return redirect()->to('admin/tradestrategy');
				} else {
					$session->setFlashData('error_message', 'Strategy detail updated Failed.');
					return redirect()->to('admin/tradestrategy');
				}
			}
		
		
		}

       
		

		echo view('admin/tradestrategy',$this->data);

	}


    public function margin_column_limit()
	{
		
		$session= \Config\Services::session();
		//$id =$session->get('uusersid');
		$num = service('request')->getPost('number');	
		//$pair = service('request')->getPost('pair');	
   
		
		$this->db = db_connect();

	     $qry = $this->db->table('suggested_strategy')->where('id',1)->get()->getRow();
	
					
		// $num=$qry->margin_column_limit;			
		$lmt=$qry->sub_position;
		$margin=explode(',',$lmt);
		$margn=array_slice($margin,-$num);

	

		if($num >= 5)
		{
			$j=0;
			for ($i=4; $i < $num; $i++) 
			{ 
				$c=$i+1;	
				if($c=='1')
			{
			    $disp=$c."st";
			}
			else if($c=='2')
			{
			    $disp=$c."nd";
			}
			else if($c=='3')
			{
			    $disp=$c."rd";
			}
			else
			{
			    $disp=$c."th";    
			}
						
				echo   "<div class='form-group' style='margin-bottom:5px;margin-right:10px'>";
				echo    "<label class=''>The ".$disp."sub-position</label>";
				echo   "<div class='input-group'>";
				if (isset($margn[$j])) {
				echo    "<input type='text' class='form-control mt-1'  name='rep_time[]' required  value=".$margn[$j].">";
				}
				else
				{
					echo    "<input type='text' class='form-control mt-1'  name='rep_time[]' required  value=''>";
				}
				echo    "<span class='input-group-addon mt-1'>% </span> </div>";
				echo   "</div>";

				$j++;
			}
        }
	   else
	   {
		 echo "";
	   }

	}
	


	public function margin_column_limit1()
	{

		$validation = \Config\Services::validation();
		$session= \Config\Services::session();
		$id =$session->get('uusersid');
		$num = service('request')->getPost('number1');
	  	

		$this->db = db_connect();
	

        $qry = $this->db->table('suggested_strategy')->where('id',1)->get()->getRow();

		$marg=$qry->margincall_drop;
		$margin=explode(',',$marg);

		for ($i=0; $i < $num; $i++) 
		{ 
			$c=$i+1;	
			if($c=='1')
			{
			    $disp=$c."st";
			}
			else if($c=='2')
			{
			    $disp=$c."nd";
			}
			else if($c=='3')
			{
			    $disp=$c."rd";
			}
			else
			{
			    $disp=$c."th";    
			}
	
			echo   "<div class='form-group ' style='margin-bottom:5px;margin-right:10px'>";
			echo    "<label class=''>The ".$disp." call</label>";
			echo   "<div class='input-group'>";
			if (isset($margin[$i])) {
			echo    "<input type='text' class='form-control mt-1 dynamic-field' required name='call_time[]' value=".$margin[$i].">";
			}else
			{
				echo  "<input type='text' class='form-control mt-1 dynamic-field' required name='call_time[]' value=''>";
			}
			echo    "<span class='input-group-addon mt-1'>% </span> </div>";
		 

			echo   "</div>";
		}
	}

	public function margin_column_limit2()
	{

	

		$session= \Config\Services::session();
		$id =$session->get('uusersid');
		$num = service('request')->getPost('number2');
	   
		$this->db = db_connect();

        $qry = $this->db->table('suggested_strategy')->where('id',1)->get()->getRow();

		$buy=$qry->buyin_ratio_times;
		$buyin=explode(',',$buy);

		for ($i=0; $i < $num; $i++) 
		{ 
			$c=$i+1;
			if($c=='1')
			{
			    $disp=$c."st";
			}
			else if($c=='2')
			{
			    $disp=$c."nd";
			}
			else if($c=='3')
			{
			    $disp=$c."rd";
			}
			else
			{
			    $disp=$c."th";    
			}
			
			echo   "<div class='form-group' style='margin-bottom:5px;margin-right:10px'> ";
			echo    "<label class='control-label'>The ".$disp." order amount</label>";
			echo   "<div class='input-group'>";
			if (isset($buyin[$i])) {
			echo    "<input type='text' class='form-control mt-1' required  name='order_time[]' value=".$buyin[$i].">";
			}
			else
			{
				echo  "<input type='text' class='form-control mt-1' required  name='order_time[]' value=''>";
			}
			echo    "<span class='input-group-addon mt-1'>Times</span> </div>";
			echo   "</div>";
	   }


	}

}