<?php defined('MW_PATH') || exit('No direct script access allowed');

/**
 * SendCampaignsCommand
 * 
 * @package MailWizz EMA
 * @author Serban George Cristian <cristian.serban@mailwizz.com> 
 * @link http://www.mailwizz.com/
 * @copyright 2013-2014 MailWizz EMA (http://www.mailwizz.com)
 * @license http://www.mailwizz.com/license/
 * @since 1.0
 */
 
class SendCampaignsCommand extends CConsoleCommand 
{
    public function actionIndex() 
    {
        // if there's no delivery server, stop.
        $server = DeliveryServer::pickServer();
        if (empty($server)) {
            return;
        }
        
        $options = Yii::app()->options;

        $criteria = new CDbCriteria();
        $criteria->select = 'campaign_id';
        $criteria->addInCondition('status', array(Campaign::STATUS_SENDING, Campaign::STATUS_PENDING_SENDING));
        $criteria->addCondition('send_at <= NOW()');
        $criteria->order = 'campaign_id ASC';
        $criteria->limit = (int)$options->get('system.cron.send_campaigns.campaigns_at_once', 10);
        
        // offer a chance to alter this criteria.
        $criteria = Yii::app()->hooks->applyFilters('console_send_campaigns_command_find_campaigns_criteria', $criteria);
        
        // and find all campaigns matching the criteria
        $campaigns = Campaign::model()->findAll($criteria);
        
        // nothing to send? rare case though...
        if (empty($campaigns)) {
            return;
        }
        
        // because a campaign can take a lot of time to be sent and we don't want to stop and wait.
        $campaignIds = array();
        foreach ($campaigns as $campaign) {
            $campaignIds[] = $campaign->campaign_id;
        }
        
        if ($memoryLimit = $options->get('system.cron.send_campaigns.memory_limit')) {
            ini_set('memory_limit', $memoryLimit);
        }
        
        // this allows the next cron to pick-up a campaign loaded in this one, thus making things easier to process
        foreach ($campaignIds as $campaignId) {
            $campaign = Campaign::model()->findByPk((int)$campaignId);
            if (empty($campaign) || $campaign->status == Campaign::STATUS_SENT) {
                continue;
            }

            // since 1.2
            if (!empty($campaign->list->customer) && !empty($campaign->list->customer->language_id)) {
                $language = Language::model()->findByPk((int)$campaign->list->customer->language_id);
                if (!empty($language)) {
                    Yii::app()->setLanguage($language->getLanguageAndLocaleCode());
                }    
            }
            
            $campaign->attachBehavior('sender', array(
                'class' => 'console.components.behaviors.CampaignSenderBehavior'
            ));
            
            $campaign->sender->sendCampaign();
        }
    }

}