<?php
/* =============================================================== *\
|		Module name:      Newsletter								|
|																	|
\* =============================================================== */

if (!defined('IN_SITE')){
     die('Hacking attempt!');
}
//Module language
//$Func->import_module_language("home/lang_newsletter". PHP_EX);

$Newslt	= new Newsletter;

class Newsletter
{
	function Newsletter(){
		global $Func;

		$act	= htmlspecialchars($Func->get_vars('act', 1));
		if ($act == 'remove'){
			$this->remove_email();
		}
		else{
			$this->add_email();
		}
	}

	function add_email(){
		global $Lang, $DB, $Template;

		$cat_id	= isset($_POST["cat_id"]) ? intval($_POST["cat_id"]) : 0;
		$name	= isset($_POST["name"]) ? htmlspecialchars($_POST["name"]) : '';
		$email	= isset($_POST["email"]) ? htmlspecialchars($_POST["email"]) : '';

		if ( !$cat_id || empty($name) || empty($email) ){
			$Template->message_die($Lang->data['general_error_not_full']);
			return false;
		}

		//Check email exist
		$DB->query("SELECT * FROM ". $DB->prefix ."newsletter WHERE email='". $email ."'");
		if ( !$DB->num_rows() ){
			//Create random code;
			$regcode = rand(100000,999999);//6 digit number
			//Insert new email
			$DB->query("INSERT INTO ". $DB->prefix ."newsletter(cat_id, name, email, reg_code, enabled) VALUES(". $cat_id .", '". $name ."', '". $email ."', ". $regcode .", 0)");
			//Update category counter
			if ( $cat_id ){
				$DB->query("UPDATE ". $DB->prefix ."newsletter_category SET email_counter=email_counter+1 WHERE cat_id=". $cat_id);
			}
		}

		$Template->message_die($Lang->data['newslt_success_subscribe']);
		return true;
	}

	function remove_email(){
		global $Info, $Func, $Lang, $DB, $Template;

		$email	= htmlspecialchars($Func->get_vars('email', 2));
		$code	= intval($Func->get_vars('code', 3));

		if ( empty($email) || !$code ){
			$Template->message_die($Lang->data['general_error_not_full']);
			return false;
		}

		//Get cat_id
		$DB->query("SELECT cat_id FROM ". $DB->prefix ."newsletter WHERE email='". $email ."' AND reg_code=$code");
		if ( $DB->num_rows() ){
			$email_info	= $DB->fetch_array();
			//Update category counter
			$DB->query("UPDATE ". $DB->prefix ."newsletter_category SET email_counter=email_counter-1 WHERE cat_id=". $email_info['cat_id']);
			//Delete email
			$DB->query("DELETE FROM ". $DB->prefix ."newsletter WHERE email='". $email ."' AND reg_code=$code");
			$Template->message_die($Lang->data['newslt_success_unsubscribe']);
		}

		$Template->message_die($Lang->data['general_error_not_full']);
		return true;
	}
}

?>