<?php
App::uses('AppController', 'Controller');
class ProductsController extends AppController {

////////////////////////////////////////////////////////////

    public $components = [
        'RequestHandler',
    ];

////////////////////////////////////////////////////////////

    public function beforeFilter() {
        parent::beforeFilter();
    }

////////////////////////////////////////////////////////////

    public function index() {
				 
		  $this->loadModel('Sitepage');	
   
		  $product_page = $this->Sitepage->find('first', array(
			'recursive' => 0,
			'order' => array(
				
			),
			'conditions' => array(
			'Sitepage.id' => 6
			),
		));
	
   
		  $all_products = $this->Product->find('all', array(
			'recursive' => 0,
			'order' => array(
				'Product.product_order'=>'asc',
			),
			'conditions' => array(
			'Product.active' => 1
			),
		));
		 
		
	if(!empty($product_page['Sitepage']['meta_title'])) {	
		$meta_title   = $product_page['Sitepage']['meta_title'];
	}
	if(!empty($product_page['Sitepage']['meta_keyword'])) {	
		$meta_keyword = $product_page['Sitepage']['meta_keyword'];
	}
	if(!empty($product_page['Sitepage']['meta_desc'])) {	
		$meta_desc   = $product_page['Sitepage']['meta_desc'];
	}
	
	$this->set(compact('all_products','meta_title','product_page','meta_keyword','meta_desc'));

   

    }
	
	 public function marketplace($location=null) {
				 
	
		
	    $this->loadModel('Location');
        $directory_name=$location.'/';		
   
	$location = $this->Location->find('first', [
            'recursive' => 0,			
            'conditions' => [
                'Location.slug' => $location
            ]
        ]);
				
    if(empty($location)) {
		
			throw new NotFoundException(__('Page Not Found.'));

    }		
		
    $this->set(compact('directory_name','location'));

    }
	//////////////////////////////////////////////////////////////
	
	public function search() {
		  
	  $search_query = $this->request->data['Product']['search'];
		  
	  
	 $string = $this->Product->find('all',array('conditions'=>array('Product.name LIKE'=>'%'.trim($search_query).'%')));
	 
	   $this->set(compact('string'));

    }

////////////////////////////////////////////////////////////

 
    public function view($id = null) {
 
 			/*$this->Product->query(" UPDATE `products` SET 
`location_title`  = concat(name,' in city');");*/
		 
		 
        $product = $this->Product->find('first', [
            'recursive' => -1,
            'contain' => [
				'ChildProduct',				
            ],
            'conditions' => [              
                'Product.active' => 1,
                'Product.slug' => $id
            ]
        ]);
		  
			
        if (empty($product)) {
          
			throw new NotFoundException('Could not find this Page.');		
			exit;
			
        }

        $this->Product->updateViews($product);
		
 	 
	if(!empty($product['Product']['meta_title'])) {	
		$meta_title   = $product['Product']['meta_title'];		
 	
		
	}
	if(!empty($product['Product']['meta_keyword'])) {	
		$meta_keyword = $product['Product']['meta_keyword'];
		
 		
	
	}
	if(!empty($product['Product']['meta_desc'])) {	
		$meta_desc   = $product['Product']['meta_desc'];	
	}

		if(!empty($product['Product']['meta_schema'])) {	
		$meta_schema   = $product['Product']['meta_schema'];	
		
	}
	// echo "<pre>";
	// print_r($meta_schema); 
	// exit;
	$this->set(compact('meta_title','meta_keyword','meta_desc','meta_schema'));		
		
	

		
        $this->set(compact('product'));

       
		
		$productbreds = $this->Product->find('all', [ 
		'recursive' => -1,        
		'conditions' => [     
		'Product.active' => 1,	
		'Product.parent_id' => $product['Product']['id'],   
		],       
		'order' => [  
		'Product.id' => 'ASC' 
		]     

		]);
       
	    $this->set(compact('productbreds'));
		
		$breadcum_products = $this->Product->find('first', [ 
		'recursive' => -1,        
		'conditions' => [     
		'Product.active' => 1,	
		'Product.id' => $product['Product']['parent_id'],   
		],       
		'order' => [  
		'Product.id' => 'ASC' 
		]     

		]);
       
	    $this->set(compact('breadcum_products')); 
		
 
    }
  
	public function admin_index($parent_id=0) { 
	
 	
		$products = $this->Product->find('all', array(
			'recursive' => 0,
			'order' => array(
				'Product.id' => 'DESC'
			),
			'conditions' => array(
		//	'Product.parent_id' => $parent_id
			),
		));
		
		
		$options = array('conditions' => array('Product.' . $this->Product->primaryKey => $parent_id));
		$product_details = $this->Product->find('first', $options);
		
		
		
		$this->set(compact('products','parent_id','product_details'));
		
	}
	
 

////////////////////////////////////////////////////////////

    public function admin_view($id = null) {

        if (($this->request->is('post') || $this->request->is('put')) && !empty($this->request->data['Product']['image']['name'])) {

            $this->Img = $this->Components->load('Img');

            $newName = $this->request->data['Product']['slug'];

            $ext = $this->Img->ext($this->request->data['Product']['image']['name']);

            $origFile = $newName . '.' . $ext;
            $dst = $newName . '.jpg';

            $targetdir = WWW_ROOT . 'images/original';

            $upload = $this->Img->upload($this->request->data['Product']['image']['tmp_name'], $targetdir, $origFile);

            if($upload == 'Success') {
                $this->Img->resampleGD($targetdir . DS . $origFile, WWW_ROOT . 'images/large/', $dst, 800, 800, 1, 0);
                $this->Img->resampleGD($targetdir . DS . $origFile, WWW_ROOT . 'images/small/', $dst, 180, 180, 1, 0);
                $this->request->data['Product']['image'] = $dst;
            } else {
                $this->request->data['Product']['image'] = '';
            }

            if ($this->Product->save($this->request->data)) {
                $this->Flash->flash($upload);
                return $this->redirect($this->referer());
            } else {
                $this->Flash->flash('The Product could not be saved. Please, try again.');
            }
        }

        if (!$this->Product->exists($id)) {
            throw new NotFoundException('Invalid product');
        }
        $product = $this->Product->find('first', [
            'recursive' => -1,
            'contain' => [
               // 'Category',
                'Brand',
            ],
            'conditions' => [
                'Product.id' => $id
            ]
        ]);
        $this->set(compact('product'));
    }

////////////////////////////////////////////////////////////

    public function admin_add() {
		
		
		
		
        if ($this->request->is('post')) {
			
			$filename1 = "";
			$filename2 = "";
			$this->request->data['Product']['slug'] = $this->generateSlug($this->request->data['Product']['name']);

			
				if(!empty($this->data['Product']['image']['name']))
                {
					  $filename1 = $this->process_image($this->request->data['Product']['image'], 'home-img-'.$this->request->data['Product']['slug'],'products/');
				}
                
				$this->request->data['Product']['image'] = $filename1;
				
			
				if(!empty($this->data['Product']['inner_image']['name']))
                {
					  $filename2 = $this->process_image($this->request->data['Product']['inner_image'], 'img-'.$this->request->data['Product']['slug'],'products/');
				}
			
			$this->request->data['Product']['inner_image'] = $filename2;
		
		 
		
            $this->Product->create();
            if ($this->Product->save($this->request->data)) {
                $this->Flash->flash('The product has been saved');
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->flash('The product could not be saved. Please, try again.');
            }
        }
       		 
	$parentproducts = $this->Product->find('list');
		$this->set(compact('parentproducts'));	
		     	
    }


	
    public function admin_seo($id = null) {
 
        if ($this->request->is('post') || $this->request->is('put')) {
 
		 
            if ($this->Product->save($this->request->data)) {
                $this->Flash->flash('The product seo has been saved');
               // return $this->redirect(['action' => 'index']);
			   
			    $product = $this->Product->find('first', [
                'conditions' => [
                    'Product.id' => $id
                ]
            ]);
            $this->request->data = $product;
			
            } else {
                $this->Flash->flash('The product seo could not be saved. Please, try again.');
            }
        } else {
            $product = $this->Product->find('first', [
                'conditions' => [
                    'Product.id' => $id
                ]
            ]);
            $this->request->data = $product;
        }

        $this->set(compact('id'));

        $this->set(compact('product'));

    }

	

    public function admin_edit($id = null) {

        
        if (!$this->Product->exists($id)) {
            throw new NotFoundException('Invalid product');
        }
		
		 $product = $this->Product->find('first', [
                'conditions' => [
                    'Product.id' => $id
                ]
            ]);
 			 
	
		$filename1 = $product['Product']['image'];
		$filename2 = $product['Product']['inner_image'];
		
        if ($this->request->is('post') || $this->request->is('put')) {
 
		$this->request->data['Product']['slug'] = $this->generateSlug($this->request->data['Product']['name']);
					  
		if(!empty($this->data['Product']['image']['name']))
                {
					  $filename1 = $this->process_image($this->request->data['Product']['image'], 'home-img-'.$this->request->data['Product']['slug'],'products/');
				}
				
			$this->request->data['Product']['image'] = $filename1;
			
		if(!empty($this->data['Product']['inner_image']['name']))
                {
					  $filename2 = $this->process_image($this->request->data['Product']['inner_image'], 'img-'.$this->request->data['Product']['slug'],'products/');
				}
				
			$this->request->data['Product']['inner_image'] = $filename2;	
			
			
		
            if ($this->Product->save($this->request->data)) {
                $this->Flash->flash('The product has been saved');
                return $this->redirect(['action' => 'index']);
            } else {
                $this->Flash->flash('The product could not be saved. Please, try again.');
            }
        } else {
            $product = $this->Product->find('first', [
                'conditions' => [
                    'Product.id' => $id
                ]
            ]);
            $this->request->data = $product;
        }

        $this->set(compact('id'));

        $this->set(compact('product'));
    }

////////////////////////////////////////////////////////////

    public function admin_tags($id = null) {

        $tags = ClassRegistry::init('Tag')->find('all', [
            'recursive' => -1,
            'fields' => [
                'Tag.name'
            ],
            'order' => [
                'Tag.name' => 'ASC'
            ],
        ]);
        $tags = Hash::combine($tags, '{n}.Tag.name', '{n}.Tag.name');
        $this->set(compact('tags'));

        if ($this->request->is('post') || $this->request->is('put')) {

            $tagstring = '';

            foreach($this->request->data['Product']['tags'] as $tag) {
                $tagstring .= $tag . ', ';
            }

            $tagstring = trim($tagstring);
            $tagstring = rtrim($tagstring, ',');

            $this->request->data['Product']['tags'] = $tagstring;

            $this->Product->save($this->request->data, false);

            return $this->redirect(['action' => 'tags', $this->request->data['Product']['id']]);

        }

        $product = $this->Product->find('first', [
            'conditions' => [
                'Product.id' => $id
            ]
        ]);
        if (empty($product)) {
            throw new NotFoundException('Invalid product');
        }
        $this->set(compact('product'));

        $selectedTags = explode(',', $product['Product']['tags']);
        $selectedTags = array_map('trim', $selectedTags);
        $this->set(compact('selectedTags'));

        $neighbors = $this->Product->find('neighbors', ['field' => 'id', 'value' => $id]);
        $this->set(compact('neighbors'));

    }

////////////////////////////////////////////////////////////

    public function admin_csv() {
        $products = $this->Product->find('all', [
            'recursive' => -1,
        ]);
        $this->set(compact('products'));
        $this->layout = false;
    }

	
////////////////////////////////////////////////////////////


 public function admin_change_product_hot()
    {
        if(!$this->request->is('AJAX'))
        {
            return $this->redirect(array('controller'=>'products', 'action'=>'index'));
        }
        
        if(!$this->Product->save(array('id'=>$this->request->data['product_id'], 'hot_product'=>$this->request->data['hot_product'])))
        {
            echo json_encode(array('status'=>'failure', 'message'=>'Unable to set Product as Featured at the moment.'));
            die;
        }
        
        echo json_encode(array('status'=>'success', 'message'=>'Product set as Featured.'));
        die;
    }

	
 public function admin_change_seo_status()
    {
        if(!$this->request->is('AJAX'))
        {
            return $this->redirect(array('controller'=>'products', 'action'=>'index'));
        }
        
        if(!$this->Product->save(array('id'=>$this->request->data['product_id'], 'seo_status'=>$this->request->data['seo_status'])))
        {
            echo json_encode(array('status'=>'failure', 'message'=>'Unable to set Product as Seo Status at the moment.'));
            die;
        }
        
        echo json_encode(array('status'=>'success', 'message'=>'Product set as Featured.'));
        die;
    }
	
 public function admin_change_product_status()
    {
        if(!$this->request->is('AJAX'))
        {
            return $this->redirect(array('controller'=>'products', 'action'=>'index'));
        }
        
        if(!$this->Product->save(array('id'=>$this->request->data['product_id'], 'active'=>$this->request->data['status'])))
        {
            echo json_encode(array('status'=>'failure', 'message'=>'Unable to set status at the moment.'));
            die;
        }
        
        echo json_encode(array('status'=>'success', 'message'=>'Product status updated.'));
        die;
    }
	

	
    public function admin_delete($id = null) {
        $this->Product->id = $id;
        if (!$this->Product->exists()) {
            throw new NotFoundException('Invalid product');
        }
        $this->request->onlyAllow('post', 'delete');
        if ($this->Product->delete()) {
            $this->Flash->flash('Product deleted');
            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->flash('Product was not deleted');
        return $this->redirect(['action' => 'index']);
    }

////////////////////////////////////////////////////////////

}
