<?php
App::uses('AppController', 'Controller');
App::uses('CakeEmail', 'Network/Email');

/**
 * AppNews Controller
 *
 * @property AppNews $AppNews
 */
class MailsController extends AppController {
	
	public $templates = array(
			0 => array(
				'name' => 'Bemmelhor Telecom',
				'template' => 'bmtelecom',
				'subject' => 'Gerencie e Reduza os custos de Telefonia do Setor de Atendimentos',
			),
	);
	
/**
 * Components
 *
 * @var array
 * @access public
 */
	public $components = array(
			'Email',	
	);
		
	public function admin_index() {
		$this->set('templates', $this->templates);
	}
	
	public function admin_send($index) {
		$this->set('template', $this->templates[$index]);
		$this->set('template_idx', $index);
	}
	
	public function admin_send_mail() {
		
		$index = $this->request->data['template_id'];	
		$emails = '';
		if ($this->request->is('post') || $this->request->is('put')) {		
			if (isset($this->request->data['email1']) && ($this->request->data['email1'] != '')) {
				$this->send_unique($index, $this->request->data['email1']);
				$emails .= ' ' .$this->request->data['email1'];
			}
			
			if (isset($this->request->data['email2']) && ($this->request->data['email2'] != '')) {
				$this->send_unique($index, $this->request->data['email2']);
				$emails .= ', ' .$this->request->data['email2'];
			}
			
			if (isset($this->request->data['email3']) && ($this->request->data['email3'] != '')) {
				$this->send_unique($index, $this->request->data['email3']);
				$emails .= ', ' .$this->request->data['email3'];
			}
		}
		
		$this->Session->setFlash('Email(s) enviado(s) com Sucesso! ' .$emails, 
				'default', array(), 'good');
		
		$this->redirect(array('action' => 'send', $index));
		
	}
	
	public function admin_view_template($index) {
		$this->autoLayout = false;
		$this -> render('/Emails/html/' . $this->templates[$index]['template']);
	}
	
	public function send_unique($index, $to) {
		
		$Email = new CakeEmail('default');
		$Email->emailFormat('html');
		$Email->from(array(Configure::read('Site.email') => 'Bemmelhor SI'));
		$Email->to($to);
		$Email->subject($this->templates[$index]['subject']);
		$Email->template($this->templates[$index]['template']);		
		$Email->send();
		
		$this->loadModel('SendMail');
		$this->SendMail->create();
		$this->SendMail->set('email',$to);
		$this->SendMail->set('template_mail',$this->templates[$index]['template']);
		$this->SendMail->set('template_id',$index);
		$this->SendMail->set('created', date('Y-m-d H:i:s'));
		$this->SendMail->save();
		
	}
	
}
