<?php
/**
* Application level Controller
*
* This file is application-wide controller file. You can put all
* application-wide controller-related methods here.
*
* PHP 5
*
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* Redistributions of files must retain the above copyright notice.
*
* @copyright     Copyright 2005-2012, Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link          http://cakephp.org CakePHP(tm) Project
* @package       app.Controller
* @since         CakePHP(tm) v 0.2.9
* @license       MIT License (http://www.opensource.org/licenses/mit-license.php)
*/

App::uses('Controller', 'Controller');

/**
* Application Controller
*
* Add your application-wide methods in the class below, your controllers
* will inherit them.
*
* @package       app.Controller
* @link http://book.cakephp.org/2.0/en/controllers.html#the-app-controller
*/
class AppController extends Controller {

function _setErrorLayout() {  
   	if ($this->name == 'CakeError') {
			$meta_title = "404 Page not Found";
			$meta_keyword = "";
			$meta_desc= "";

			$this->set(compact('meta_title','meta_keyword','meta_desc'));			
		}    
}                   

function beforeRender () {  

      $this->_setErrorLayout();
    
}

    public $components = [
        'Session',
        'Auth',
        'Flash',
       // 'DebugKit.Toolbar',
        // 'Security',
    ];


public function generateSlug($title){
	$pattern="[?()\/&#\,\;\.$+%]";
	$title = trim($title);
//	$slug_name=ereg_replace($pattern,"-",$title);
	$slug_name=preg_replace($pattern,"-",$title);
	$slug_name=strtolower($slug_name);
	$slug_name=str_replace("  ","-",$slug_name);
	$slug_name=str_replace(" ","-",$slug_name);
	$slug_name=str_replace("_","-",$slug_name);
	$slug_name=str_replace("%","",$slug_name);
	$slug_name=str_replace("__","-",$slug_name);
	$slug_name=str_replace("--","-",$slug_name);
	$slug_name=strtolower($slug_name);
	return $this->slugit($title);
	
}
 
	public function slugit($str, $replace=array(), $delimiter='-') { 
		if ( !empty($replace) ) {   
			$str = str_replace((array)$replace, ' ', $str);	
		}
			$clean = $str; // iconv('UTF-8', 'ASCII//TRANSLIT', $str);	
			$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);	
			$clean = strtolower(trim($clean, '-'));
			$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);	
			return $clean;	
	}

	

public function process_image($image_file = null,$service_slug = null,$folderpath = '') {
		
		$final_image = "";
		
		if($service_slug == null) {
			
			$service_slug = time();
		}
		
		
		 $ext = substr(strtolower(strrchr($image_file['name'], '.')), 1); //get the extension
                        $arr_ext = array('jpg', 'jpeg', 'gif','png'); //set allowed extensions

                        //only process if the extension is valid
                        if(in_array($ext, $arr_ext))
                        {
						
							$newName = $service_slug.".".$ext;
							  
							move_uploaded_file($image_file['tmp_name'], WWW_ROOT . 'images/'.$folderpath . $newName);	
							  
                            $final_image = $newName;  
                        }
						return $final_image;
	}
	
    public function beforeFilter() {

		
			$this->loadModel('Product');	
            $this->loadModel('Sitepage');				

			
			
			$this->loadModel('Catalog');
		$home_content_seo = $this->Catalog->find('first', [
            'conditions'=> ['Catalog.id'=>'7'],
        ]); 	
        $this->set(compact('home_content_seo'));
        
        $this->loadModel('Location');
        $rand_locationsa = $this->Location->find('all', array( 
    
                 'order' => 'rand()',
    
                 'limit' => 6,
    
            ));
    $this->set(compact('rand_locationsa'));
				
			$products = $this->Product->find('all', array(
			'fields' => array('Product.name', 'Product.slug'),
			'contain' => array(
			'ChildProduct'
			),
 			'conditions' => array(
				'Product.active' => '1',
				'Product.parent_id' => '0',
			)
		));
			  
		$all_products = $this->Product->find('all', array(
			'contain' => array(
			'ChildProduct'
			),
 			'conditions' => array(
				'Product.active' => '1',
				//'Product.hot_product' => '1'
			)
		));
		
		$page= "";
		
	$this->set(compact('all_products'));
			 
			 $footer_products = $this->Product->find('all', array(
			'contain' => array(
			'ChildProduct'
			),
 			'conditions' => array(
				'Product.active' => '1',
				//'Product.hot_product' => '1'
			),
			'limit' => 8
		));
		
 	            $this->set(compact('footer_products'));
			
		        $this->set(compact('products','page'));
			
				$directory_name = "";
				$this->set(compact('directory_name'));
                $meta_schema ="";
				$presence_name = "";
				$this->set(compact('presence_name','meta_schema'));


      
       	

				
			
	            $sitepage20 = $this->Sitepage->find('first', array(
									'recursive' => 0,
									'order' => array(							
									),
									'conditions' => array(
										'Sitepage.id' => '20'
									),
								));
											
			$this->set(compact('sitepage20'));	
			
		        								
				$this->loadModel('Setting');
				$setting = $this->Setting->find('first', array(
						'conditions' => array(
							'Setting.id' => '1'
						)
					));
    $this->set(compact('setting'));
		 
	$company_address1   = $setting['Setting']['address1'];							
	$company_email     =  $setting['Setting']['email'];
	$company_email2      = $setting['Setting']['email3'];
	$company_phone     = $setting['Setting']['contact_number'];
	$contact_number3     = $setting['Setting']['contact_number3'];
	
	//$image_keyword     = $setting['Setting']['image_keyword'];



	$footer_text       = $setting['Setting']['footer_text'];
	$google_analytics  = $setting['Setting']['google_analytics'];
	$company_name      = $setting['Setting']['name'];
	$sitelogo          = $setting['Setting']['sitelogo'];
	$company_details   = array(
								'company_name'    =>	$company_name,								
								'company_email'   =>	$company_email ,								
								'company_address1'=>	$company_address1,
								'company_email'   =>	$company_email,
								'company_email2'   =>	$company_email2 ,
								//'dheeraj_email'   =>	$dheeraj_email,
								'contact_number3'    =>	$contact_number3,
								//'sanjeev_phone'   =>	$sanjeev_phone,
								//'sachin_phone'    =>	$sachin_phone,
								//'dheeraj_phone'   =>	$dheeraj_phone,
								'company_phone'   =>	$company_phone,
								'sitelogo'        =>	$sitelogo,
								//'image_keyword'   =>	$image_keyword,
							
								
								
		);

		$subject ="";
		$products = "";
		$image_keyword="";
		$company_email1="";
		$this->Session->write('company_details',$company_details);
		
		$this->set(compact('company_name','company_address1','company_email1','company_phone','contact_number3','company_email','company_email2','sitelogo','footer_text','image_keyword','google_analytics'));   
		
		$contact_pos = stripos($_SERVER['REQUEST_URI'] , '?');

		if($contact_pos != '') {
		throw new NotFoundException(__('Page Not Found.'));
		//exit;
		}
		else {

		}

        $this->Auth->loginAction = ['controller' => 'users', 'action' => 'login', 'admin' => false];
        $this->Auth->loginRedirect = ['controller' => 'pages', 'action' => 'index', 'admin' => true];
        $this->Auth->logoutRedirect = ['controller' => 'pages', 'action' => 'index', 'admin' => false];
        $this->Auth->authorize = ['Controller'];

        $this->Auth->authenticate = [
            'Form' => [
                'userModel' => 'User',
                'fields' => [
                    'username' => 'username',
                    'password' => 'password'
                ],
                'scope' => [
                    'User.active' => 1,
                ]
            ]
        ];

        if(isset($this->request->params['admin']) && ($this->request->params['prefix'] == 'admin')) {
            if($this->Session->check('Auth.User')) {
                $this->set('authUser', $this->Auth->user());
                $loggedin = $this->Session->read('Auth.User');
                $this->set(compact('loggedin'));
                $this->layout = 'admin';
            }
        } elseif(isset($this->request->params['customer']) && ($this->request->params['prefix'] == 'customer')) {
            if($this->Session->check('Auth.User')) {
                $this->set('authUser', $this->Auth->user());
                $loggedin = $this->Session->read('Auth.User');
                $this->set(compact('loggedin'));
                $this->layout = 'customer';
            }
        } else {
            $this->Auth->allow();
        }

    }

    public function isAuthorized($user) {
        if (($this->params['prefix'] === 'admin') && ($user['role'] != 'admin')) {
            echo '<a href="/users/logout">Logout</a><br />';
            die('Invalid request for '. $user['role'] . ' user.');
        }
        if (($this->params['prefix'] === 'customer') && ($user['role'] != 'customer')) {
            echo '<a href="/users/logout">Logout</a><br />';
            die('Invalid request for '. $user['role'] . ' user.');
        }
        return true;
    }


    public function admin_switch($field = null, $id = null) {
        $this->autoRender = false;
        $model = $this->modelClass;
        if ($this->$model && $field && $id) {
            $field = $this->$model->escapeField($field);
            return $this->$model->updateAll([$field => '1 -' . $field], [$this->$model->escapeField() => $id]);
        }
        if(!$this->RequestHandler->isAjax()) {
            return $this->redirect($this->referer());
        }
    }

    public function admin_editable() {

        $model = $this->modelClass;

        $id = trim($this->request->data['pk']);
        $field = trim($this->request->data['name']);
        $value = trim($this->request->data['value']);

        $data[$model]['id'] = $id;
        $data[$model][$field] = $value;
        $this->$model->save($data, false);

        $this->autoRender = false;

    }

}
