<?php
	require_once( $GLOBALS["site_root"] . "/includes/tasks/GeneralTask.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/Newsletter.inc.php" );
	require_once( $GLOBALS["site_root"] . "/includes/models/TemplateMail.inc.php" );

	class NewsletterTask extends GeneralTask {
		protected $nm;
		
		public function __construct( $task_id , $task_processor ) {
			parent::__construct( $task_id , $task_processor );
			$this->nm = new NewsletterModel();
		}

		protected function activateNewsletterUser( $nl_id , $nu_id ) {
			$ins = array();
			$ins["newsletter_newsletter_id"]=sprintf( "%d" , $nl_id );
			$ins["newsletter_user_id"]=sprintf( "%d" , $nu_id );
			FNTH_db_free_result( FNTH_db_query(
				FNTH_db_generate_insert_query( "newsletter_newsletter_users" , $ins )
			) );
			usleep( 10000 );
		}
		
		protected function processActivationTask() {
			if ($this->task_processor->timeLeft()<3) return false;	// mindjart lejar az ido

			$nl_id = $this->tm->getTaskUID();
			$newsletter = $this->nm->getNewsletterFromId( $nl_id );

			$ts = $this->tm->getTaskState();
			$where_clause = sprintf( " where newsletter_group_id = %d", $newsletter["newsletter_group_id"] );
			if (!isset( $ts["number_of_recipients"] )) {
				$numofitems = FNTH_db_get_field( sprintf( "select count(*) as num from newsletter_group_users %s",$where_clause ) , "num" );
				$ts["number_of_recipients"]=$numofitems;
				$ts["offset"]=0;
			}

			$batchsize = 1000;
			$query = sprintf( "select newsletter_user_id from newsletter_group_users %s
				order by newsletter_user_id
				limit %d offset %d",
				$where_clause ,
				$batchsize ,
				$ts["offset"] );
			$nu_ids = FNTH_db_get_column( $query , "newsletter_user_id" );
			if (!empty( $nu_ids )) {
				foreach ($nu_ids as $nu_id) {
					if ($this->task_processor->timeleft()<3) return false;
					$this->task_processor->log( sprintf( "activating #%d newsletter (%d/%d)",
						$nl_id , $ts["offset"]+1 , $ts["number_of_recipients"] ) );
					$this->activateNewsletterUser( $nl_id , $nu_id );
					$ts["offset"]++;
					$this->tm->setTaskState( $ts );
					$this->tm->updateTask();
				}
			}
			if ($ts["offset"]==$ts["number_of_recipients"] || empty( $nu_ids )) {
				// close task
				$query = sprintf( "update newsletter_newsletters set nl_is_activated=true where newsletter_newsletter_id=%d",
					$nl_id );
				FNTH_db_free_result( FNTH_db_query( $query ) );
				return true;
			}
			$this->tm->lowerTaskPriority();
			$this->tm->updateTask();
			return false;
		}
		
		protected function processSendNewsletterCore( $nl_id , $nu_id ) {
			$this->nm->sendNewsletterToUser( $nl_id , $nu_id );
		}

		protected function processSendNewsletter( $nl_id , $nu_id ) {
			$this->task_processor->log( sprintf( "sent newsletter #%d to user %d" , $nl_id , $nu_id ) );
			$this->processSendNewsletterCore( $nl_id , $nu_id );
		}

		protected function processSendTask() {
			if ($this->task_processor->timeLeft()<3) return false;	// mindjart lejar az ido

			$nl_id = $this->tm->getTaskUID();
			$newsletter = $this->nm->getNewsletterFromId( $nl_id );

			$ts = $this->tm->getTaskState();
			$where_clause = sprintf( " where newsletter_newsletter_id = %d", $nl_id );

			if (!isset( $ts["number_of_recipients"] )) {
				$numofitems = FNTH_db_get_field( sprintf( "select count(*) as num from newsletter_newsletter_users %s",
					$where_clause ) , "num" );
				$ts["number_of_recipients"]=$numofitems;
				$ts["offset"]=0;
			}

			$where_clause.=sprintf( " and nnu_senttstamp is null" );
			$batchsize = 1000;

			$query = sprintf( "select
				newsletter_user_id
				from newsletter_newsletter_users %s
				order by newsletter_user_id limit %d offset %d" , $where_clause , $batchsize , $ts["offset"] );
			$nu_ids = FNTH_db_get_column( $query , "newsletter_user_id" );

			if (!empty( $nu_ids )) {
				foreach ($nu_ids as $nu_id) {
					if ($this->task_processor->timeleft()<3) return false;
					$this->task_processor->log( sprintf( "sending #%d newsletter (%d/%d)",
						$nl_id , $ts["offset"]+1 , $ts["number_of_recipients"] ) );
					$this->processSendNewsletter( $nl_id , $nu_id );
					$ts["offset"]++;
					$this->tm->setTaskState( $ts );
					$this->tm->updateTask();
				}
			}

			if ($ts["offset"]==$ts["number_of_recipients"] || empty( $nu_ids )) {
				// close task
				$query = sprintf( "update newsletter_newsletters set nl_senttstamp=now() where newsletter_newsletter_id=%d" , $nl_id );
				FNTH_db_free_result( FNTH_db_query( $query ) );
				return true;
			}
			$this->tm->lowerTaskPriority();
			$this->tm->updateTask();
			return false;
		}
		
		public function processTask() {
			$success = false;
			$task_type = $this->tm->getTaskType();
			switch ($task_type) {
			case "newsletter_activation":
				$success = $this->processActivationTask();
				break;
			case "newsletter_send":
				$success = $this->processSendTask();
				break;
			}
			if ($success)
				$this->tm->closeTask();
			else
				$this->tm->releaseTask();
		}
	}
?>
