<?php
App::uses('AppController', 'Controller');

/**
 * Mailings Controller
 *
 * @property Mailing $Mailing
 * @property PaginatorComponent $Paginator
 * @property SessionComponent $Session
 */
class MailingsController extends AppController {

/**
 * Components
 *
 * @var array
 */
	public $helpers = array('Api');	
	
/**
 * Components
 *
 * @var array
 */
	public $components = array(
			'Paginator',
			'Export.Export'
	);

/**
 * Importacao de dados pelo Model
 * @param unknown_type $export
 */
	public function admin_import($export = null) {
	    $this->set('title_for_layout', 'Importação de Contatos');
	    
	    if ($this->request->is('post')) {
	         
	        $filename = $this->request->data['Mailing']['document']['name'];
	        $tmpname = $this->request->data['Mailing']['document']['tmp_name'];
	        $model = $this->request->data['Mailing']['mailing_type'];
	         
	        if (($filename == null) || (trim($filename) == "")) {
	            $this->Session->setFlash("Selecione um arquivo válido");
	        } 
	        else {
    	        
    	        $filedata = WWW_ROOT. 'uploads' .DS. $filename;
    	        move_uploaded_file($tmpname, $filedata);
    	        $retorno = $this->Mailing->import($filename, $this->Auth->user('id'), $model);
    	        
    	        if (strpos($retorno, 'Falha') !== false) {
    	            $this->Session->setFlash($retorno);
    	        }
    	        else {
        	        $this->redirect(array(	                
        	                'plugin' => 'mailings',
        	                'admin' => true,
        	                'controller' => 'item_mailings',
        	                'action' => 'view', $retorno));
    	        }
	        }
	    }  
	}
	
/**
 * Exportacao de dados
 * @param unknown_type $export
 */	
	public function admin_export($export = null) {
	   $data = $this->Mailing->find('all');
	   $this->Export->append($data, 'mailing.csv');
	}	
	
/**
 * index method
 *
 * @return void
 */
	public function admin_index() {	    
	    $this->set('title_for_layout', 'Importações Realizadas');

	    /**
	     * Valida o usuario que somente o admin possa ver os dados de todos
	     * cadastrados
	     * @var unknown_type
	     */
	    $conditions = array();
	    if ($this->Auth->user('role_id') != '1') {
	        $conditions['Mailing.user_id'] = $this->Auth->user('id');
	    }
	    
	    $this->Mailing->recursive = 1;
	    $this->Paginator->settings = array(
	            'conditions' => $conditions,
	            'order' => array(
	                    'Mailing.id' => 'desc',
	            ),
	    );
	    $this->set('mailings', $this->Paginator->paginate());
    }
}	