<?php
function saveNewsletter( $sEmail ){
	global $config;
	$oDB = DataBase::getInstance( );
	if( !checkNewsletterEmail( $sEmail ) ){
		$oDB->save( DB_NEWSLETTER, Array( 'sEmail' => $sEmail ) );
		$sCode = null;
		if( !empty( $config['newsletter_coupon_value'] ) ){
			if( !empty( $config['newsletter_coupon_producer'] ) ){
				$aProducer = throwProducer( $config['newsletter_coupon_producer'] );
				$sProducer = $aProducer['sName'];
			}
			$aCodes = generateDiscountCodes( $config['newsletter_coupon_producer'], $config['newsletter_coupon_length'], $config['newsletter_coupon_notExpiring'], 1, PK, $config['newsletter_coupon_prefix'], $config['newsletter_coupon_value'], time() + 3600 * 24 * $config['newsletter_coupon_time'] );
			if( is_array( $aCodes ) )
				$sCode = array_pop( $aCodes );
		}
		sendEmail( Array(
			'sTopic' => $GLOBALS['lang']['newsletter_new_mail_header'],
			'sMailContent' => ( !empty( $sCode ) ?
				str_replace(
					Array( '|n|', '%sCode%', '%sValue%', '%sExpire%', '%sProducerInfo%', '%iDays%' ),
					Array( "\n",
								 $sCode,
								 $config['newsletter_coupon_value'] . ( strpos( $config['newsletter_coupon_value'], '%' ) !== false ? null : $config['currency_symbol'] ),
								 $config['newsletter_coupon_notExpiring'] ? $GLOBALS['lang']['newsletter_new_mail_noexpire'] : $GLOBALS['lang']['newsletter_new_mail_expire'],
								 empty( $config['newsletter_coupon_producer'] ) ? null : str_replace( '%sProducer%', $sProducer, $GLOBALS['lang']['newsletter_new_mail_producer'] ),
								 $config['newsletter_coupon_time']
								),
					$GLOBALS['lang']['newsletter_new_mail_code']
				) :
				$GLOBALS['lang']['newsletter_new_mail_nocode']
			),
			'sSender' => $config['newsletter_email'] ),
			$sEmail
		);
	}
}
function deleteNewsletter( $sEmail ){
	$oDB = DataBase::getInstance( );
	$oDB->deleteInFile( DB_NEWSLETTER, $sEmail, 'sEmail' );
}
if( !function_exists( 'checkEmail' ) ){
	function checkEmail( $sEmail ){
		$sRegExp = '/^[a-z0-9_\\-A-Z]+(\\.[a-z0-9_\\-A-Z]+)*@[a-z0-9_\\-A-Z]+(\\.[a-z0-9_\\-A-Z]+)*\\.[a-z]+$/';
		if( preg_match( $sRegExp, $sEmail ) ) return true;
		else return false;
	}
}
function checkNewsletterEmail( $sEmail ){
	$oDB = DataBase::getInstance( );
	return $oDB->executeSQL( 'SELECT COUNT( `sEmail` ) FROM `' . $oDB->throwTableName( DB_NEWSLETTER ) . '` WHERE `sEmail` = \'' . $oDB->escape( $sEmail ) . '\'', true, DataBase::SINGLE_VALUE );
}
?>