<?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 Tradepairsettings 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()
	{
		$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['pairdata'] = $this->db->table('tradepair_list')->get()->getResult();
		//$this->data['news_data'] = $this->common_model->GetNews();
       // $this->data['languages'] = $this->common_model->GetResults('language_controls');

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

	}


    public function add($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' => 'Trade pairs',
			'href' => base_url('admin/tradepairs')
		);
		
		$this->data['languages'] = $this->common_model->GetResults('language_controls');
		$this->data['module_name'] = 'settings';
		$this->data['action'] =  'admin/tradepairs/add';

		// if($id) {
		// 	$coin_id = $myencrypt->decode($id);
		// 	$condition = "coin_id = '".$id."'";
		// 	$this->data['pairdata'] = $this->db->table('tradepair_list')->where($condition)->getRow();
			
		// }

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

			 $validation->setRules([
				'coin_name' =>['label'=>'Coin name', 'rules'=>'trim|required'],
				'pair_name' =>['label'=>'Pair name', 'rules'=>'trim|required'],
			]);

			$image=$_FILES['coin_image']['tmp_name'];
			if($image!='') {
				$validation->setRule('coin_image','Coin Image', 'trim|ext_in[coin_image,jpg,png,gif,jpeg]|is_image[coin_image]');
			}
			
            // check form validate
			if ($validation->withRequest($this->request)->run() == TRUE) {
                 

				
				 	$pairdata = array(
						"coin_name"	=>	$this->request->getPost('coin_name'),
						"pair_name"	=>	$this->request->getPost('pair_name'),
					    "status"	=>	($this->request->getPost('coin_status')) ? '1' : '0'
					);


					if($image!='') {
				
						// $admin_profile_file = $this->upload->data();
						$path 				= 'styles/images/tradingpair_images/';
						$file 			    = $this->request->getFile('coin_image');
						$upload_file 	    = $this->uploadFile($path, $file);
	
						$news_img = array(
							"coin_image"	=>	$upload_file
						);
						$news_img = implode(',', $news_img);
					    $pairdata["coin_image"] = $news_img;
				
					}
					
					$query_status = $this->db->table('tradepair_list')->insert($pairdata);
					

				if($query_status) {
					$session->setFlashData('success_message', 'Trade Pair Added Successfullly');
					return redirect()->to('admin/tradepairs');
				} else {
					$session->setFlashData('error_message', 'Failed to Add Trade Pair');
					return redirect()->to('admin/tradepairs');
				}
				
			} 
			
		}
		echo view('admin/addtradepairs',$this->data);
	}

    public function uploadFile($path, $image) {


		if ($image->isValid() && ! $image->hasMoved()) {
			$newName = $image->getRandomName();
			$image->move('../'.$path, $newName);
			return $image->getName();
		}
		return "";
	}


    public function delete($id) {
		$session =session();
        $myencrypt = new MyEncrypt;
        $pairid = $myencrypt->decode($id);

        $pair_detail= $this->db->table('tradepair_list')->where('id',$pairid)->get()->getRow();
        $pairname = strtoupper($pair_detail->pair_name);
      

        $count = $this->db->table('trade_process')->where('pair',$pairname.'USDT')->countAllResults();

       if($count == '0')
       {
			
				
			   $delete_status = $this->db->table('tradepair_list')->where('id',$pairid)->delete();
				

				if($delete_status) {
					$session->setFlashData('success_message', 'Tradepair successfully deleted.');
					return redirect()->to('admin/tradepairs');
				} else {
					$session->setFlashData('error_message', 'Failed to delete Tradepair.' );
					return redirect()->to('admin/tradepairs');
				}	
            }
            else
            {
             $session->setFlashData('error_message', "This $pairname pair connected with trade . so can't change the status");
             return redirect()->to('admin/tradepairs');
            }
				
			
	}

	public function changeStatus($id) {
		$session = session();
        $this->db = db_connect();
			$myencrypt = new MyEncrypt;
			$pairid = $myencrypt->decode($id);

            $pair_detail= $this->db->table('tradepair_list')->where('id',$pairid)->get()->getRow();
            $pairname = strtoupper($pair_detail->pair_name);
          

            $count = $this->db->table('trade_process')->where('pair',$pairname.'USDT')->countAllResults();
	
           if($count == '0')
           {
            $cur_up_data = array(
				"status" => '0'
			);
			$update_status = $this->db->table('tradepair_list')->where('id',$pairid)->update($cur_up_data);

			if($update_status){
				$session->setFlashData('success_message', 'Tradepair status updated successfully.');
                return redirect()->to('admin/tradepairs');
			} else {
				$session->setFlashData('error_message', 'Tradepair status updated failed.');
				return redirect()->to('admin/tradepairs');
			}
           }
           else
           {
            $session->setFlashData('error_message', "This $pairname pair connected with trade . so can't change the status");
            return redirect()->to('admin/tradepairs');
           }
           

		
	}
	public function changeActiveStatus($id) {
        $session = session();
			$myencrypt = new MyEncrypt;
            $pairid = $myencrypt->decode($id);

            $pair_detail= $this->db->table('tradepair_list')->where('id',$pairid)->get()->getRow();
            $pairname = strtoupper($pair_detail->pair_name);
          

            $count = $this->db->table('trade_process')->where('pair',$pairname.'USDT')->countAllResults();
            
            if($count == '0')
            {
			$cur_up_data = array(
				"status" => '1'
			);
			
			$update_status = $this->db->table('tradepair_list')->where('id',$pairid)->update($cur_up_data);

			if($update_status){
				$session->setFlashData('success_message', 'Tradepair status updated successfully.');
				return redirect()->to('admin/tradepairs');
			} else {
				$session->setFlashData('error_message', 'Tradepair status updated failed.');
			    return redirect()->to('admin/tradepairs');
			}
        }
        else
        {
         $session->setFlashData('error_message', "This $pairname pair connected with trade . so can't change the status");
         return redirect()->to('admin/tradepairs');
        }

		
	}



}