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

class Cms extends BaseController {

	/**
	 * 
	 * Start 
	 * Create Date: 29 Jun, 2016
	 * This controller to manage CMS page.
	 * Created karthiga.
	 * @see http://ihyip.com/admin/sitesettings/
	 * Last Updated: 1 Jun, 2016
	 * End
	 * 
	 */

	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')) {

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

			// custom encryption
			// $this->load->library('MyEncrypt');
			$myencrypt = new MyEncrypt;
			$this->isSubadmin();

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

	}

	private function isSubadmin() {
		$this->router = service('router');
		$session = session();

		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' => lang('language_lang.cms_page_text'),
			'href' => base_url('admin/cms')
		);
		$this->data['module_name'] = 'settings';
		$this->data['page_data'] = $this->common_model->GetCms();
        
		echo view('admin/cms',$this->data);

	}
	/*
	public function add($id='') {
		

		$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.cms_page_text')
			
		);
		
		$this->data['languages'] = $this->common_model->GetResults('language_controls');
		$this->data['module_name'] = 'settings';
		$this->data['action'] =  base_url().'admin/cms/add';

		if($id) {
			$myencrypt = new MyEncrypt;
			$page_id = $myencrypt->decode($id);
			$condition = "page_id = '".$page_id."'";
			$this->data['page_data'] = $this->common_model->GetRow('page_controls', $condition);

		}

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

			$this->form_validation->set_rules('page_title', lang("language_lang.cms_page_titlename"), 'trim|required|is_unique[page_controls.page_title]');
			$this->form_validation->set_rules('page_content', lang("language_lang.cms_page_content"), 'trim|required');
			

			// check form validate
			if ($this->form_validation->run() == TRUE) {
				// pr($this->request->getPost());
                 $pageurl = strtolower(str_replace(" ", "-", $this->request->getPost('page_title')));
				 foreach ($this->data['languages'] as $row) {
				 	$pagedata = array(
						"page_title"	=>	$this->request->getPost('page_title'),
                        "page_url"	    =>	$pageurl,
						"page_content"	=>	$this->request->getPost('page_content'),
						"language_id"   =>  $row->language_id,
						"page_status"	=>	($this->request->getPost('page_status')) ? '1' : '0'
					);
					$query_status = $this->db->insert('page_controls',$pagedata);
					// echo $this->db->last_query();
				 }
				 // exit;
				if($query_status) {
					$session->set('success_message', lang('language_lang.cms_success_message'));
					$myencrypt = new MyEncrypt;
					$cmspage = $myencrypt->encode($pageurl);
					return redirect()->to('admin/cms/edit/'.$cmspage);
				} else {
					$session->set('error_message', lang('language_lang.cms_error_message'));
					return redirect()->to('admin/cms');
				}
				
			} 
			
		}
		echo view('admin/addcmspage',$this->data);
	} */
	public function edit($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' => lang('language_lang.cms_page_text'),
			'href' => base_url().'admin/cms'
		);
		
		$this->data['languages'] = $this->common_model->GetResults('language_controls');
		$this->data['module_name'] = 'settings';
		$this->data['action'] = 'admin/cms/edit';

		if($id) {
			$myencrypt = new MyEncrypt;
			$page_url = $myencrypt->decode($id);
			
			$this->data['page_data'] = $this->common_model->GetCMSpage($page_url);
			$this->data['page_url'] = $page_url;
			
		}



		if($this->request->getPost()) {
			$validation->setRules([
				'page_title_1' => ['label'=>lang("language_lang.cms_page_title"),'rules'=>'trim|required'],
				'page_content_1' => ['label'=>lang("language_lang.cms_page_content"),'rules'=>'trim|required|min_length[50]']
			]);
			// $post_data = $this->request->getPost();
			// $this->form_validation->set_rules('page_title_1', lang("language_lang.cms_page_title"), 'trim|required');
			// $this->form_validation->set_rules('page_content_1', lang("language_lang.cms_page_content"), 'trim|required|min_length[50]');

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

				$page_title = $this->request->getPost('page_title_1');
				// $this->form_validation->set_rules('page_content_'.$row->language_id, lang("language_lang.cms_page_content"), 'trim|required');



				$i='0';				
				foreach ($this->data['languages'] as $lang) {


					$lang_id = $lang->language_id;
					$myencrypt = new MyEncrypt;

				    $page_url = $myencrypt->decode($this->request->getPost('page_url'));

						$this->request->getPost('page_content_'.$lang_id);
						// if($this->request->getPost('page_content_'.$lang_id)){
						$defaultpage = $this->common_model->GetCMSpageLang($page_url,$lang_id);
						if($defaultpage) {
							// $page_title = $this->request->getPost('page_title_'.$lang_id);
							$pagedata = array(
								"page_title"	=>	($this->request->getPost('page_title_'.$lang_id)) ? $this->request->getPost('page_title_'.$lang_id) : $page_title,
								"page_content"	=>	$this->request->getPost('page_content_'.$lang_id)
							);
							$builder = $this->db->table('page_controls');
							$builder->where('language_id',$lang_id);
							$builder->where('page_url',$page_url);
							$query_status = $builder->update($pagedata);
						}
						else
						{	
							$condition = "page_url = '".$page_url."' and  language_id = '".$lang_id."'";
							$default = $this->common_model->GetRow('page_controls',$condition);

							if($default=='')
							{
								$pagedata = array(
									"page_title"	=>	($this->request->getPost('page_title_'.$lang_id)) ? $this->request->getPost('page_title_'.$lang_id) : $page_title,
									"page_content"	=>	$this->request->getPost('page_content_'.$lang_id),
									"page_url"      => $page_url,
									"language_id"   => $lang_id,
									"page_status"   => '1' 
									
								);
								// $this->db->where('language_id',$lang_id);
								// $this->db->where('page_url',$page_url);
								$query_status = $this->db->table('page_controls')->insert($pagedata);
							}							

						} 
				}
				

				if($query_status) {
					$session->setFlashData('success_message', lang('language_lang.cms_success_message'));
					return redirect()->to('admin/cms');
				} else {
					$session->setFlashData('error_message', lang('language_lang.cms_error_message'));
					return redirect()->to('admin/cms');
				}
				
			} else {
				$myencrypt = new MyEncrypt;
				$page_title = $myencrypt->decode($this->request->getPost('page_title'));
				$page_url = $myencrypt->decode($this->request->getPost('page_url'));

				$this->data['page_data'] = $this->common_model->GetCMSpage($page_title);

				$this->data['page_title'] = $page_title;
				$this->data['page_url'] = $page_url;
				
			}
			
		}
		echo view('admin/editcmspage',$this->data);	

	}

	public function delete($id) {
        $this->db = db_connect();
        $session = session();
		$myencrypt = new MyEncrypt;
		$page_url = $myencrypt->decode($id);
		if($page_url=='about' || $page_url=='different-services'){

			$session->setFlashData('error_message', lang('language_lang.cms_delete_error_message'));
			return redirect()->to('admin/cms');

		} else {
	$delete_status = $this->db->table('page_controls')->where('page_url',$page_url)->delete();
		if($delete_status) {
				$session->setFlashData('success_message', lang('language_lang.cms_delete_success_message'));
				return redirect()->to('admin/cms');
			} else {
				$session->setFlashData('error_message', lang('language_lang.cms_delete_error_message'));
				return redirect()->to('admin/cms');
			}
		}
    }

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

		$cur_up_data = array(
			"page_status" => '0'
		);
		
		$update_status = $this->db->table('page_controls')->where('page_url',$page_title)->update($cur_up_data);

		if($update_status){
		$session->setFlashData('success_message', lang('language_lang.cms_default_success'));
			return redirect()->to('admin/cms');
		} else {
			$session->setFlashData('error_message', lang('language_lang.cms_default_error'));
			return redirect()->to('admin/cms');
		}

	}

	public function changeActiveStatus($id) {
        $session = session();
		$myencrypt = new MyEncrypt;
		$page_title = $myencrypt->decode($id);
		
		$cur_up_data = array(
			"page_status" => '1'
		);
		$update_status = $this->db->table('page_controls')->where('page_url',$page_title)->update($cur_up_data);

		if($update_status){
			$session->setFlashData('success_message', lang('language_lang.cms_default_success'));
			return redirect()->to('admin/cms');
		} else {
			$session->setFlashData('error_message', lang('language_lang.cms_default_error'));
			return redirect()->to('admin/cms');
		}
		
	}

	public function viewcontents($id) {

		$myencrypt = new MyEncrypt;
		$page_title = $myencrypt->decode($id);
		
		$page_data = $this->common_model->GetCMSpage($page_title);
		
		foreach ($page_data as $row) {
			echo "<h5>".ucfirst($row->language_name)."</h5>";
			echo "<div class='col-lg-12 bg-primary'><h5>".lang('language_lang.cms_page_titlename').': '.$row->page_title."</h5></div>";
			echo "<br/>".$row->page_content;
			echo "<br/>";
		}

	}

	

}

