<?php
class Admin extends CI_Controller{
	private $module;
	private $action;
	private $page;
	private $delim;
	private $rCore;

	public function __construct(){
		parent::__construct();
		$this->rCore = array();
		$sitename = $this->settings_model->get('sitename');
		$sitename = !empty($sitename)?$sitename:'Site Name';
		$sitelogodark = $this->settings_model->get('sitelogodark');
		$sitelogodark = base_url('images/'.(!empty($sitelogodark)?$sitelogodark:'defaultdark.png'));
		$sitelogolight = $this->settings_model->get('sitelogolight');
		$sitelogolight = base_url('images/'.(!empty($sitelogolight)?$sitelogolight:'defaultlight.png'));
		$this->config->set_item('acl_site_name', $sitename);
		$this->config->set_item('acl_logo_dark', $sitelogodark);
		$this->config->set_item('acl_logo_light', $sitelogolight);
		$this->rCore['ajax'] = base_url('lbadmin/ajax');
		$this->rCore['context']['cir'] = md5('acl/removeconfigimage');
        $this->rCore['path']['images'] = base_url('images/');
        $this->rCore['path']['plugin'] = base_url('plugins/');
        $this->module = "__acl_module_";
        $this->action = "__acl_action_";
        $this->page = "";
        $this->delim = "";
	}
	public function index($page='login'){
	    $page = explode('.', $page);
        $this->delim = isset($page[1])?$page[1]:"";
	    $page = $page[0];
	    if($page=='ajax'){
            show_404();
            exit();
        }

		if($this->session->userdata('logged')){

			if($page=='login'){
				redirect('lbadmin/dashboard');
			}

			if($page=='logout'){
				$this->logout();
				redirect('lbadmin');
			}

			if(method_exists($this, $this->action.$page)){
                call_user_func_array(array($this, $this->action.$page), array());
            } else if(file_exists(APPPATH.'views/admin/'.strtolower($page).'.php')){
				$this->page = $page;
				if(method_exists($this, $this->module.$this->page)){
					call_user_func_array(array($this, $this->module.$this->page), array());
				} else $this->loadView(array());
			} else show_404();

		} else {
			$this->login();
		}
		
	}

	public function root(){

		$this->load->view('root', array('url' => $this->settings_model->get('companyurl')));
	}

	public function emailNotExists($email){
		$this->form_validation->set_message('emailNotExists', 'Email not found');
		if(!$this->user_model->emailExists($email)){
			return true;
		} else {
			return false;
		}
	}

	public function currencyNotExists($currency){
	    $this->form_validation->set_message('currencyNotExists', 'This currency already exists');
	    if(!$this->currency_model->exists($currency)){
			return true;
		} else {
            return false;
        }
    }

	public function validUrl($url){
		$this->form_validation->set_message('validUrl', 'Invalid Url');
		return filter_var($url, FILTER_VALIDATE_URL);
	}

	public function validCurrencyRate($rate){
        $this->form_validation->set_message('validCurrencyRate', 'Currency Rate must be greater than 0');
        return ($rate>0);
    }

    public function notExistsGatewaySlug($slug){
        $this->form_validation->set_message('notExistsGatewaySlug', 'Another gateway using the same slug');
        if(!$this->gateway_model->exists($slug)){
            return true;
        } else {
            return false;
        }
    }

	private function loadCore(){
	    if($this->page=='currency'){
            $this->rCore['datatable']['currency'] = base_url('datatable/currency');
        } else if($this->page=='transaction') {
            $this->rCore['datatable']['transaction'] = base_url('datatable/transaction');
            $this->rCore['context']['tbp'] = md5('acl/paybkashmanual');
            $this->rCore['context']['tdp'] = md5('acl/paydynamicmanual');
            $this->rCore['context']['tca'] = md5('acl/canceltransaction');
            $this->rCore['context']['tra'] = md5('acl/removetransaction');
            $this->rCore['context']['tdr'] = md5('acl/reviewtransaction');
            $this->rCore['context']['tae'] = md5('acl/allexpiretransaction');
            $this->rCore['context']['tua'] = md5('acl/aclunpaidtransaction');
        } else if($this->page=='gateway') {
            $this->rCore['datatable']['gateway'] = base_url('datatable/gateway');
        } else if($this->page=='dashboard') {
            $this->rCore['context']['dcl'] = md5('acl/algeneratechartdata');
        }
    }

	private function loadView(array $data){
	    $this->loadCore();
		$header['page'] = $this->page;
		$header['title'] = isset($data['title'])?$data['title']:$this->page;
        $header['select'] = isset($data['select'])?$data['select']:$this->page;
		$footer['page'] = $this->page;
		$footer['rCore'] = $this->rCore;
		$this->load->view('header', $header);
		$this->load->view('admin/'.strtolower($this->page), $data);
		$this->load->view('footer', $footer);
	}

    private function __acl_action_currencydefault(){
        if(!empty($this->delim) && $this->currency_model->exists($this->delim)) {
            $default = $this->currency_model->getDefault();
            if(!$default || strtolower($default->currency)!=strtolower($this->delim)) {
                if($this->currency_model->makeDefault($this->delim)) {
                    $this->session->set_flashdata('currencyupdate', $this->currency_model->currencyLib(true, xss_clean($this->delim))." set as default currency successfully");
                } else {
                    $this->session->set_flashdata('currencyerror', xss_clean(strtoupper($this->delim))." cannot be set as default currency");
                }
            } else {
                $this->session->set_flashdata('currencyerror', xss_clean(strtoupper($this->delim))." already is a default currency");
            }
        } else {
            $this->session->set_flashdata('currencyerror', "Currency ".$this->currency_model->currencyLib(true, xss_clean($this->delim))." not found");
        }
        redirect('lbadmin/currency');
    }

	private function __acl_action_currencyremove(){
	    if(!empty($this->delim) && $this->currency_model->exists($this->delim)) {
	        if($this->currency_model->delete($this->delim)) {
                $this->session->set_flashdata('currencyupdate', "Currency ".$this->currency_model->currencyLib(true, xss_clean($this->delim))." removed successfully");
            } else {
                $this->session->set_flashdata('currencyerror', "Currency ".$this->currency_model->currencyLib(true, xss_clean($this->delim))." cannot be removed");
            }
        } else {
            $this->session->set_flashdata('currencyerror', "Currency ".$this->currency_model->currencyLib(true, xss_clean($this->delim))." not found");
        }
        redirect('lbadmin/currency');
    }

    private function __acl_action_gatewayremove(){
        if(!empty($this->delim) && $this->gateway_model->exists($this->delim)) {
            $gateway = $this->gateway_model->get($this->delim);
            if($this->gateway_model->delete($this->delim)) {
                $this->session->set_flashdata('gatewayupdate', "Gateway ".xss_clean($gateway->name)." removed successfully");
            } else {
                $this->session->set_flashdata('gatewayerror', "Gateway ".xss_clean($gateway->name)." cannot be removed");
            }
        } else {
            $this->session->set_flashdata('gatewayerror', "Requested gateway not found");
        }
        redirect('lbadmin/gateway');
    }

    private function __acl_module_profile(){
        $data = array();
        $data['upload_error'] = array();
        $svstatus = $this->session->flashdata('profileupdate');
		$data['savesuccess'] = $svstatus!=null?$svstatus:false;
        $this->form_validation->set_rules('username', 'Full Name', 'trim|required');
        $this->form_validation->set_rules('usermail', 'Email Address', 'trim|required');
        $user = $this->user_model->get();
        if($this->form_validation->run() === FALSE){
            $data['validation_error'] = $this->form_validation->error_array();
        } else {
            $this->user_model->update($this->input->post('username'), $this->input->post('usermail'));
            $oldpass = $this->input->post('oldpassword');
            $newpass = $this->input->post('newpassword');
            $procced = false;
            if(!empty($oldpass) && !empty($newpass)) {
                if(md5($oldpass)==$user->password){
                    if($this->user_model->changePassword($newpass)) {
                        $procced = true;
                    } else {
                        $data['validation_error']['newpassword'] = 'Password Not Changed!';
                    }
                } else {
                    $data['validation_error']['oldpassword'] = 'Old Password Not Matched!';
                }
            } else {
                $procced = true;
            }

            if($procced){
                $this->session->set_flashdata('profileupdate', true);
                redirect('lbadmin/profile');
            }

        }

        $data['saved_data'] = array(
            'username' => $user->name,
            'usermail' => $user->email,
        );

        $this->loadView($data);
    }

    private function __acl_module_transaction(){
	    $this->loadView(!empty($this->delim) ? array('find'=>$this->delim) : array());
    }

    private function __acl_module_currencyadd(){
        $edit = false;
        $data = array('title' => 'Currency Add', 'select' => 'currency');
        if(!empty($this->delim)){
            $sv = $this->currency_model->get($this->delim);
            if(!empty($sv)) {
                $data['saved_data'] = array(
                    'currencycode' => $sv->currency,
                    'currencyrate' => $sv->rate
                );
                $data['edit_url'] = 'lbadmin/currency/edit/'.xss_clean(strtolower($this->delim));
                $data['title'] = 'Edit Currency';
                $edit = true;
            } else {
                $this->session->set_flashdata('currencyerror', "Currency ".xss_clean(strtoupper($this->delim))." not found");
                redirect('lbadmin/currency');
            }
        }
        if($edit) {
            $this->form_validation->set_rules('currencyrate', 'Currency Rate', 'trim|required|callback_validCurrencyRate');
        } else {
            $this->form_validation->set_rules('currencycode', 'Currency Code', 'trim|required|callback_currencyNotExists');
            $this->form_validation->set_rules('currencyrate', 'Currency Rate', 'trim|required|callback_validCurrencyRate');
        }

        if($this->form_validation->run() === FALSE){
            $data['validation_error'] = $this->form_validation->error_array();
        } else {

            if($edit) {
                if($this->currency_model->update($this->delim, $this->input->post('currencyrate'))) {
                    $this->session->set_flashdata('currencyupdate', "Currency ".$this->currency_model->currencyLib(true, xss_clean($this->delim))." Saved Successfully");
                    redirect('lbadmin/currency');
                } else {
                    $this->session->set_flashdata('currencyerror', "Currency ".$this->currency_model->currencyLib(true, xss_clean($this->delim))." not saved");
                    redirect('lbadmin/currency');
                }
            } else if($this->currency_model->update($this->input->post('currencycode'), $this->input->post('currencyrate'))){
                $this->session->set_flashdata('currencyupdate', "Currency ".$this->currency_model->currencyLib(true, $this->input->post('currencycode'))." Saved Successfully");
                redirect('lbadmin/currency');
            } else {
                $this->session->set_flashdata('currencyerror', "Currency ".$this->currency_model->currencyLib(true, $this->input->post('currencycode'))." not saved");
                redirect('lbadmin/currency');
            }
        }
        $this->loadView($data);
    }

    private function __acl_module_gatewayadd(){
        $data = array('title' => 'Gateway Add', 'select' => 'gateway');
        $edit = false;
        if(!empty($this->delim)) {
            $sv = $this->gateway_model->get($this->delim);
            if (!empty($sv)) {
                $data['saved_data'] = array(
                    'gatewayname' => $sv->name,
                    'gatewayslug' => $sv->slug,
                    'gatewayrbkey' => $sv->resellbizkey,
                    'gatewaycharge' => $sv->charge,
                    'gatewayinstruction' => $sv->instruction,
                    'gatewayfields' => @json_decode($sv->fields, true),
                    'gatewayfieldssort' => $sv->fields_sort
                );
                $data['edit_url'] = 'lbadmin/gateway/edit/' . xss_clean(strtolower($this->delim));
                $data['title'] = 'Edit Gateway';
                $edit = true;
            } else {
                $this->session->set_flashdata('gatewayerror', "Gateway " . xss_clean(strtoupper($this->delim)) . " not found");
                redirect('lbadmin/gateway');
            }
        }
        $this->form_validation->set_rules('gatewayname', 'Name', 'trim|required');
        if(!$edit) {
            $this->form_validation->set_rules('gatewayslug', 'Slug', 'trim|required|callback_notExistsGatewaySlug');
        }
        $this->form_validation->set_rules('gatewayrbkey', 'Resell.Biz Key', 'trim|required');

        if($this->form_validation->run() === FALSE){
            $data['validation_error'] = $this->form_validation->error_array();
        } else {
            if($edit) {
                if($this->gateway_model->update($this->delim, array(
                    'name' => xss_clean($this->input->post('gatewayname')),
                    'resellbizkey' => xss_clean($this->input->post('gatewayrbkey')),
                    'charge' => xss_clean($this->input->post('gatewaycharge')),
                    'fields' => @json_encode($this->input->post('gatewayfields')),
                    'fields_sort' => xss_clean($this->input->post('gatewayfieldssort')),
                    'instruction' => $this->input->post('gatewayinstruction'),
                ))) {
                    $this->session->set_flashdata('gatewayupdate', "Gateway ".xss_clean($sv->name)." Saved Successfully");
                    redirect('lbadmin/gateway');
                } else {
                    $this->session->set_flashdata('gatewayerror', "Gateway ".xss_clean($sv->name)." not saved");
                    redirect('lbadmin/gateway');
                }
            } else if($this->gateway_model->update($this->input->post('gatewayslug'), array(
                'name' => xss_clean($this->input->post('gatewayname')),
                'resellbizkey' => xss_clean($this->input->post('gatewayrbkey')),
                'charge' => xss_clean($this->input->post('gatewaycharge')),
                'fields' => @json_encode($this->input->post('gatewayfields')),
                'fields_sort' => xss_clean($this->input->post('gatewayfieldssort')),
                'instruction' => xss_clean($this->input->post('gatewayinstruction')),
            ))){
                $this->session->set_flashdata('gatewayupdate', "Gateway ".xss_clean($this->input->post('gatewayname'))." Saved Successfully");
                redirect('lbadmin/gateway');
            } else {
                $this->session->set_flashdata('gatewayerror', "Gateway ".xss_clean($this->input->post('gatewayname'))." not saved");
                redirect('lbadmin/gateway');
            }
        }

        $this->loadView($data);
    }

	private function __acl_module_bkash(){
		$data = array();
		$data['bkashErrorCode'] = array(
	        '0000' => array (
	            'c' => '0000',
	            't' => 'Transaction Successful',
	        ),
	        '0010' => array (
	            'c' => '0010, 0011',
	            't' => 'Transaction Pending',
	        ),
	        '0100' => array (
	            'c' => '0100',
	            't' => 'Transaction Reversed',
	        ),
	        '0111' => array (
	            'c' => '0111',
	            't' => 'Transaction Failure',
	        ),
	        '1001' => array (
	            'c' => '1001',
	            't' => 'Invalid Merchant Account',
	        ),
	        '1002' => array (
	            'c' => '1002',
	            't' => 'Invalid trxID',
	        ),
	        '1003' => array (
	            'c' => '1003',
	            't' => 'Authorization Failed (API User Name)',
	        ),
	        '1004' => array (
	            'c' => '1004',
	            't' => 'Authorization Failed (API Password)',
	        )
	    );
	    $svstatus = $this->session->flashdata('bkashsettingsupdate');
		$data['savesuccess'] = $svstatus!=null?$svstatus:false;
		$data['upload_error'] = array();
		$this->form_validation->set_rules('bkashusername', 'Site Name', 'trim|required');
		$this->form_validation->set_rules('bkashpassword', 'Company Url', 'trim|required');
		$this->form_validation->set_rules('bkrskey', 'Company Url', 'trim|required');
		$this->form_validation->set_rules('bkashmerchant', 'Company Url', 'trim|required');
		if($this->form_validation->run() === FALSE){
			$data['validation_error'] = $this->form_validation->error_array();
		} else {
			$this->settings_model->update('bkashusername', $this->input->post('bkashusername'));
			$this->settings_model->update('bkashpassword', $this->input->post('bkashpassword'));
			$this->settings_model->update('bkrskey', $this->input->post('bkrskey'));
			$this->settings_model->update('bkashmerchant', $this->input->post('bkashmerchant'));
			$this->settings_model->update('bkashcharge', $this->input->post('bkashcharge'));
			foreach($data['bkashErrorCode'] AS $bk => $bv){
				$this->settings_model->update('bkasherror'.$bk, $this->input->post('bkasherror'.$bk));
			}
			$procced = true;
			$qrcode = isset($_FILES['bkashqrcode']['name']) && !empty($_FILES['bkashqrcode']['name']) ? $_FILES['bkashqrcode']['name'] : '';
			if(!empty($qrcode)){
				$procced = false;
				$config['upload_path'] = FCPATH . 'images';
				$config['allowed_types'] = 'png|jpg';
				$config['max_size'] = '2048';
				$config['max_width'] = '700';
				$config['max_height'] = '700';
				$this->load->library('upload', $config);
				if($this->upload->do_upload('bkashqrcode')){
					$procced = true;
					$ud = $this->upload->data();
					$this->settings_model->update('bkashqrcode', $ud['file_name']);
				} else {
					$data['upload_error']['bkashqrcode'] = "<b>App Qr Code :</b> ".$this->upload->display_errors('', '');
				}
			}
			if($procced){
				$this->session->set_flashdata('bkashsettingsupdate', true);
				redirect('lbadmin/bkash');
			}
		}
		$data['saved_data'] = array(
			'bkashusername' => $this->settings_model->get('bkashusername'),
			'bkashpassword' => $this->settings_model->get('bkashpassword'),
			'bkrskey' => $this->settings_model->get('bkrskey'),
			'bkashmerchant' => $this->settings_model->get('bkashmerchant'),
			'bkashqrcode' => $this->settings_model->get('bkashqrcode'),
			'bkashcharge' => $this->settings_model->get('bkashcharge')
		);
		foreach($data['bkashErrorCode'] AS $bk => $bv){
			$data['saved_data']['bkasherror'.$bk] = $this->settings_model->get('bkasherror'.$bk);
		}
		$this->loadView($data);
	}

	private function __acl_module_settings(){
		$data = array();
		$data['upload_error'] = array();
		$svstatus = $this->session->flashdata('settingsupdate');
		$data['savesuccess'] = $svstatus!=null?$svstatus:false;
		$this->form_validation->set_rules('sitename', 'Site Name', 'trim|required');
        $this->form_validation->set_rules('companyurl', 'Company Url', 'trim|required|callback_validUrl');
        $this->form_validation->set_rules('gatewayalert', 'Gateway Alert Email ', 'trim|required');
		if($this->form_validation->run() === FALSE){
			$data['validation_error'] = $this->form_validation->error_array();
		} else {
			$this->settings_model->update('sitename', $this->input->post('sitename'));
			$this->settings_model->update('companyurl', $this->input->post('companyurl'));
			$this->settings_model->update('gatewayalert', $this->input->post('gatewayalert'));
			$procced = true;
			$logodark = isset($_FILES['sitelogodark']['name']) && !empty($_FILES['sitelogodark']['name']) ? $_FILES['sitelogodark']['name'] : '';
			$logolight = isset($_FILES['sitelogolight']['name']) && !empty($_FILES['sitelogolight']['name']) ? $_FILES['sitelogolight']['name'] : '';
			if(!empty($logodark) || !empty($logolight)){
				$procced = false;
				$rlogo = 0;
				$ulogo = 0;
				$config['upload_path'] = FCPATH . 'images';
				$config['allowed_types'] = 'png|jpg';
				$config['max_size'] = '2048';
				$config['max_width'] = '700';
				$config['max_height'] = '200';
				$this->load->library('upload', $config);
				if(!empty($logodark)){
					$rlogo++;
					if($this->upload->do_upload('sitelogodark')){
					    $ud = $this->upload->data();
						$this->settings_model->update('sitelogodark', $ud['file_name']);
						$ulogo++;
					} else {
						$data['upload_error']['sitelogodark'] = "<b>Site Logo (Dark) :</b> ".$this->upload->display_errors('', '');
					}
				}
				if(!empty($logolight)){
					$rlogo++;
					if($this->upload->do_upload('sitelogolight')){
					    $ud = $this->upload->data();
						$this->settings_model->update('sitelogolight', $ud['file_name']);
						$ulogo++;
					} else {
						$data['upload_error']['sitelogolight'] = "<b>Site Logo (Light) :</b> ".$this->upload->display_errors('', '');
					}
				}
				if($rlogo==$ulogo) $procced = true;
			}

			if($procced){
				$this->session->set_flashdata('settingsupdate', true);
				redirect('lbadmin/settings');
			}
		}
		$data['saved_data'] = array(
			'sitename' => $this->settings_model->get('sitename'),
			'companyurl' => $this->settings_model->get('companyurl'),
			'sitelogodark' => $this->settings_model->get('sitelogodark'),
			'sitelogolight' => $this->settings_model->get('sitelogolight'),
            'gatewayalert' => $this->settings_model->get('gatewayalert')
		);
        $this->loadView($data);
	}

	private function logout(){
		$this->session->unset_userdata('logged');
		$this->session->unset_userdata('id');
		$this->session->unset_userdata('email');
	}

	private function login(){
		$this->form_validation->set_rules('email', 'Email', 'required|callback_emailNotExists');
		$this->form_validation->set_rules('password', 'Password', 'required');
		if($this->form_validation->run() === FALSE){
		    $this->load->view('login');
		} else {
			$email = $this->input->post('email');
			$password = md5($this->input->post('password'));
			$id = $this->user_model->login($email, $password);
			if($id){
			    $user = $this->user_model->get();
				$data = array(
					'id' => $id,
					'email' => $email,
					'username' => $user->name,
					'logged' => true
				);
				$this->session->set_userdata($data);
                $i = 1;
                $uri = array();
                while ($this->uri->segment($i)) {
                    $uri[] = $this->uri->segment($i);
                    $i++;
                }
				redirect(!empty($uri) ? implode('/',$uri) : 'lbadmin');
			} else {
                $this->session->set_flashdata('password_error', "Password did not match");
                $this->load->view('login');
            }
		}
	}
}