<?php

/**
 * Generated: 2013-11-04 11:03:31
 * @author Rtn_Module_Tool
 */
class Newsletter_Sender extends Main_Newsletter_Sender {

	const AT_ONCE = 2;
	const NEWSLETTER_EMAIL = 'newsletter@oil.szczecin.pl';
	const NEWSLETTER_NAME = 'Biuletyn OIL';
	
	static function cron() {
		$o = new static();
		$o->process();
	}

	public function process() {
		$queue = R::getAll('SELECT * FROM viewnlsending LIMIT ' . static::AT_ONCE);

		foreach ($queue as $sending) {
			$this->_processSending((object) $sending);
		}
	}

	protected function _processSending($sending) {
		if (!$this->_isSent($sending)) {
			if ($this->_canBeSent($sending)) {
				$this->_sendToReceiver($sending);
				$this->_logSending($sending, 'sent');
			}
			else {
				$this->_logSending($sending, 'skipped');
			}
			$this->_removeFromQueue($sending);
		}

		if ($this->_isNewsletterQueueEmpty($sending->id)) {
			$this->_markNewsletterAsSent($sending->id);
			Rtn_Cli::writeln(__(':timestamp Newsletter :nlid SENT!', [':timestamp' => time(), ':nlid' => $sending->id]));
		}
	}

	protected function _isSent($sending) {
		return (bool) R::getCell('SELECT count(*) FROM nltmpsent WHERE nlgroup_id = ? AND nluser_id = ? AND letter_id = ?', [
				$sending->nlgroup_id,
				$sending->nluser_id,
				$sending->id
		]);
	}

	protected function _canBeSent($sending) {
		$validator = new Zend_Validate_EmailAddress();
		return $validator->isValid($sending->useremail);
	}

	protected function _removeFromQueue($sending) {
		$bean = R::dispense('nltmpsent');

		$bean->created = time();
		$bean->nlgroup_id = $sending->nlgroup_id;
		$bean->nluser_id = $sending->nluser_id;
		$bean->letter_id = $sending->id;

		R::store($bean);
	}

	protected function _isNewsletterQueueEmpty($letterId) {
		$queue = R::getAll('SELECT * FROM viewnlsending WHERE id = ?', [$letterId]);

		foreach ($queue as $sending) {
			if (!$this->_isSent((object) $sending)) {
				return false;
			}
		}

		return true;
	}

	protected function _markNewsletterAsSent($letterId) {
		$bean = R::findOne('nlletter', 'id = ?', [$letterId]);
		$bean->box()->setSent();
	}

	protected function _logSending($sending, $oper) {
		Rtn_Cli::writeln(__(':timestamp;:oper;:nluser_id;:nlgroup_id;:letter_id', [
			':timestamp' => time(),
			':nluser_id' => $sending->nluser_id,
			':nlgroup_id' => $sending->nlgroup_id,
			':letter_id' => $sending->id,
			':oper' => $oper
		]));
	}

	protected function _sendToReceiver($sending) {
			$mail = new Zend_Mail('utf-8');
                        
			$mail->setBodyHtml( Newsletter_Renderer::factory($sending->id)->renderBody() );
			
			$mail->setFrom(static::NEWSLETTER_EMAIL, static::NEWSLETTER_NAME);
                        
                        foreach (explode(';', $sending->useremail) as $email) {
                            $mail->addTo(trim($email));
                        }
			$mail->setSubject( $sending->subject );
			if(in_array(APPLICATION_ENV, array('production','testing'))){
				$mail->send();
			}
	}
}
