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

class Currencysettings extends BaseController {
	/**
	 * 
	 * Start 
	 * Create Date: 17 Jun, 2016
	 * This controller to manage site currency setting page.
	 * Created saravana kumar.
	 * @see http://ihyip.com/admin/sitesettings/
	 * Last Updated: 23 Jun, 2016
	 * End
	 * 
	 */

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

		// admin login only
		if($session->get('admin_login')) {

			// form validation library
			// $this->load->library('form_validation');
			$this->isSubadmin();

			
		} else {
			if(isset($_COOKIE['remember_token'])) {

				$myencrypt = new MyEncrypt;
				$token_value = $myencrypt->decode($this->input->cookie('remember_token'));
				$this->isCookie($token_value);	

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

	}

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

	private function isCookie($values) 
	{
		$value = explode('|', $values);
		$result = $this->common_model->getPassword($value[0]);
		$hashed_password = $result->password;
		if(crypt(urlencode($value[1]), $hashed_password)) 
		{
			$array = array(
				"logged_in" => TRUE,
				"userid" => $result->id,
				"admin_login" => TRUE
			);
			$session->set($array);
		} 
		else 
		{
			redirect()->to('admin/login');
		}
	}

	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_settings')
		);

		$this->data['module_name'] = 'settings';
		$this->data['currency_data'] = $this->common_model->GetResults('currency_controls');

		echo view('admin/settings/currency',$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->db = db_connect();
		$uri = service('uri');
		$id = $uri->getSegment(4);
		$validation = \Config\Services::validation();
		$session = \Config\Services::session();
		// $myencrypt = \Config\Services::encrypter();
		$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_settings'),
			'href' => base_url().'admin/sitesettings'
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_currency'),
			'href' => base_url().'admin/currencysettings'
		);
		
		$this->data['module_name'] = 'settings';
		$this->data['action'] =  'admin/currencysettings/add';
		if($id) {
			$myencrypt = new MyEncrypt(true);
			$currency_id = $myencrypt->decode($id);
			$condition = "currency_id = '".$currency_id."'";
			$this->data['cur_data'] = $this->common_model->GetRow('currency_controls', $condition);
		}

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

			if($this->request->getPost('currency_id')) {
				
				$currency_id = $this->request->getPost('currency_id');
				$validation->setRules([
				'name' => ['label' => lang("language_lang.label_cur_name"), 'rules' => 'trim|required|alpha|min_length[4]|edit_unique[currency_controls.currency_name'.$currency_id.']'],
				'unit' => ['label' => lang("language_lang.label_cur_unit"), 'rules' => 'trim|required|min_length[3]|max_length[4]|edit_unique[currency_controls.currency_unit'.$currency_id.']']
				]);
				
			} else {
				$validation->setRules([
				'name' => ['label' => lang("language_lang.label_cur_name"), 'rules' => 'trim|required|alpha|min_length[4]|is_unique[currency_controls.currency_name]'],
				'unit' => ['label' => lang("language_lang.label_cur_unit"), 'rules' => 'trim|required|min_length[3]|max_length[4]|is_unique[currency_controls.currency_unit]']
				]);
			}

			$validation->setRules([
				'symbol' => ['label' => lang("language_lang.label_cur_symbol"), 'rules' => 'trim|required|max_length[10]'],
				'deimal_point' => ['label' => lang("language_lang.label_cur_decimal_point"), 'rules' => 'trim|required|numeric|max_length[1]']
				]);
		
			

			// check form validate
			if ($validation->withRequest($this->request)->run() == TRUE) {
				

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

					$condition = "currency_id = '".$this->request->getPost('currency_id')."' ";
					$curr_data = $this->common_model->GetRow('currency_controls',$condition);
					
					if($curr_data->currency_default=='1') {

						$currencydata = array(
							"currency_name"	=>	strtolower($this->request->getPost('name')),
							"currency_unit"	=>	strtolower($this->request->getPost('unit')),
							"currency_symbol"	=>	strtolower($this->request->getPost('symbol')),
							"currency_default"	=>	'1',
							"currency_status"	=>	'1',
							"deimal_point"	=>	strtolower($this->request->getPost('deimal_point'))
						);	

					} 
					else {

						$currencydata = array(
							"currency_name"	=>	strtolower($this->request->getPost('name')),
							"currency_unit"	=>	strtolower($this->request->getPost('unit')),
							"currency_symbol"	=>	strtolower($this->request->getPost('symbol')),
							"currency_default"	=>	($this->request->getPost('default')) ? '1' : '0',
							"currency_status"	=>	($this->request->getPost('status')) ? '1' : '0',
							"deimal_point"	=>	strtolower($this->request->getPost('deimal_point'))
						);

					}
					
					$query_status = $this->db->table('currency_controls')->where('currency_id',$this->request->getPost('currency_id'))->update($currencydata);

					if($this->request->getPost('default') !='0'){

					$cur_up_data = array(
						"currency_default" => '0'
					);
					$this->db->table('currency_controls')->where("currency_id != '".$this->request->getPost('currency_id')."'")->update($cur_up_data);
					}

				} else {

					$currencydata = array(
						"currency_name"	=>	strtolower($this->request->getPost('name')),
						"currency_unit"	=>	strtolower($this->request->getPost('unit')),
						"currency_symbol"	=>	strtolower($this->request->getPost('symbol')),
						"currency_default"	=>	($this->request->getPost('default')) ? '1' : '0',
						"currency_status"	=>	($this->request->getPost('status')) ? '1' : '0',
						"deimal_point"	=>	strtolower($this->request->getPost('deimal_point'))
					);
					
				$query_status = $this->db->table('currency_controls')->insert($currencydata);
					$currency_id = $this->db->insertID();

					if($this->request->getPost('default') !='0'){

						$cur_up_data = array(
						"currency_default" => '0'
					);

					$this->db->table('currency_controls')->where("currency_id != '".$currency_id."'")->update($cur_up_data);


					}
					
				}
				// echo $this->db->last_query();exit;

				if($query_status) {
					$session->setFlashData('success_message', lang('language_lang.cur_success_message'));
					return redirect()->to('admin/currencysettings');
				} else {
					$session->setFlashData('error_message', lang('language_lang.cur_error_message'));
					return redirect()->to('admin/currencysettings');
				}
				
			} 
			
		}
		echo view('admin/settings/addcurrency',$this->data);
	}

	public function delete($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');
		}
		
		$id = $uri->getSegment(4);
		if($id) {
			$myencrypt = new MyEncrypt(true);
			
			$currency_id = $myencrypt->decode($id);

			if($currency_id!=1){

				$condition = "currency_id = '".$currency_id."' ";
				$curr_data = $this->common_model->GetRow('currency_controls',$condition);
				
				if($curr_data->currency_default) {

					$curr_up_data = array(
						"currency_default" => '1'
					);
					$this->db->where('currency_id', '1');
					$update_status = $this->db->table('currency_controls')->update($curr_up_data);

					$delete_status = $this->db->table('currency_controls')->where('currency_id',$currency_id)->delete();

				} else {
					$delete_status = $this->db->table('currency_controls')->where('currency_id',$currency_id)->delete();
				}

				if($delete_status) {
					$session->setFlashData('success_message', lang('language_lang.cur_success_message'));
					return redirect()->to('admin/currencysettings');
				} else {
					$session->setFlashData('error_message', lang('language_lang.cur_error_message'));
					return redirect()->to('admin/currencysettings');
				}	
				
			} else {
				$session->setFlashData('error_message', lang('language_lang.cur_error_default_message'));
				return redirect()->to(site_url('admin/currencysettings'));
			}

		} else {
			return redirect()->to(site_url('admin/currencysettings'));
		}
		if($id) {
			$myencrypt = new MyEncrypt(true);
			$currency_id = $myencrypt->decode($id);

			// $condition = "currency_id = '".$currency_id."' ";
			// $curr_data = $this->common_model->GetRow('currency_controls',$condition);
			// echo $curr_data->currency_default;
			$delete_status = $this->db->table('currency_controls')->where('currency_id',$currency_id)->delete();

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

	public function makedefaults() 
	{
		if($this->request->getPost()) 
		 {
			$myencrypt = new MyEncrypt(true);
			$currency_id = $myencrypt->decode($this->request->getPost('id'));
			$condition = "currency_id = '".$currency_id."' ";
			$curr_data = $this->common_model->GetRow('currency_controls',$condition);
			if($curr_data->currency_default==0)
			{
				$cur_up_data = array(
					"currency_default" => '0'
				);
				$this->db->table('currency_controls')->update($cur_up_data);

				$cur_up_data1 = array(
					"currency_default" => '1',
					"currency_status"	=> '1'
				);

				$default_status = $this->db->table('currency_controls')->where('currency_id',$currency_id)->update($cur_up_data1);

				if($default_status){
					$session->setFlashData('success_message', lang('language_lang.cur_success_message_default'));
					echo 1;
				} else {
					$session->setFlashData('error_message', lang('language_lang.cur_error_message_default'));
					echo 0;
				}

			}

		}
	}

}

