<?php

if (!defined('BASEPATH')) {
    exit('No direct script access allowed');
}

class newsletter_site extends MX_Controller
{

    public function __construct()
    {
        $this->load->library('form_hash');
        $this->config->load('newsletter/config');
        $time_point = $this->config->item('newsletter_time_point');
        $this->form_hash->time_point = !empty($time_point) ? $time_point : 3;
    }

    public function index()
    {
        $this->load->helper('form');
        $content = array(
            'hash' => $this->form_hash->set_form_hash(),
        );

        return $this->parser->parse('newsletter/template', $content, TRUE);
    }

    public function add()
    {
        $data = array(
            'success' => false,
        );

        if ($this->input->post('email') && $this->form_hash->check_form_hash()) {
            $this->load->model('newsletter/newsletter_email_tmodel');
            if (!$this->newsletter_email_tmodel->is_email_exist($this->input->post('email'))) {
                $data['success'] = $this->newsletter_email_tmodel->add([
                    'email' => $this->input->post('email'),
                    'date'  => date('Y-m-d H:i:s'),
                    'tags'  => $this->input->post('tags') ?: '',
                ]);
            } else {
                $data['success'] = true;
            }
        }

        $data['hash'] = $this->form_hash->set_form_hash();

        $this->output->set_content_type('application/json')->set_output(json_encode($data));
    }

}
