<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); 
error_reporting(0);
/* 
 * 
 * This controller contains the common functions
 * @author Teamtweaks
 *
 */

date_default_timezone_set('Asia/Kolkata'); 

class MY_Controller extends CI_Controller {  
	public $privStatus;	
	public $data = array();
	function __construct()
    { 
        parent::__construct(); 
		ob_start();
		error_reporting(E_ALL ^ (E_NOTICE | E_WARNING));
		$this->load->helper(array('url', 'text'));
		$this->load->library('pagination');
		$this->load->library('session');
		$this->load->helper('cookie');
		$this->load->helper('directory');
		$this->output->set_header('Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0');
		$this->output->set_header('Pragma: no-cache');
		$this->load->library('session');
		
		$this->load->model('category_model');
			$this->load->model('seller_model');
			$this->load->model('user_model');
			
		//$feedbackCount = $this->category_model->getFeedbackCount();
	//	$this->data['cmsPages'] = count($feedbackCount);
		/*
		 * Connecting Database
		 */
		$this->load->database();
		$this->data['demoserverChk'] = $demoserverChk = strpos($this->input->server('DOCUMENT_ROOT'),'casperon/');
		
		/*
		 * Loading CMS Pages
		 */
		if ($_SESSION['cmsPages'] == ''){
			$cmsPages = $this->db->query('select * from '.CMS.' where `status`="Publish" and `hidden_page`="No"');
			$_SESSION['cmsPages'] = $cmsPages->result_array();
		}
		$this->data['cmsPages'] = $_SESSION['cmsPages'];
		
		/*
		 * Getting fancybox count
		 */
		if ($_SESSION['fancyBoxCount'] == ''){
			$fancyBoxList = $this->db->query('select * from '.FANCYYBOX.' where `status`="Publish"');
			$_SESSION['fancyBoxCount'] = $fancyBoxList->num_rows();
		}
		$this->data['fancyBoxCount'] = $_SESSION['fancyBoxCount'];

		/*
		 * Loading active languages
		 */
		if ($_SESSION['activeLgs'] == ''){
			$activeLgsList = $this->db->query('select * from '.LANGUAGES.' where `status`="Active"');
			$_SESSION['activeLgs'] = $activeLgsList->result_array();
		}
		$this->data['activeLgs'] = $_SESSION['activeLgs'];
		
		/*
		 * Checking user language and loading user details
		 */
		if($this->checkLogin('U')!=''){
			$this->data['userDetails'] = $this->db->query('select * from '.USERS.' where `id`="'.$this->checkLogin('U').'"');
			$selectedLangCode = $this->session->userdata('language_code');
	 		if ($this->data['userDetails']->row()->language != $selectedLangCode){
	 			$this->session->set_userdata('language_code',$this->data['userDetails']->row()->language);
	 			$this->session->keep_flashdata('sErrMSGType');
	 			$this->session->keep_flashdata('sErrMSG');				
	 			redirect($this->uri->uri_string());
	 		}
		}
		
		/*
		 * User activity Count
		 */
		if($this->checkLogin('U')!=''){
			$userProfileDetails = $this->db->query('select * from '.USERS.' where `id`="'.$this->checkLogin('U').'"')->result_array();
			$this->data['curruserGroup']=$userProfileDetails[0]['group'];
			
			$userList=explode(',',$userProfileDetails[0]['following']);
			$userList[0]=$this->checkLogin('U');$condition='(';
			foreach($userList as $userIds){
				$condition.="ua.user_id = ".$userIds." or ";
			}
			$len=strlen($condition);
			$condition=substr($condition,0,$len-4);
			$condition.=') and ua.activity_time > "'.$userProfileDetails[0]['last_activity_visit'].'"';	 
			$this->data['userActivityCount']=$userActivityCount= $this->user_model->get_activity($condition)->num_rows();	
			#echo $this->db->last_query(); die;
		}
		if (substr($uriMethod, 0,7) == 'display' || substr($uriMethod, 0,4) == 'view' || $uriMethod == '0'){
			$this->privStatus = '0';
		}else if (substr($uriMethod, 0,3) == 'add'){
			$this->privStatus = '1';
		}else if (substr($uriMethod, 0,4) == 'edit' || substr($uriMethod, 0,6) == 'insert' || substr($uriMethod, 0,6) == 'change'){
			$this->privStatus = '2';
		}else if (substr($uriMethod, 0,6) == 'delete'){
			$this->privStatus = '3';
		}else {
			$this->privStatus = '0';
		}
		$this->data['title'] = $this->config->item('meta_title');;
		$this->data['heading'] = '';
		$this->data['flash_data'] = $this->session->flashdata('sErrMSG');
		$this->data['flash_data_type'] = $this->session->flashdata('sErrMSGType');
		$this->data['adminPrevArr'] = $this->config->item('adminPrev');
 		$this->data['adminEmail'] = $this->config->item('email');	
		$this->data['privileges'] = $this->session->userdata('shopsy_session_admin_privileges');
		$this->data['subAdminMail'] = $this->session->userdata('shopsy_session_admin_email');				
		$this->data['loginID'] = $this->session->userdata('shopsy_session_user_id');				
    	$this->data['allPrev'] = '0';
    	$this->data['logo'] = $this->config->item('logo_image');
    	$this->data['fevicon'] = $this->config->item('fevicon_image');
    	$this->data['footer'] = $this->config->item('footer_content');
    	$this->data['siteContactMail'] = $this->config->item('site_contact_mail');
		$this->data['WebsiteTitle'] = $this->config->item('email_title');
    	$this->data['siteTitle'] = $this->config->item('email_title');
    	$this->data['meta_title'] = $this->config->item('meta_title');
    	$this->data['meta_keyword'] = $this->config->item('meta_keyword');
    	$this->data['meta_description'] = $this->config->item('meta_description');
    	$this->data['giftcard_status'] = $this->config->item('giftcard_status');
		$this->data['sidebar_id'] = $this->session->userdata('session_sidebar_id');
		if ($this->session->userdata('shopsy_session_admin_name') == $this->config->item('admin_name')){
			$this->data['allPrev'] = '1';
		}
		$this->data['paypal_ipn_settings'] = unserialize($this->config->item('payment_0'));
		$this->data['paypal_credit_card_settings'] = unserialize($this->config->item('payment_1'));
		$this->data['authorize_net_settings'] = unserialize($this->config->item('payment_2'));
		
		
		
		
		$this->data['datestring'] = "%Y-%m-%d %h:%i:%s";
		if($this->checkLogin('U')!=''){
 			$this->data['common_user_id'] = $this->checkLogin('U'); 
		}elseif($this->checkLogin('T')!=''){
 			$this->data['common_user_id'] = $this->checkLogin('T'); 
		}else{
			$temp_id = substr(number_format(time() * rand(),0,'',''),0,6);
			$this->session->set_userdata('shopsy_session_temp_id',$temp_id);
			$this->data['common_user_id'] = $temp_id;
		}
		$this->data['emailArr'] = $this->config->item('emailArr');
		$this->data['notyArr'] = $this->config->item('notyArr');
		$this->load->model('minicart_model');
		$this->load->model('product_model');
		$this->data['MiniCartViewSet'] = $this->minicart_model->mini_cart_view($this->data['common_user_id']); 
		
		//echo '<pre>'; print_r($this->data['MiniCartViewSet']); die;
		$this->data['userLists'] = $this->minicart_model->get_all_details(LISTS_DETAILS,array('user_id'=>$this->data['common_user_id']))->result_array();
		$this->data['userRegistry'] = $this->minicart_model->get_all_details(REGISTRY,array('user_id'=>$this->data['common_user_id']))->row();
		#echo '<pre>'; print_r($this->data['userRegistry']); die;
		if($_SESSION['sMainCategories'] == ''){
			$sortArr1 = array('field'=>'cat_position','type'=>'asc');
			$sortArr = array($sortArr1);
			$_SESSION['sMainCategories'] = $this->minicart_model->get_all_details(CATEGORY,array('rootID'=>'0','status'=>'Active'),$sortArr);
		}
		$this->data['mainCategories'] = $_SESSION['sMainCategories'];
		
		if($_SESSION['sColorLists'] == ''){
			$_SESSION['sColorLists'] = $this->minicart_model->get_all_details(LIST_VALUES,array('list_id'=>'1'));
		}
		$this->data['mainColorLists'] = $_SESSION['sColorLists'];
		
		if($_SESSION['sAttributeLists'] == ''){
			$_SESSION['sAttributeLists'] = $this->minicart_model->get_all_details(PRODUCT_ATTRIBUTE,array('status'=>'Active'));
		}
		$this->data['mainAttributeLists'] = $_SESSION['sAttributeLists'];
		
		/*
		 * Like button texts
		 */
		define(LIKE_BUTTON, $this->config->item('like_text'));
		define(LIKED_BUTTON, $this->config->item('liked_text'));
		define(UNLIKE_BUTTON, $this->config->item('unlike_text'));
		
		if($_SESSION['authUrl'] == ''){
			//header( 'Location:http://192.168.1.253/fancyclone/');
		}
		
		
		/*Refereral Start */
		
		if($this->input->get('ref') != '')
		{
			//echo $this->input->get('ref');	
			$referenceName = $this->input->get('ref');
			$this->session->set_userdata('referenceName',$referenceName);
		}
		/*Refereral End */
		
		/* Multilanguage start*/
		if($this->uri->segment('1') != 'admin')
		{
			$selectedLanguage = $this->session->userdata('language_code');
			$defaultLanguage = $this->data['defaultLg'][0]['lang_code'];
			if ($defaultLanguage==''){
				$defaultLanguage = 'en';
			}
			$filePath = APPPATH."language/".$selectedLanguage."/".$selectedLanguage."_lang.php";
			if($selectedLanguage != '')
			{					
				if(!(is_file($filePath)))
				{
					$this->lang->load($defaultLanguage, $defaultLanguage);
				}
				else
				{				
					$this->lang->load($selectedLanguage, $selectedLanguage);
				}

			}
			else
			{
				$this->lang->load($defaultLanguage, $defaultLanguage);
			}
		}
		/* Multilanguage end*/
		//echo $this->lang->line('file1_first')."<br>";
		//echo $this->lang->line('file2_fourth')."<br>";
		/*Shop Header Navigation  */			
		$this->data['selectSellershop_details']=$this->seller_model->get_sellers_data(SELLER,$condition);
		$this->data['shopProduc'] =$this->product_model->view_product_details_from_section($condition1)->result_array();
        $this->data['countryList'] = $this->product_model->get_all_details(COUNTRY_LIST,array())->result();
		/*LAnguage List*/
		$this->data['languagesList']=$this->product_model->get_all_details(LANGUAGES,array('status' => 'Active'));
       /************this function set the default currency detais in session*******/
	   $this->data['currencyList']=$this->product_model->get_all_details(CURRENCY,array('status' => 'Active'));
	   if(!$this->session->userdata('currency_data'))	{	
			if($this->checkLogin('U')!=''){
			$checkUserPreference=$this->product_model->get_all_details(USER,array('id' => $this->checkLogin('U')));
			$condition = array('currency_code'=> $checkUserPreference->row()->currency);
			} else {
			$condition = array('default_currency'=>'Yes');	
			}  
			$result=$this->product_model->get_all_details(CURRENCY,$condition);
			$this->session->set_userdata('currency_data',$result->row_array());
		}
		/*if(!$this->session->userdata('region')){
			if($this->checkLogin('U')!=''){
			$checkUserPreference=$this->product_model->get_all_details(USER,array('id' => $this->checkLogin('U')));
			$condition=array('country_code' => $checkUserPreference->row()->region);
			} else {
			$condition=array('country_code' => 'EV');
			}
			$result=$this->product_model->get_all_details(COUNTRY_LIST,$condition);
			$this->session->set_userdata('region',$result->row_array());
		}*/
		$LangName=$this->product_model->get_all_details(LANGUAGES,array('lang_code'=>$this->session->userdata('language_code')))->row();
		$this->data['languageName'] = $LangName->name;
		$this->data['languageCode'] = $this->session->userdata('language_code');
		$this->data['currencySymbol'] = $this->session->userdata['currency_data']['currency_symbol'];//$this->config->item('currency_currency_symbol');
        $this->data['currencyValue'] = $this->session->userdata['currency_data']['currency_value'];
		$this->data['currencyType'] = $this->session->userdata['currency_data']['currency_code']; //$this->config->item('currency_currency_type');
		$this->data['currencyName'] = $this->session->userdata['currency_data']['currency_name'];
		/*$this->data['regionCode'] = $this->session->userdata['region']['country_code'];
		$this->data['regionName'] = $this->session->userdata['region']['name'];
		if($this->session->userdata['region']['country_code'] == 'EV'){
		$this->data['regionName'] = 'Everywhere';
		}*/
		
    }
 
	
	/**
     * 
     * This function return the session value based on param
     * @param $type
     */
    public function checkLogin($type=''){
    	if ($type == 'A'){
    		return $this->session->userdata('shopsy_session_admin_id');
    	}else if ($type == 'N'){
    		return $this->session->userdata('shopsy_session_admin_name');
    	}else if ($type == 'M'){
    		return $this->session->userdata('shopsy_session_admin_email');
    	}else if ($type == 'P'){
    		return $this->session->userdata('shopsy_session_admin_privileges');
    	}else if ($type == 'U'){
    		return $this->session->userdata('shopsy_session_user_id');
    	}else if ($type == 'T'){
    		return $this->session->userdata('shopsy_session_temp_id');
			
    	}
    }
    
    /**
     * 
     * This function set the error message and type in session
     * @param string $type
     * @param string $msg
     */
    public function setErrorMessage($type='',$msg=''){
    	($type == 'success') ? $msgVal = 'message-green' : $msgVal = 'message-red';
		$this->session->set_flashdata('sErrMSGType', $msgVal);
		$this->session->set_flashdata('sErrMSG', $msg);
    }
   /**
    * 
    * This function check the admin privileges
    * @param String $name	->	Management Name
    * @param Integer $right	->	0 for view, 1 for add, 2 for edit, 3 delete
    */ 
   public function checkPrivileges($name='',$right=''){
   		$prev = '0';
		$privileges = $this->session->userdata('shopsy_session_admin_privileges');
		extract($privileges);
		$userName =  $this->session->userdata('shopsy_session_admin_name');
		$adminName = $this->config->item('admin_name');
		if ($userName == $adminName){
			$prev = '1';
		}
		if (isset(${$name}) && is_array(${$name}) && in_array($right, ${$name})){
			$prev = '1';
		}
		if ($prev == '1'){
			return TRUE;
		}else {
			return FALSE;
		}
   }
   
   /**
    * 
    * Generate random string
    * @param Integer $length
    */
   public function get_rand_str($length='6'){
		return substr(str_shuffle("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"), 0, $length);
   }
   
   /**
    * 
    * Unsetting array element
    * @param Array $productImage
    * @param Integer $position
    */
	public function setPictureProducts($productImage,$position){
		unset($productImage[$position]);
		return $productImage;
	}
	
	/**
	 * 
	 * Resize the image
	 * @param int target_width
	 * @param int target_height
	 * @param string image_name
	 * @param string target_path
	 */
	public function imageResizeWithSpace($box_w,$box_h,$userImage,$savepath){
			
			$thumb_file = $savepath.$userImage;
				
			list($w, $h, $type, $attr) = getimagesize($thumb_file);
				
				$size=getimagesize($thumb_file);
			    switch($size["mime"]){
			        case "image/jpeg":
            			$img = imagecreatefromjpeg($thumb_file); //jpeg file
			        break;
			        case "image/gif":
            			$img = imagecreatefromgif($thumb_file); //gif file
				      break;
			      case "image/png":
			          $img = imagecreatefrompng($thumb_file); //png file
			      break;
				
				  default:
				        $im=false;
				    break;
				}
				
			$new = imagecreatetruecolor($box_w, $box_h);
			if($new === false) {
				//creation failed -- probably not enough memory
				return null;
			}
		
		
			$fill = imagecolorallocate($new, 255, 255, 255);
			imagefill($new, 0, 0, $fill);
		
			//compute resize ratio
			$hratio = $box_h / imagesy($img);
			$wratio = $box_w / imagesx($img);
			$ratio = min($hratio, $wratio);
		
			if($ratio > 1.0)
				$ratio = 1.0;
		
			//compute sizes
			$sy = floor(imagesy($img) * $ratio);
			$sx = floor(imagesx($img) * $ratio);
		
			$m_y = floor(($box_h - $sy) / 2);
			$m_x = floor(($box_w - $sx) / 2);
		
			if(!imagecopyresampled($new, $img,
				$m_x, $m_y, //dest x, y (margins)
				0, 0, //src x, y (0,0 means top left)
				$sx, $sy,//dest w, h (resample to this size (computed above)
				imagesx($img), imagesy($img)) //src w, h (the full size of the original)
			) {
				//copy failed
				imagedestroy($new);
				return null;
				
			}
			imagedestroy($i);
			imagejpeg($new, $thumb_file, 99);
			
	}
	
	
	function getAddEditDetails($excludeArray)
	{
		$inputArrayDetails = array();
		
		foreach($this->input->post() as $key=>$val)
		{
			if(!(in_array($key,$excludeArray)))
			{
				$inputArrayDetails[$key] = trim(addslashes($val));
			}
		}
		return $inputArrayDetails;
	}
	
	
	/**
	 * Image resize
	 * @param int $width
	 * @param int $height
	 * @param string $targetImage Name
	 * @param string $savepath 
	 */
	public function ImageResizeWithCrop($width, $height, $thumbImage, $savePath){
		
		$thumb_file = $savePath.$thumbImage;
		
		$newimgPath = base_url().substr($savePath,2).$thumbImage;
		
		/* Get original image x y*/
		list($w, $h) = getimagesize($thumb_file);
		$size=getimagesize($thumb_file);
		/* calculate new image size with ratio */
		$ratio = max($width/$w, $height/$h);
		$h = ceil($height / $ratio);
		$x = ($w - $width / $ratio) / 2;
		$w = ceil($width / $ratio);
		/* new file name */
		$path = $savePath.$thumbImage;
		/* read binary data from image file */
		
		$imgString = file_get_contents($newimgPath);
		/* create image from string */
		$image = imagecreatefromstring($imgString);
		$tmp = imagecreatetruecolor($width, $height);
		imagecopyresampled($tmp, $image, 0, 0, $x, 0, $width, $height, $w, $h); 
	
		/* Save image */
		switch ($size["mime"]) {
			case 'image/jpeg':
				imagejpeg($tmp, $path, 100);
				break;
			case 'image/png':
				imagepng($tmp, $path, 0);
				break;
			case 'image/gif':
				imagegif($tmp, $path);
				break;
			default:
				exit;
			break;
		}
		return $path;
		/* cleanup memory */
		imagedestroy($image);
		imagedestroy($tmp);
	}
	
	
}
