<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Advertisement extends CI_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->model('common_model');
		if(get_cookie('admin_id'))
		{
			$this->session->set_userdata('admin_id',get_cookie('admin_id'));
		}
		if(!$this->session->userdata('admin_id'))
		{
			redirect('admin/login');
		}
	}

	public function index(){
		//echo "TEST";die;
		$content_data = array();
		$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
		$content_data['adverts'] = $this->common_model->getAllMultipleJoin('adverts',array('lang_id'=>2),array(array('adverts_lang_values','adverts_lang_values.adverts_id = adverts.id')),'display_order ASC','*,adverts.id');
		//echo '<pre>';print_r($content_data);die;
		$data['content'] = $this->load->view('admin/adverts/list', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function add(){
		$content_data = array();
		if($this->input->post()){
			$total_adverts = $this->common_model->getAll('adverts');
			if(!empty($total_adverts))
			{
				foreach ($total_adverts as $ads) {
					$this->common_model->UpdateData('adverts',array('display_order'=>$ads['display_order']+1),array('id'=>$ads['id']));
				}
			}
			$Details_on = array(
            	'date' => $this->input->post('date'),
				'type' => $this->input->post('type'),
				'link' => $this->input->post('link'),
				'visible' => 1,
				'display_order' => 1,
			);//print_r($Details_on); die;
            $advertId = $this->common_model->insertData('adverts',$Details_on);
            $languages = $this->common_model->getAll('sys_languages');
			$arr= array();
			if(!empty($languages))
			{
				foreach ($languages as $value) {
					$arr1['adverts_id'] = $advertId;
					$arr1['title'] = $this->input->post('title_'.$value['id']);
					$arr1['sub_title'] = $this->input->post('sub_title_'.$value['id']);
					$arr1['intro_text'] = $this->input->post('intro_text_'.$value['id']);
					$arr1['lang_id'] = $value['id'];
					$this->common_model->insertData('adverts_lang_values',$arr1);
				}
			}
			if($_FILES['logofile']['name']!='')
			{
				$imagefolder = 'adverts/';
				$uploadpath = 'assets/userfiles/'. $imagefolder;
				$config = array(
					'upload_path' 		=> FCPATH . $uploadpath . '/',
					'allowed_types' 	=> '*',
					'encrypt_name' 		=> true,
					'file_ext_tolower' 	=> true,
					//'max_size' 			=> (int)MSysSettings::getValue('upload_max_filesize') * 1024,
				);

				$this->load->library('upload', $config);
			   
				if(!$this->upload->do_upload('logofile')) {

					$this->utility->setMsg($this->upload->display_errors(),'ERROR');	
					redirect(base_url().'admin/advertisement/add');
				}

				$uploaddata = $this->upload->data();
				$resizeBlur = $this->avater($uploaddata['raw_name'] .'.'. substr($uploaddata['file_ext'], 1));

				$file = array(
					'image' 	=> base_url().$uploadpath.'160/'.$uploaddata['raw_name'].'.'.substr($uploaddata['file_ext'], 1),
				);

				$this->common_model->UpdateData('adverts',$file,array('id'=>$advertId));
			}
            $this->utility->setMsg('Advertisement added','SUCCESS');	
			redirect(base_url().'admin/advertisement');
		}
		$content_data['adverts'] = $this->common_model->getAll('adverts');
		$content_data['language'] = $this->common_model->getAll('sys_languages');
		//echo '<pre>';print_r($content_data);die;
		$data['content'] = $this->load->view('admin/adverts/add', $content_data, TRUE);
		$this->load->view('admin/layout', $data);
	}
	public function edit($edit_id=''){
		if($edit_id!=''){
			$advertId = base64_decode($edit_id);
			if($this->input->post()){
				$total_adverts = $this->common_model->getAll('adverts');
				$Details_on = array(
	            	'date' => $this->input->post('date'),
					'type' => $this->input->post('type'),
					'link' => $this->input->post('link'),
				);//print_r($Details_on); die;
	            $this->common_model->UpdateData('adverts',$Details_on,array('id'=>$advertId));
	            $languages = $this->common_model->getAll('sys_languages');
				$arr= array();
				if(!empty($languages))
				{
					foreach ($languages as $value) {
						$arr['title'] = $this->input->post('title_'.$value['id']);
						$arr['sub_title'] = $this->input->post('sub_title_'.$value['id']);
						$arr['intro_text'] = $this->input->post('intro_text_'.$value['id']);
						$exist = $this->common_model->getAllRow('adverts_lang_values',array('adverts_id'=>$advertId,'lang_id'=>$value['id']));
						if(empty($exist))
						{
							$arr1['adverts_id'] = $advertId;
							$arr1['title'] = $this->input->post('title_'.$value['id']);
							$arr1['sub_title'] = $this->input->post('sub_title_'.$value['id']);
							$arr1['intro_text'] = $this->input->post('intro_text_'.$value['id']);
							$arr1['lang_id'] = $value['id'];
							$this->common_model->insertData('adverts_lang_values',$arr1);
						}
						else
						{
							$this->common_model->UpdateData('adverts_lang_values',$arr,array('adverts_id'=>$advertId,'lang_id'=>$value['id']));
						}
					}
				}
				if($_FILES['logofile']['name']!='')
				{
					$imagefolder = 'adverts/';
					$uploadpath = 'assets/userfiles/'. $imagefolder;
					$config = array(
						'upload_path' 		=> FCPATH . $uploadpath . '/',
						'allowed_types' 	=> '*',
						'encrypt_name' 		=> true,
						'file_ext_tolower' 	=> true,
						//'max_size' 			=> (int)MSysSettings::getValue('upload_max_filesize') * 1024,
					);

					$this->load->library('upload', $config);
				   
					if(!$this->upload->do_upload('logofile')) {

						$this->utility->setMsg($this->upload->display_errors(),'ERROR');	
						redirect(base_url().'admin/advertisement/edit/'.$edit_id);
					}

					$uploaddata = $this->upload->data();
					$resizeBlur = $this->avater($uploaddata['raw_name'] .'.'. substr($uploaddata['file_ext'], 1));

					$file = array(
						'image' 	=> base_url().$uploadpath.'160/'.$uploaddata['raw_name'].'.'.substr($uploaddata['file_ext'], 1),
					);

					$this->common_model->UpdateData('adverts',$file,array('id'=>$advertId));
				}
	            $this->utility->setMsg('Advertisement added','SUCCESS');	
				redirect(base_url().'admin/advertisement');
			}
			$content_data = array();
			$content_data['language'] = $this->common_model->getAll('sys_languages');
			$content_data['advertDetails'] = $this->common_model->getAllRow('adverts',array('id'=>$advertId)) ;
			$data['loginDetails'] = $this->common_model->getAllRow('feu_userdetails',array('id'=>$this->session->userdata('admin_id')),array('usr_users','feu_userdetails.user_id = usr_users.id')) ;
			$data['content'] = $this->load->view('admin/adverts/edit', $content_data, TRUE);
			$this->load->view('admin/layout', $data);
		}else{
			//echo "Edit Failed";die;
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/advertisement/list');
		}
	}
	public function visibility($advert_id,$updated_status){
		$advertId = base64_decode($advert_id);
		$update_status = array(
			'visible' => $updated_status
		);
		$this->common_model->UpdateData('adverts',$update_status,array('id'=>$advertId));
		$this->utility->setMsg('Home page show status updated','SUCCESS');	
		redirect(base_url().'admin/advertisement');
	}
	public function delete($advert_id='')
	{
		//echo $cat_id;die;
		if($advert_id!='')
		{
			$advertId=base64_decode($advert_id);
			$this->common_model->deleteData('adverts',array('id'=>$advertId));
			$this->common_model->deleteData('adverts_lang_values',array('adverts_id'=>$advertId));
			$this->utility->setMsg('Advertisement deleted','SUCCESS');	
			redirect(base_url().'admin/advertisement');
		}
		else
		{
			$this->utility->setMsg('Invalid id','ERROR');	
			redirect(base_url().'admin/advertisement');
		}
	}
	public function display_order($display_order,$type,$blog_id){
		if($type == 1)
		{
			$new = $display_order-1;
		}
		else
		{
			$new = $display_order+1;
		}
		$update_status = array(
				'display_order' => $new,
			);
		$get = $this->common_model->getAllRow('adverts',array('display_order'=>$new));
		$this->common_model->UpdateData('adverts',array('display_order'=>$display_order),array('id'=>$get['id']));
		$this->common_model->UpdateData('adverts',$update_status,array('id'=>$blog_id));
		$this->utility->setMsg('Display order updated','SUCCESS');	
		redirect(base_url().'admin/advertisement');
	}
	/***************************************/
	public function dirToArray($dir){
  
			$result = array();
			$cdir = scandir($dir);
		   foreach ($cdir as $key => $value)
		   {
			  if (!in_array($value,array(".","..")))
			  {
				 if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
				 {
					$result[$value] = $this->dirToArray($dir . DIRECTORY_SEPARATOR . $value);
				 }
				 else
				 {
					$result[] = $value;
				 }
			  }
		   }
  		return $result;
	}
	
	public function createThumb($spath, $dpath, $maxd) {
	$info = getimagesize($spath);
    $mime = $info['mime'];
	//var_dump($mime);
	if($mime=='image/png'){
		
			$src = ImageCreateFromPNG($spath);
			if (!$src) {return false;} else {
		  $srcw=imagesx($src);
		  $srch=imagesy($src);
		  if ($srcw<$srch) {$height=$maxd;$width=floor($srcw*$height/$srch);}
		  else {$width=$maxd;$height=floor($srch*$width/$srcw);}
		  if ($width>$srcw && $height>$srch) {$width=$srcw;$height=$srch;}  //if image is actually smaller than you want, leave small (remove this line to resize anyway)
		  $thumb=imagecreatetruecolor($width, $height);
			imagealphablending($thumb, false);
		 //if ($height<100) {imagecopyresized($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
		 // else {
			imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));
			//  }
			
				imagepng($thumb, $dpath,9);
			}
		 return true;
	}else{
	
		$src=@imagecreatefromjpeg($spath);

	if (!$src) {return false;} else {
	  $srcw=imagesx($src);
	  $srch=imagesy($src);
	  if ($srcw<$srch) {$height=$maxd;$width=floor($srcw*$height/$srch);}
	  else {$width=$maxd;$height=floor($srch*$width/$srcw);}
	  if ($width>$srcw && $height>$srch) {$width=$srcw;$height=$srch;}  //if image is actually smaller than you want, leave small (remove this line to resize anyway)
	  $thumb=imagecreatetruecolor($width, $height);
	// if ($height<100) {imagecopyresized($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));}
	//  else {
		imagecopyresampled($thumb, $src, 0, 0, 0, 0, $width, $height, imagesx($src), imagesy($src));
		//  }
		
			imagejpeg($thumb, $dpath,90);
		}
		 return true;
	}
  
 
	}
	//avater
	public function avater($picval=''){
		//$sizes=array('60','80','120','160','240','320');
	$sizes=array('160','500');
	   $picdir[]=$this->dirToArray('assets');
		$avatar=$picdir[0]['userfiles']['adverts'];
				foreach($sizes as $size){
				
				$toWidth=$toHeight=$size;
				//destination path
				$folderpath = 'assets/userfiles/adverts/'.$toWidth;

				$org_path = 'assets/userfiles/adverts/'; //source path
				if (!file_exists($folderpath)) { // file exist in target folder
					mkdir($folderpath, 0777, true);
				}
				$source_path = $org_path.'/'.$picval;
				$d_path = $folderpath.'/'.$picval;
				$this->createThumb($source_path,$d_path,$toWidth);
			}//end of avaters resizer
		
		return '1';
	}
}