<?php
class ControllerCommonModuleNewsletter extends Controller {
	protected function index() {

		$route = isset($this->request->get['route']) ? $this->request->get['route'] : 'common/home' ;
		
		if ( !$this->config->get('newsletter_status') || 
				($this->config->get('config_maintenance') == 1 && !$this->user->isLogged()) || 
				($this->ftrgeralregistry->isApp() && $route != 'common/home') ) {
			return false;
		}

		$this->load->type('tipocomum');

		if(isset($this->session->data['api_key'])){

				$this->load->dmodel('design/layout');

				$layout_id = $this->dmodel_design_layout->getLayoutRoute($route);
				if($layout_id != Type_IdLayout::Tp_IdHome){
					return false;
				}
		}

		$this->document->addScriptApp(array(
      'catalog/view/theme/appmobile/js/module.newsletter.js'
    ));

		$language = $this->load->language('common/module_newsletter');
    $this->data = array_merge($this->data, $language);

		if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/module_newsletter.twig')) {
			$this->template = $this->config->get('config_template') . '/template/common/module_newsletter.twig';
		} else {
			$this->template = 'default/template/common/module_newsletter.twig';
		}

		$this->render();
	}

	public function newsletter(){

		$json = array ();

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

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

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

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

		$this->response->setOutputJson($json);

	}

}
