<?php

/**
 *--------------------------------------
 * subscribe
 *--------------------------------------
 * @project		: loga
 * @author		: cblee
 * @created		: 2016-08-26
 * @copyright	: (c)2016 AsThis
 *--------------------------------------
 */
defined('PFA_PATH') or exit('Access Denied');

class SubscribeCtrlr extends IndexCtrlr {
	protected $_o;

	public function __construct() {
		parent::__construct();

		$this->_o = EO('subscribe');
		if(!$this->_o['switch']) {
			halt(L('SUBSCRIBE_IS_OFF'), true, true);
		}
	}

	public function add_subscribe_do() {
		$_o_i = M('Option')->get_option('interaction');
		if(!I('subscribe', $_o_i['search_interval'])) {
			$this->error(L('_TRY_LATER_'), Url::U('search/search'));
		}

		$data = array();
		$data['s_email'] = trim(AFilter::text(ARequest::get('email'), 192));
		if(!AFilter::is_email($data['s_email'])) {
			$this->error(L('DATA_INVALID'), AServer::get_preUrl());
		}

		$_SI = M('Subscribe')->field('`subscribe_id`,`s_status`')->where(array('s_email' => array('EQ', $data['s_email'])))->find();
		$result = array('data' => '', 'error' => '');
		if(!empty($_SI)) {
			if(1 != $_SI['s_status']) {
				$data['subscribe_id'] = $_SI['subscribe_id'];
				$data['s_status'] = 1;
				$result = M('Subscribe')->edit_subscribe($data);
			}
		}
		else {
			$data['s_add_time'] = NOW_TIME;
			$data['s_add_ip'] = CLIENT_IP;
			$data['s_status'] = 1;

			$result = M('Subscribe')->add_subscribe($data);
		}

		I('subscribe');
		ACookie::set('email', $data['s_email']);

		if(!empty($result['error'])) {
			$this->error($result['error'], AServer::get_preUrl());
		}
		$this->success(L('SUBSCRIBE_SUCCESS'), AServer::get_preUrl());
	}

	public function cancel_subscribe_do() {
		$_o_i = M('Option')->get_option('interaction');
		if(!I('subscribe', $_o_i['search_interval'])) {
			$this->error(L('_TRY_LATER_'), Url::U('search/search'));
		}

		$data = array();
		$data['s_email'] = trim(AFilter::text(ARequest::get('email'), 192));
		if(!AFilter::is_email($data['s_email'])) {
			$this->error(L('DATA_INVALID'), AServer::get_preUrl());
		}

		$_SI = M('Subscribe')->field('`subscribe_id`,`s_status`')->where(array('s_email' => array('EQ', $data['s_email'])))->find();
		$result = array('data' => '', 'error' => '');
		if(!empty($_SI)) {
			if(0 != $_SI['s_status']) {
				$data['subscribe_id'] = $_SI['subscribe_id'];
				$data['s_status'] = 0;
				$result = M('Subscribe')->edit_subscribe($data);
			}
		}

		I('subscribe');
		ACookie::set('email', $data['s_email']);

		if(!empty($result['error'])) {
			$this->error($result['error'], AServer::get_preUrl());
		}
		$this->success(L('UNSUBSCRIBE_SUCCESS'), AServer::get_preUrl());
	}

}

?>