<?php
class ControllerCommonNewsletter extends Controller {

	public function index() {		

		$valida = array(
			'newsletter_status' => $this->config->get('newsletter_status'),
			'route' 			=> (isset($this->request->get['route']) && ($this->request->get['route']!='common/home') && ($this->request->get['route']!='account/register')) ? true : false,
			'cookie' 			=> isset($_COOKIE['close_newsletter']) ? false : true,
			'login'				=> ($this->customer->isLogged()) ? false : true
		);	

		if(count(array_filter($valida))<4){
			return false;
		}

        $language = $this->language->load('common/newsletter');				
		$this->data = array_merge($this->data, $language);				        
      
		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/newsletter.tpl')) {
            $this->template = $this->config->get('config_template') . '/template/common/newsletter.tpl';
        } else {
            $this->template = 'default/template/common/newsletter.tpl';
        }
		
		$this->response->setOutput($this->render());

	}

	public function send(){

		$json = array();

		$this->language->load('common/newsletter');
		$this->load->model('account/newsletter');

		if ((utf8_strlen($this->request->post['name_newsletter']) < 1) || (utf8_strlen($this->request->post['name_newsletter']) > 80)) {
			$json['error']['name_newsletter'] = $this->language->get('error_name');
		}

		if ((utf8_strlen($this->request->post['email_newsletter']) > 96) || !preg_match('/^[^\@]+@.*\.[a-z]{2,6}$/i', $this->request->post['email_newsletter']) || !filter_var($this->request->post['email_newsletter'], FILTER_VALIDATE_EMAIL) || !preg_match('/^[a-zA-Z0-9\._-]+@/', $this->request->post['email_newsletter']) ) {
			$json['error']['email_newsletter'] = $this->language->get('error_email');
		}

		if($this->model_account_newsletter->getNewsletterByEmail($this->request->post['email_newsletter'])){
			$json['error']['email_newsletter'] = $this->language->get('error_email_exists');
		}	
		
		if(!$json){
			$this->model_account_newsletter->addNewsletter($this->request->post);
			$json['success'] = $this->language->get('success');			
		}

		$this->response->setOutput(json_encode($json));
	}
	
	
}
?>