<?php

class FramesController extends AppController{
	
	var $name = 'frames';
	var $components = array('Uploader.Uploader');
	
	function beforeFilter(){
		parent::beforeFilter();
		
		$this->Auth->allow('getRandomFrames');		
	}
	
	function view($id = null){
		$this->Frame->id = $id;
		$this->set('frame', $this->Frame->read());		
	}
	
	function admin_index(){
		$this->set('frames', $this->Frame->find('all'));
	}
	
	function index(){
		$this->set('frames', $this->Frame->find('all'));
	}
	
	function admin_add(){
		$error = false;
		
		if (!empty($this->data)) {
    		$this->Frame->set($this->data);
    		//Si el fichero es correcto.
 			if ($this->Frame->validates()) {
 				//Guarda el registro.
 				$this->Frame->create();
           		if ($this->Frame->save($this->data)) {
           			//Sube el fichero.
 					$this->Uploader->uploadDir = 'files/uploads/frames/';
           			if ($data = $this->Uploader->upload('frame_image', array('name' => $this->Frame->id))){
           				$this->_cropImage('center', 100, 100);
						$this->_cropImage('center', 250, 250);
						
						$this->Frame->set(array(
							'name' => $data['name'],
							'ext' => $data['ext'],
							'path' => $data['path']
						));
						
						//Actualizar datos del registro.
						$this->Frame->save();
						//pr($data);
					
						$this->Session->setFlash('El frame se guardó correctamente.');
						$this->redirect(array('controller' => 'frames', 'action' => 'admin_add'));
					} else {
						//No se pudo subir el fichero.
						$this->Frame->delete();
						$error = true;
					}
				} else {
					//No se pudo guardar el registro.
					$error = true;
				}
        	}
    	}
    	
    	if ($error){
    		$this->Session->setFlash('Lo sentimos, no se pudo guardar el frame.');
    	}
	}
	
	/**
	 * Recorta una imagen, partiendo de una posición y unas dimensiones.
	 * @param $location: center, left, right, top, bottom
	 * @param $width
	 * @param $height
	 */
	function _cropImage($location = 'center', $width = 100, $height = 100){
		$crop_opctions = array(
					'location' => $location,
					'width' => $width,
             		'height' => $height,
		);
		
		return $this->Uploader->crop($crop_opctions);
	}
	
	function getRandomFrames(){
		$this->autoRender = false;
		return $this->Frame->find('list', array('fields'=> array('id', 'ext'), 'order' => 'rand()', 'limit' => 28));
	}
	
}

?>