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


class Slider extends BaseController {

	/**
	 * 
	 * Start 
	 * Create Date: 30 July, 2016
	 * This controller to manage user side home page banner slider.
	 * Created saravanan.
	 * @see http://zhyip.com/
	 * Last Updated: 30 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

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

		} else {
			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.text_extra')
		
		);
		$this->data['module_name'] = 'settings';
		$this->data['slider_data'] = $this->common_model->Getslider('slider_controls');
		$this->data['languages'] = $this->common_model->GetResults('language_controls');        
		echo view('admin/slider/slider',$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 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['languages'] = $this->common_model->GetResults('language_controls');
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.text_home'),
			'href' => base_url('admin')
		);
		$this->data['breadcrumbs'][] = array(
			'text' => lang('language_lang.slider_text'),
			'href' => base_url('admin/slider')
		);
		
		$this->data['module_name'] = 'settings';
		$this->data['action'] =  'admin/slider/add';
        $this->data['user_list'] = $this->common_model->GetResults('uusers');
		if($id) {
			$myencrypt = new MyEncrypt;
			$slider_id = $myencrypt->decode($id);
			$condition = "slider_id = '".$slider_id."' ";
			$this->data['slider_data'] = $this->common_model->GetRow('slider_controls', $condition);
		}

		if($this->request->getPost()) {
			$validation->setRules([
                'title_1' => ['label' => lang("language_lang.lbl_slider_title"), 'rules' => 'trim|required']
			]);
			// $this->form_validation->set_rules('title_1', lang("language_lang.lbl_slider_title"), 'trim|required');
			if($this->request->getPost('slider_id')=='') {
				$validation->setRules([
                'image' => ['label' => lang("language_lang.lbl_slider_image"), 'rules' => 'trim|required']
			]);
			   // $this->form_validation->set_rules('image', lang("language_lang.lbl_slider_image"), 'trim|required');
			 }
			// $this->form_validation->set_rules('description', lang("language_lang.lbl_slider_description"), 'trim|required');

			$logo=$_FILES['image']['tmp_name'];
			if($logo!='') {
				$validation->setRules([
                'image' => ['label' => lang("language_lang.lbl_slider_image"), 'rules' => 'trim|ext_in[image,jpg,png,gif,jpeg]|is_image[image]']
            ]);
				// $this->form_validation->set_rules('image', lang("language_lang.lbl_slider_image"), 'trim|callback_validate_image');
			}
            
            
			// check form validate
			if ($validation->withRequest($this->request)->run() == TRUE) {

				if($this->request->getPost('slider_id')) {
					$slider_id = $this->request->getPost('slider_id');
					 $logo=$_FILES['image']['tmp_name'];
					

	              	foreach ($this->data['languages'] as $lang)
					{
						$lang_id = $lang->language_id;
						$slider_data = array(
						"title"			=>	$this->request->getPost('title_'.$lang_id),
						"description"	=>	$this->request->getPost('description_'.$lang_id),
						"status"		=>	($this->request->getPost('status')) ? '1' : '0',
						);

						// $condition = "slider_id = '".$slider_id."' and  language_id = '".$lang_id."'";
						$condition = "slider_id = '".$slider_id."'";
						$default = $this->common_model->GetRow('slider_controls',$condition);	
						
						

						$condition = "pre_slider_id = '".$slider_id."' ORDER BY language_id DESC LIMIT 1 ";
						$default1 = $this->common_model->GetRow('slider_controls',$condition);																	
                        
					

						if($default)
						{

						
						 // $condition =  "pre_slider_id = '".$slider_id."' and language_id = '".$lang_id."'";;
							$condition = "slider_id = '".$slider_id."'";

						
						
							$query_status = $this->db->table('slider_controls')->where($condition)->update($slider_data);
						}
						else
						{
							
							$insdataar = array();
							foreach ($default1 as $key => $value)
							{
								if($key!='language_id' && $key!='slider_id' && $key!='title' && $key!='description')								
								{
									$insdataar[$key] = $value;
								}
								else if($key=='language_id')
								{
									$insdataar['language_id'] = $lang_id;	
								}
								else if($key=='title')
								{
									$insdataar['title'] = $this->request->getPost('title_'.$lang_id);
								}
								else if($key=='description')
								{
									$insdataar['description'] = $this->request->getPost('description_'.$lang_id);
								}
							}
							$query_status = $this->db->table('slider_controls')->insert($insdataar);
						}	
					}
							  
							
					if($logo!='') {
						$path 				= 'content/slider/';
					$file 			    = $this->request->getFile('image');
					$uim 	    = $this->uploadFile($path, $file);
						// $slider_image_file = $this->upload->data();

						//  $uim = $slider_image_file['file_name'];

						$slide_imag = array(
							"image"	=> $uim
						);			
			
						//$query_status = $this->db->table('slider_controls')->where('pre_slider_id',$slider_id)->update($slide_imag);
						$query_status = $this->db->table('slider_controls')->where('slider_id',$slider_id)->update($slide_imag);
					}		
					

				} else {

					

					$i='0';
					$ade = "";					
					foreach ($this->data['languages'] as $lang)
					{
						$i++;
						$lang_id = $lang->language_id;
						$slider_data = array(
							"title"			=>	$this->request->getPost('title_'.$lang_id),
							"description"	=>	$this->request->getPost('description_'.$lang_id),
							"status"		=>	($this->request->getPost('status')) ? '1' : '0',
							"language_id"      => $lang_id
						);

						$logo=$_FILES['image']['tmp_name'];
					if($logo!='')
					{
					$path 				= 'content/slider/';
					$file 			    = $this->request->getFile('image');
					$upload_file 	    = $this->uploadFile($path, $file);
						// $slider_image_file = $this->upload->data();
						$slide_imag = array(
							"image"	=> $upload_file
						);	
						$slider_data['image'] = $slide_imag;
					}


						
						$query_status = $this->db->table('slider_controls')->insert($slider_data);
						$lastuserid = $this->db->insertID();
					
						if($i==1)						
						{
							

							$pre_data = array(
								"pre_slider_id" => $lastuserid
							);
							
						
							$query_status = $this->db->table('slider_controls')->where('slider_id',$lastuserid)->update($pre_data);
						 	$ade =  $session->set('userdatd',$lastuserid);

						}
						else
						{
							$ade =  $session->get('userdatd');
							$pre_data = array(
								"pre_slider_id" => $ade
							);

							$query_status = $this->db->table('slider_controls')->where('slider_id',$lastuserid)->update($pre_data);
						}
					}

					if($logo!='') {
						// $slider_image_file = $this->upload->data();
					$path 				= 'content/slider/';
					$file 			    = $this->request->getFile('image');
					$upload_file 	    = $this->uploadFile($path, $file);

						 $uim = $upload_file;
						$slide_imag = array(
							"image"	=> $uim
						);			
						$query_status = $this->db->table('slider_controls')->where('pre_slider_id',$ade)->update($slide_imag);
					}							
				}

				if($query_status) {
					$session->setFlashData('success_slider', lang('language_lang.slider_success_message'));
					return redirect()->to('admin/slider');
				} else {
					$session->setFlashData('error_slider', lang('language_lang.slider_error_message'));
					return redirect()->to('admin/slider');
				}
				
			} 
			
		}
		echo view('admin/slider/addslider',$this->data);
	}

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

			$condition = "slider_id = '".$slider_id."'";
			$slider_data = $this->common_model->GetRow('slider_controls',$condition);

			if(file_exists('content/slider/'.$slider_data->image)) {
				unlink('content/slider/'.$slider_data->image);		
			}
			
$delete_status = $this->db->table('slider_controls')->where('slider_id',$slider_id)->delete();

			if($delete_status) {
				$session->setFlashData('success_slider', 'Slider deleted successfully');
				return redirect()->to('admin/slider');
			} else {
				$session->setFlashData('error_slider', 'Slider deleted failed');
				return redirect()->to('admin/slider');
			}	
			
		} else {
			return redirect()->to('admin/slider');
		}
	}

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

			if($update_status){
				$session->setFlashData('success_slider', lang('language_lang.slider_default_success'));
                return redirect()->to('admin/slider');
			} else {
				$session->setFlashData('error_slider', lang('language_lang.slider_default_error'));
				return redirect()->to('admin/slider');
			}

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

			if($update_status){
				$session->setFlashData('success_slider', lang('language_lang.slider_default_success'));
				return redirect()->to('admin/slider');
			} else {
				$session->setFlashData('error_slider', lang('language_lang.slider_default_error'));
			    return redirect()->to('admin/slider');
			}

		
	}

	/* validate image value */
	public function validate_image($str)
	{
		
		$config['upload_path'] = './content/slider/';
		$config['allowed_types'] = 'gif|jpg|png|jpeg';
		$config['encrypt_name'] = TRUE;
		$this->load->library('upload', $config);

		if ( ! $this->upload->do_upload('image')) {
			$this->form_validation->set_message('validate_image', '<p><em class="text-danger">'.$this->upload->display_errors().'</em></p>');
			return false;
		} else {
			
			return true;
		}
		
	}

	

}

