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

class News extends BaseController {

	/**
	 * 
	 * Start 
	 * Create Date: 5 July, 2016
	 * This controller to manage faq page.
	 * Created karthiga.
	 * @see http://ihyip.com/admin/faq/
	 * Last Updated: 5 July, 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 {
			$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' => lang('language_lang.text_extra')
		
		);
		$this->data['module_name'] = 'settings';
		$this->data['news_data'] = $this->common_model->GetNews();
        $this->data['languages'] = $this->common_model->GetResults('language_controls');
		//$this->data['news_data'] = $this->common_model->GetResults('admin',$condition);

		echo view('admin/news',$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' => lang('language_lang.news_text'),
			'href' => base_url('admin/news')
		);
		
		$this->data['languages'] = $this->common_model->GetResults('language_controls');
		$this->data['module_name'] = 'settings';
		$this->data['action'] =  'admin/news/add';

		if($id) {
			$news_id = $myencrypt->decode($id);
			$condition = "news_id = '".$news_id."'";
			$this->data['news_data'] = $this->common_model->GetRow('news_controls', $condition);
			
		}

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

			// $image=$_FILES['news_img']['tmp_name'];
			// if($image!='') {
			// 	$validation->setRules([
			// 	'news_img' => ['label' => 'News Image', 'rules' => 'trim|xss_clean|callback_validate_favimage']]);

			
			// }

             $validation->setRules([
				'news_header' =>['label'=>lang("language_lang.news_title"), 'rules'=>'trim|required'],
				'news_content' =>['label'=>lang("language_lang.news_content"), 'rules'=>'trim|required'],
				'news_date' =>['label'=>lang("language_lang.news_date"), 'rules'=>'trim|required']
			]);

			$image=$_FILES['news_image']['tmp_name'];
			if($image!='') {
				$validation->setRule('news_image','News Image', 'trim|ext_in[news_image,jpg,png,gif,jpeg]|is_image[news_image]');
			}
			// $this->form_validation->set_rules('news_header', lang("language_lang.news_title"), 'trim|required');
			// $this->form_validation->set_rules('news_content', lang("language_lang.news_content"), 'trim|required');
			// $this->form_validation->set_rules('news_date', lang("language_lang.news_date"), 'trim|required');
            
			// check form validate
			if ($validation->withRequest($this->request)->run() == TRUE) {
                 

				// print_r($this->request->getPost());
				// exit;
				 	$newsdata = array(
						"news_header"	=>	$this->request->getPost('news_header'),
						"news_content"	=>	$this->request->getPost('news_content'),
						"language_id"   =>  $this->request->getPost('language_id'),
						"news_date"     =>  date('Y-m-d',strtotime($this->request->getPost('news_date'))),
						"news_status"	=>	($this->request->getPost('news_status')) ? '1' : '0'
					);


					if($image!='') {
				
						// $admin_profile_file = $this->upload->data();
						$path 				= 'assets/images/news/';
						$file 			    = $this->request->getFile('news_image');
						$upload_file 	    = $this->uploadFile($path, $file);
	
						$news_img = array(
							"news_image"	=>	$upload_file
						);
						$news_img = implode(',', $news_img);
					    $newsdata["news_image"] = $news_img;
				
					}
					
					$query_status = $this->db->table('news_controls')->insert($newsdata);
					

				if($query_status) {
					$session->setFlashData('success_message', lang('language_lang.news_success_message'));
					return redirect()->to('admin/news');
				} else {
					$session->setFlashData('error_message', lang('language_lang.news_error_message'));
					return redirect()->to('admin/news');
				}
				
			} 
			
		}
		echo view('admin/addnews',$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.news_title'),
			'href' => base_url('admin/news')
		);
		
		$this->data['languages'] = $this->common_model->GetResults('language_controls');
		$this->data['module_name'] = 'settings';
		$this->data['action'] =  'admin/news/edit';

		if($id) {
			$myencrypt = new MyEncrypt;
			$news_id = $myencrypt->decode($id);
			
			$condition = "news_id = '".$news_id."'";
			$this->data['news_data'] = $this->common_model->GetRow('news_controls', $condition);
			
		}

		if($this->request->getPost()) {
			$validation->setRules([
				'news_header' =>['label'=>lang("language_lang.news_title"), 'rules'=>'trim|required'],
				'news_content' =>['label'=>lang("language_lang.news_content"), 'rules'=>'trim|required'],
				'news_date' =>['label'=>lang("language_lang.news_date"), 'rules'=>'trim|required']
			]);

			$file=$_FILES['news_image']['tmp_name'];
			if($file!='') {
			$validation->setRule('news_image', "News image", 'trim|ext_in[news_image,jpg,png,gif,jpeg]|is_image[news_image]');
			}
   //          $this->form_validation->set_rules('news_header', lang("language_lang.news_title"), 'trim|required');
			// $this->form_validation->set_rules('news_content', lang("language_lang.news_content"), 'trim|required');
			// $this->form_validation->set_rules('news_date', lang("language_lang.news_date"), 'trim|required');
			if ($validation->withRequest($this->request)->run() == TRUE) {
           
				 
				$lang_id = $this->request->getPost('language_id');
				$news_id = $this->request->getPost('news_id');
				$this->request->getPost('news_content');

				if($file!='') {
					
					// $admin_profile_file = $this->upload->data();
					$path 				= 'assets/images/news/';
					$file 			    = $this->request->getFile('news_image');
					$upload_file 	    = $this->uploadFile($path, $file);
					$news_img = array(
						"news_image"	=>	$upload_file
					);

				
					$query_status = $this->db->table('news_controls')->where('news_id',$news_id)->update($news_img);
				}

					
							$news_data = array(
								"news_header"	=>	$this->request->getPost('news_header'),
								"news_content"	=>	$this->request->getPost('news_content'),
								"language_id"   =>  $this->request->getPost('language_id'),
								"news_date"     =>  date('Y-m-d',strtotime($this->request->getPost('news_date'))),
								"news_status"	=>	($this->request->getPost('news_status')) ? '1' : '0'
							);
							
							$query_status = $this->db->table('news_controls')->where('news_id',$news_id)->update($news_data);
						
				if($query_status) {
					$session->setFlashData('success_message', lang('language_lang.news_success_message'));
					return redirect()->to('admin/news');
				} else {
					$session->setFlashData('error_message', lang('language_lang.news_error_message'));
					return redirect()->to('admin/news');
				}
			}
			
		}
		echo view('admin/addnews',$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;
			$news_id = $myencrypt->decode($id);
			if(isset($news_id)){
				
					$delete_status = $this->db->table('news_controls')->where('news_id',$news_id)->delete();
				

				if($delete_status) {
					$session->setFlashData('success_message', lang('language_lang.news_delete_success_message'));
					return redirect()->to('admin/news');
				} else {
					$session->setFlashData('error_message', lang('language_lang.news_delete_error_message'));
					return redirect()->to('admin/news');
				}	
				
			} else {
				return redirect()->to('admin/faq');
			}
	}

	public function changeStatus($id) {
		$session = session();
			$myencrypt = new MyEncrypt;
			$news_id = $myencrypt->decode($id);
		
			$cur_up_data = array(
				"news_status" => '0'
			);
			$update_status = $this->db->table('news_controls')->where('news_id',$news_id)->update($cur_up_data);

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

		
	}
	public function changeActiveStatus($id) {
        $session = session();
			$myencrypt = new MyEncrypt;
			$news_id = $myencrypt->decode($id);
			
			$cur_up_data = array(
				"news_status" => '1'
			);
			
			$update_status = $this->db->table('news_controls')->where('news_id',$news_id)->update($cur_up_data);

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

		
	}

	

}

