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

/**
 * CampaignsController
 * 
 * Handles the actions for campaigns related tasks
 * 
 * @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 CampaignsController extends Controller
{
    public function init()
    {
        $pageScripts = $pageStyles = array();
        
        $pageStyles['datepicker']   = AssetsUrl::js('datetimepicker/css/bootstrap-datetimepicker.min.css');
        $pageScripts['datepicker']  = AssetsUrl::js('datetimepicker/js/bootstrap-datetimepicker.min.js');
        
        $languageCode = LanguageHelper::getAppLanguageCode();
        if (Yii::app()->language != Yii::app()->sourceLanguage && is_file(AssetsPath::js($languageFile = 'datetimepicker/js/locales/bootstrap-datetimepicker.'.$languageCode.'.js'))) {
            $pageScripts['datepicker-language'] = AssetsUrl::js($languageFile);
        }
        
        $pageScripts = CMap::mergeArray($pageScripts, array(
            'campaigns' => AssetsUrl::js('campaigns.js'),
        ));
        
        foreach ($pageScripts as $handler => $url) {
           Yii::app()->clientScript->registerScriptFile($url);
        }

        $pageStyles = CMap::mergeArray($pageStyles, array(
            'wizard' => AssetsUrl::css('wizard.css')
        ));
        
        foreach ($pageStyles as $handler => $url) {
           Yii::app()->clientScript->registerCssFile($url);
        }
        
        parent::init();
    }
    
    /**
     * Define the filters for various controller actions
     * Merge the filters with the ones from parent implementation
     */
    public function filters()
    {
        return CMap::mergeArray(array(
            'postOnly + delete, pause_unpause, copy, spamcheck, resume_sending, remove_attachment',
        ), parent::filters());
    }
    
    /**
     * List available campaigns
     */
    public function actionIndex()
    {
        $request = Yii::app()->request;
        $campaign = new Campaign('search');
        $campaign->attributes = (array)$request->getQuery($campaign->modelName, array());
        $campaign->customer_id = (int)Yii::app()->customer->getId();
        
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('campaigns', 'Your campaigns'), 
            'pageBreadcrumbs'   => array(
                Yii::t('campaigns', 'Campaigns') => $this->createUrl('campaigns/index'),
                Yii::t('app', 'View all')
            )
        ));
        
        $this->render('index', compact('campaign'));
    }
    
    /**
     * Show the overview for a campaign
     */
    public function actionOverview($campaign_uid)
    {
        $campaign = $this->loadCampaignModel($campaign_uid);
        $request = Yii::app()->request;
        
        if (!$campaign->accessOverview) {
            $this->redirect(array('campaigns/setup', 'campaign_uid' => $campaign->campaign_uid));
        }
        
        $campaign->attachBehavior('stats', array(
            'class' => 'customer.components.behaviors.CampaignStatsProcessorBehavior',
        ));
        
        $options        = Yii::app()->options;
        $webVersionUrl  = $options->get('system.urls.frontend_absolute_url');
        $webVersionUrl .= 'campaigns/' . $campaign->campaign_uid;
        
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('campaigns', 'Campaign overview'),
            'pageHeading'       => Yii::t('campaigns', 'Campaign overview'),
            'pageBreadcrumbs'   => array(
                Yii::t('campaigns', 'Campaigns') => $this->createUrl('campaigns/index'),
                $campaign->name => $this->createUrl('campaigns/overview', array('campaign_uid' => $campaign_uid)),
                Yii::t('campaigns', 'Overview')
            )
        ));

        $this->render('overview', compact('campaign', 'webVersionUrl'));
    }
    
    /**
     * Create a new campaign
     */
    public function actionCreate()
    {
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        $campaign = new Campaign('step-name');
        $campaign->customer_id = (int)Yii::app()->customer->getId();
        
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($campaign->modelName, array()))) {
            $campaign->attributes = $attributes;
            if ($campaign->save()) {
                if ($logAction = Yii::app()->customer->getModel()->asa('logAction')) {
                    $logAction->campaignCreated($campaign);    
                }
                
                $option = new CampaignOption();
                $option->campaign_id = $campaign->campaign_id;
                $option->save();
                
                $notify->addSuccess(Yii::t('app', 'Your form has been successfully saved!'));
                $this->redirect(array('campaigns/setup', 'campaign_uid' => $campaign->campaign_uid));
            } else {
                $notify->addError(Yii::t('app', 'Your form has a few errors, please fix them and try again!'));
            }
        }
        
        $listsArray = CMap::mergeArray(array('' => Yii::t('app', 'Choose')), $campaign->getListsDropDownArray());
        $segmentsArray = CMap::mergeArray(array('' => Yii::t('app', 'Choose')), $campaign->getSegmentsDropDownArray());
        
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('campaigns', 'Create new campaign'),
            'pageHeading'       => Yii::t('campaigns', 'Create new campaign'),
            'pageBreadcrumbs'   => array(
                Yii::t('campaigns', 'Campaigns') => $this->createUrl('campaigns/index'),
                Yii::t('app', 'Create new')
            )
        ));
        
        $this->render('step-name', compact('campaign', 'listsArray', 'segmentsArray'));
    }
    
    /**
     * Update existing campaign
     */
    public function actionUpdate($campaign_uid)
    {
        $request    = Yii::app()->request;
        $notify     = Yii::app()->notify;
        $campaign   = $this->loadCampaignModel($campaign_uid);
        
        if (!$campaign->editable) {
            $this->redirect(array('campaigns/overview', 'campaign_uid' => $campaign->campaign_uid));
        }

        $campaign->scenario = 'step-name';
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($campaign->modelName, array()))) {
            $campaign->attributes = $attributes;
            if ($campaign->save()) {
                if ($logAction = Yii::app()->customer->getModel()->asa('logAction')) {
                    $logAction->campaignUpdated($campaign);    
                }
                $notify->addSuccess(Yii::t('app', 'Your form has been successfully saved!'));
                $this->redirect(array('campaigns/setup', 'campaign_uid' => $campaign->campaign_uid));
            } else {
                $notify->addError(Yii::t('app', 'Your form has a few errors, please fix them and try again!'));
            }
        }
        
        $listsArray = CMap::mergeArray(array('' => Yii::t('app', 'Choose')), $campaign->getListsDropDownArray());
        $segmentsArray = CMap::mergeArray(array('' => Yii::t('app', 'Choose')), $campaign->getSegmentsDropDownArray());
        
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('campaigns', 'Update campaign'),
            'pageHeading'       => Yii::t('campaigns', 'Update campaign'),
            'pageBreadcrumbs'   => array(
                Yii::t('campaigns', 'Campaigns') => $this->createUrl('campaigns/index'),
                $campaign->name => $this->createUrl('campaigns/update', array('campaign_uid' => $campaign_uid)),
                Yii::t('app', 'Update')
            )
        ));
        
        $this->render('step-name', compact('campaign', 'listsArray', 'segmentsArray'));
    }
    
    /**
     * Setup campaign
     */
    public function actionSetup($campaign_uid)
    {
        $request    = Yii::app()->request;
        $notify     = Yii::app()->notify;
        $campaign   = $this->loadCampaignModel($campaign_uid);
        
        if (!$campaign->editable) {
            $this->redirect(array('campaigns/overview', 'campaign_uid' => $campaign->campaign_uid));
        }
        
        $campaign->scenario = 'step-setup';
        $default = $campaign->list->default;
        $sameFields = array('from_name', 'from_email', 'subject', 'reply_to');
        
        if (!empty($default)) {
            foreach ($sameFields as $attribute) {
                if (empty($campaign->$attribute)) {
                    $campaign->$attribute = $default->$attribute;
                }    
            }    
        }
        
        // delivery servers for this campaign - start
        $campaignToDeliveryServers = CampaignToDeliveryServer::model();
        $deliveryServers = DeliveryServer::model()->findAll(array(
            'select'    => 'server_id, hostname',
            'condition' => 'status = :s',
            'params'    => array(':s' => DeliveryServer::STATUS_ACTIVE),
        ));
        
        $campaignDeliveryServers = $campaignToDeliveryServers->findAllByAttributes(array(
            'campaign_id' => $campaign->campaign_id,
        ));
        $campaignDeliveryServersArray = array();
        foreach ($campaignDeliveryServers as $srv) {
            $campaignDeliveryServersArray[] = $srv->server_id;
        }
        // delivery servers for this campaign - end
        
        // attachments - start
        $attachment = new CampaignAttachment('multi-upload');
        $attachment->campaign_id = $campaign->campaign_id;
        // attachments - end
        
        if ($request->isPostRequest && ($attributes = (array)$request->getPost($campaign->modelName, array()))) {
            $campaign->attributes = $attributes;
            $campaign->option->attributes = (array)$request->getPost($campaign->option->modelName, array());
            if ($campaign->save() && $campaign->option->save()) {
                
                $campaignToDeliveryServers->deleteAllByAttributes(array(
                    'campaign_id' => $campaign->campaign_id,
                ));
                
                if (($attributes = (array)$request->getPost($campaignToDeliveryServers->modelName, array()))) {
                    foreach ($attributes as $serverId) {
                        $relation = new CampaignToDeliveryServer();
                        $relation->campaign_id = $campaign->campaign_id;
                        $relation->server_id = (int)$serverId;
                        $relation->save();
                    }
                }
                
                if ($attachments = CUploadedFile::getInstances($attachment, 'file')) {
                    $attachment->file = $attachments;
                    $attachment->validateAndSave();
                }
                
                $notify->addSuccess(Yii::t('app', 'Your form has been successfully saved!'));
                $this->redirect(array('campaigns/template', 'campaign_uid' => $campaign->campaign_uid));
            } else {
                $notify->addError(Yii::t('app', 'Your form has a few errors, please fix them and try again!'));
            }
        }
        
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('campaigns', 'Setup campaign'),
            'pageHeading'       => Yii::t('campaigns', 'Campaign setup'),
            'pageBreadcrumbs'   => array(
                Yii::t('campaigns', 'Campaigns') => $this->createUrl('campaigns/index'),
                $campaign->name => $this->createUrl('campaigns/update', array('campaign_uid' => $campaign_uid)),
                Yii::t('campaigns', 'Setup')
            )
        ));
        
        $this->render('step-setup', compact(
            'campaign', 
            'attachment',
            'campaignToDeliveryServers', 
            'deliveryServers', 
            'campaignDeliveryServersArray'
        ));
    }
    
    /**
     * Choose or create campaign template
     */
    public function actionTemplate($campaign_uid, $do = 'create')
    {
        $request = Yii::app()->request;
        $campaign = $this->loadCampaignModel($campaign_uid);
        
        if (!$campaign->editable) {
            $this->redirect(array('campaigns/overview', 'campaign_uid' => $campaign->campaign_uid));
        }

        if ($do === 'select') {
            
            if ($template_uid = $request->getQuery('template_uid')) {
                $campaignTemplate = $campaign->template;
                if (empty($campaignTemplate)) {
                    $campaignTemplate = new CampaignTemplate();
                }
                $campaignTemplate->setScenario('copy');
                
                $selectedTemplate = CustomerEmailTemplate::model()->findByAttributes(array(
                    'template_uid'  => $template_uid,
                    'customer_id'   => (int)Yii::app()->customer->getId(),
                ));
                
                $redirect = array('campaigns/template', 'campaign_uid' => $campaign_uid, 'do' => 'create');
                
                if (!empty($selectedTemplate)) {
                    
                    $campaignTemplate->campaign_id  = $campaign->campaign_id;
                    $campaignTemplate->template_id  = $selectedTemplate->template_id;
                    $campaignTemplate->content      = $selectedTemplate->content;
                    $campaignTemplate->inline_css   = $selectedTemplate->inline_css;
                    
                    if (!empty($campaign->option) && $campaign->option->plain_text_email == CampaignOption::TEXT_YES && $campaignTemplate->auto_plain_text === CampaignTemplate::TEXT_YES) {
                        $campaignTemplate->plain_text = CampaignHelper::htmlToText($selectedTemplate->content);
                    }
                
                    $campaignTemplate->save();
                    
                    /**
                     * We also need to create a copy of the template files.
                     * This avoids the scenario where a campaign based on a uploaded template is sent
                     * then after a while the template is deleted. 
                     * In this scenario, the campaign will remain without images. 
                     */

                    $storagePath = Yii::getPathOfAlias('root.frontend.assets.gallery');
                    
                    // make sure the new template has images, otherwise don't bother.
                    $filesPath = $storagePath.'/'.$selectedTemplate->template_uid;
                    if (!file_exists($filesPath) || !is_dir($filesPath)) {
                        $this->redirect($redirect);
                    }

                    // check if there's already a copy if this campaign template. if so, remove it, we don't want a folder with 1000 images.
                    $campaignFiles = $storagePath.'/cmp'.$campaign->campaign_uid;
                    if (file_exists($campaignFiles) && is_dir($campaignFiles)) {
                        FileSystemHelper::deleteDirectoryContents($campaignFiles, true, 1);
                    }
                    
                    // copy the template folder to the campaign folder.
                    if (!FileSystemHelper::copyOnlyDirectoryContents($filesPath, $campaignFiles)) {
                        $this->redirect($redirect);
                    }
                    
                    $search = array (
                        'frontend/assets/gallery/cmp'.$campaign->campaign_uid,
                        'frontend/assets/gallery/'.$selectedTemplate->template_uid
                    );
                    $replace = 'frontend/assets/gallery/cmp'.$campaign->campaign_uid;
                    $campaignTemplate->content = str_ireplace($search, $replace, $campaignTemplate->content);
                    
                    if (!empty($campaign->option) && $campaign->option->plain_text_email == CampaignOption::TEXT_YES && $campaignTemplate->auto_plain_text === CampaignTemplate::TEXT_YES) {
                        $campaignTemplate->plain_text = CampaignHelper::htmlToText($campaignTemplate->content);
                    }
                    
                    $campaignTemplate->save(false);
                }
                $this->redirect($redirect);
            }
            
            $criteria = new CDbCriteria();
            $criteria->compare('t.customer_id', (int)Yii::app()->customer->getId());
            $criteria->order = 't.template_id DESC';
            $count = CustomerEmailTemplate::model()->count($criteria);
            
            $pages = new CPagination($count);
            $pages->pageSize = 30;
            $pages->applyLimit($criteria);
            
            $this->data->templates = CustomerEmailTemplate::model()->findAll($criteria);
            $this->data->pages = $pages;
            
            $viewFile = 'step-template-select';
        
        } elseif ($do === 'create') {
            
            $template = $campaign->template;
            if (empty($template)) {
                $template = new CampaignTemplate();
            }
            $template->fieldDecorator->onHtmlOptionsSetup = array($this, '_setEditorOptions');
            $template->campaign_id = $campaign->campaign_id;
            $this->data->template = $template;

            if ($request->isPostRequest && ($attributes = (array)$request->getPost($template->modelName, array()))) {
                $template->attributes = $attributes;
                $template->content = Yii::app()->params['POST'][$template->modelName]['content'];
                $template->campaign_id = $campaign->campaign_id;
                $parser = new EmailTemplateParser();
                $parser->inlineCss = $template->inline_css === CampaignTemplate::TEXT_YES;
                $template->content = $parser->setContent($template->content)->getContent();
                $isNext = $request->getPost('is_next', 0);
                
                if (!empty($campaign->option) && $campaign->option->plain_text_email == CampaignOption::TEXT_YES && $template->auto_plain_text === CampaignTemplate::TEXT_YES && empty($template->plain_text)) {
                    $template->plain_text = CampaignHelper::htmlToText($template->content);
                }
                
                if ($template->save()) {
                    Yii::app()->notify->addSuccess(Yii::t('app', 'Your form has been successfully saved!'));
                    if ($isNext) {
                        $this->redirect(array('campaigns/confirm', 'campaign_uid' => $campaign_uid));
                    }
                } else {
                    Yii::app()->notify->addError(Yii::t('app', 'Your form has a few errors, please fix them and try again!'));
                }
            }
            
            $this->data->templateUp = new CampaignEmailTemplateUpload('upload');
            $viewFile = 'step-template-create';
        
        } elseif ($do == 'upload') {
            
            if ($request->isPostRequest && $request->getPost('is_next', 0)) {
                $this->redirect(array('campaigns/confirm', 'campaign_uid' => $campaign_uid));
            }
            
            $template = $campaign->template;
            if (empty($template)) {
                $template = new CampaignTemplate();
            }
            $template->fieldDecorator->onHtmlOptionsSetup = array($this, '_setEditorOptions');
            $template->campaign_id = $campaign->campaign_id;

            $templateUp = new CampaignEmailTemplateUpload('upload');
            $templateUp->customer_id = (int)Yii::app()->customer->getId();
            $templateUp->campaign    = $campaign;

            if ($request->isPostRequest && ($attributes = (array)$request->getPost($templateUp->modelName, array()))) {
                $templateUp->attributes = $attributes;
                $templateUp->archive = CUploadedFile::getInstance($templateUp, 'archive');
                if (!$templateUp->validate() || !$templateUp->uploader->handleUpload()) {
                    Yii::app()->notify->addError($templateUp->shortErrors->getAllAsString());
                } else {
                    $template->content      = $templateUp->content;
                    $template->inline_css   = $templateUp->inline_css;
                    
                    if (!empty($campaign->option) && $campaign->option->plain_text_email == CampaignOption::TEXT_YES && $templateUp->auto_plain_text === CampaignTemplate::TEXT_YES && empty($templateUp->plain_text)) {
                        $template->plain_text = CampaignHelper::htmlToText($templateUp->content);
                    }
                    
                    if ($template->save()) {
                        Yii::app()->notify->addSuccess(Yii::t('app', 'Your file has been successfully uploaded!'));
                    } else {
                        Yii::app()->notify->addError($template->shortErrors->getAllAsString());
                    }
                }
            }
            
            $this->data->templateUp = $templateUp;
            $this->data->template   = $template;
            $viewFile = 'step-template-create';
            
        } else {
            
            $this->redirect(array('campaigns/template', 'campaign_uid' => $campaign_uid, 'do' => 'create'));
        
        }
        
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('campaigns', 'Campaign template'),
            'pageHeading'       => Yii::t('campaigns', 'Campaign template'),
            'pageBreadcrumbs'   => array(
                Yii::t('campaigns', 'Campaigns') => $this->createUrl('campaigns/index'),
                $campaign->name => $this->createUrl('campaigns/update', array('campaign_uid' => $campaign_uid)),
                Yii::t('campaigns', 'Template')
            )
        ));
        
        $this->render($viewFile, compact('campaign'));
    }
    
    /**
     * Confirm the campaign and schedule it for sending
     */
    public function actionConfirm($campaign_uid)
    {
        $request    = Yii::app()->request;
        $notify     = Yii::app()->notify;
        $campaign   = $this->loadCampaignModel($campaign_uid);

        if (!$campaign->editable) {
            $this->redirect(array('campaigns/overview', 'campaign_uid' => $campaign->campaign_uid));
        }
        
        $customer = Yii::app()->customer->getModel();
        $campaign->scenario = 'step-confirm';
        
        $segmentSubscribers = 0;
        $listSubscribers = 0;
        $hasError = false;

        if (!empty($campaign->segment_id)) {
            $segmentSubscribers = $campaign->segment->countSubscribers();
            if ($segmentSubscribers == 0) {
                $hasError = true;
                $notify->addError(Yii::t('campaigns', 'Your selected segment does not have any subscriber. Please go back and correct this.'));
            }
        }
        
        if (!empty($campaign->list_id)) {
            $listSubscribers = $campaign->list->confirmedSubscribersCount;
            if ($listSubscribers == 0) {
                $hasError = true;
                $notify->addError(Yii::t('campaigns', 'Your selected list does not have any subscriber. Please go back and correct this.'));
            }
        }
        
        if ($hasError) {
            $notify->addError(Yii::t('campaigns', 'Please fix the above errors before continue.'));
        }
        
        if (empty($campaign->template->content)) {
            $hasError = true;
            $notify->addError(Yii::t('campaigns', 'Missing campaign template!'));
        }
        
        if (!$hasError && $request->isPostRequest && ($attributes = (array)$request->getPost($campaign->modelName, array()))) {
            $campaign->attributes = $attributes;
            $campaign->status = Campaign::STATUS_PENDING_SENDING;
            if ($campaign->save()) {
                if ($logAction = Yii::app()->customer->getModel()->asa('logAction')) {
                    $logAction->campaignScheduled($campaign);    
                }
                $dateTime = new DateTime($campaign->send_at);
                $dateTime->setTimezone(new DateTimeZone($customer->timezone));
                $sendDateTime = Yii::app()->dateFormatter->formatDateTime(CDateTimeParser::parse($dateTime->format('Y-m-d H:i:s'), 'yyyy-MM-dd HH:mm:ss'), "short", "short");
                Yii::app()->notify->addSuccess(Yii::t('campaigns', 'Your campaign named "{campaignName}" has been successfully saved and scheduled for sending at {sendDateTime}!', array(
                    '{campaignName}'    => $campaign->name,
                    '{sendDateTime}'    => $sendDateTime
                )));
                $this->redirect(array('campaigns/index'));
            } else {
                Yii::app()->notify->addError(Yii::t('app', 'Your form has a few errors, please fix them and try again!'));
            }
        }
        
        // prepare the send at for display.
        if ($campaign->send_at === null) {
            $dateTime = new DateTime('@'.strtotime('+30 minutes'));
        } else {
            $dateTime = new DateTime($campaign->send_at); 
        }
        
        $dateTime->setTimezone(new DateTimeZone($customer->timezone));
        $timestamp = CDateTimeParser::parse($dateTime->format('Y-m-d H:i:s'), 'yyyy-MM-dd HH:mm:ss');
        $campaign->send_at = Yii::app()->dateFormatter->formatDateTime($timestamp, 'short', 'short');
        $this->setData('fakeSendAt', date('Y-m-d H:i:s', $timestamp));

        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('campaigns', 'Campaign overview'),
            'pageHeading'       => Yii::t('campaigns', 'Campaign confirmation'),
            'pageBreadcrumbs'   => array(
                Yii::t('campaigns', 'Campaigns') => $this->createUrl('campaigns/index'),
                CHtml::encode($campaign->name) => $this->createUrl('campaigns/update', array('campaign_uid' => $campaign_uid)),
                Yii::t('campaigns', 'Confirmation')
            )
        ));
        
        $this->render('step-confirm', compact('campaign', 'listSubscribers', 'segmentSubscribers'));
    }

    /**
     * Test the campaign email template by sending it to desired email addressed
     */
    public function actionTest($campaign_uid)
    {
        $request    = Yii::app()->request;
        $notify     = Yii::app()->notify;
        $campaign   = $this->loadCampaignModel($campaign_uid);
        $template   = $campaign->template;
        
        if (!$campaign->editable) {
            $this->redirect(array('campaigns/overview', 'campaign_uid' => $campaign->campaign_uid));
        }

        if (!$request->getPost('email')) {
            $notify->addError(Yii::t('campaigns', 'Please specify the email address to where we should send the test email.'));
            $this->redirect(array('campaigns/template', 'campaign_uid' => $campaign_uid));
        }
        
        $emails = explode(',', $request->getPost('email'));
        $emails = array_map('trim', $emails);
        $emails = array_unique($emails);
        $emails = array_slice($emails, 0, 10);
        
        $server = DeliveryServer::pickServer();
        if (empty($server)) {
            $notify->addError(Yii::t('app', 'Email delivery is temporary disabled.'));
            $this->redirect(array('campaigns/template', 'campaign_uid' => $campaign_uid));
        }
        
        foreach ($emails as $index => $email) {
            if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                $notify->addError(Yii::t('email_templates',  'The email address {email} does not seem to be valid!', array('{email}' => CHtml::encode($email))));
                unset($emails[$index]);
                continue;
            }
        }
        
        if (empty($emails)) {
            $notify->addError(Yii::t('campaigns', 'Cannot send using provided email address(es)!'));
            $this->redirect(array('campaigns/template', 'campaign_uid' => $campaign_uid));
        }
        
        $subscriber = ListSubscriber::model()->findByAttributes(array(
            'list_id'   => $campaign->list->list_id,
            'status'    => ListSubscriber::STATUS_CONFIRMED,
        ));
        
        $fromName        = $campaign->list->default->from_name;
        $emailSubject    = '[TEST CAMPAIGN] '.$campaign->name;
        $emailContent    = $template->content;
        
        if (!empty($subscriber)) {
            
            if (!empty($campaign->option) && $campaign->option->xml_feed == CampaignOption::TEXT_YES) {
                $emailContent = CampaignXmlFeedParser::parseContent($emailContent);
            }
            
            if (!empty($campaign->option) && $campaign->option->json_feed == CampaignOption::TEXT_YES) {
                $emailContent = CampaignJsonFeedParser::parseContent($emailContent);
            }

            $emailData    = CampaignHelper::parseContent($emailContent, $campaign, $subscriber, false);
            list(, $_emailSubject, $emailContent) = $emailData;
            $emailSubject .= ' - ' . $_emailSubject;
        }
        
        foreach ($emails as $email) {

            $params = array(
                'to'        => $email,
                'from'      => array($server->getFromEmail() => $fromName),
                'subject'   => $emailSubject,
                'body'      => $emailContent,
            );
            
            $sent = false;
            for ($i = 0; $i < 3; ++$i) {
                if ($sent = $server->setDeliveryFor(DeliveryServer::DELIVERY_FOR_CAMPAIGN_TEST)->setDeliveryObject($campaign)->sendEmail($params)) {
                    break;
                }
                $server = DeliveryServer::pickServer($server->server_id);    
            }
            
            if (!$sent) {
                $notify->addError(Yii::t('campaigns', 'Unable to send the test email to {email}!', array(
                    '{email}' => CHtml::encode($email),
                )));
            } else {
                $notify->addSuccess(Yii::t('campaigns', 'Test email successfully sent to {email}!', array(
                    '{email}' => CHtml::encode($email),
                )));
            }
        }
        
        $this->redirect(array('campaigns/template', 'campaign_uid' => $campaign_uid));
    }
    
    /**
     * List available list segments when choosing a list for a campaign
     */
    public function actionList_segments($list_id)
    {
        $request = Yii::app()->request;
        if (!$request->isAjaxRequest) {
            $this->redirect(array('campaigns/index'));
        }
        
        $list = Lists::model()->findByAttributes(array(
            'list_id'       => (int)$list_id,
            'customer_id'   => (int)Yii::app()->customer->getId(),
        ));
        if (empty($list)){
            return $this->renderJson(array('segments' => array()));
        }
        
        $campaign = new Campaign();
        $campaign->list_id = $list->list_id;
        $segments = $campaign->getSegmentsDropDownArray();

        $json = array();
        $json[] = array(
            'segment_id'    => '',
            'name'          => Yii::t('app', 'Choose')
        );
        
        foreach ($segments as $segment_id => $name) {
            $json[] = array(
                'segment_id' => $segment_id, 
                'name'       => CHtml::encode($name)
            );
        }
        
        return $this->renderJson(array('segments' => $json));
    }
    
    /**
     * Copy campaign
     */
    public function actionCopy($campaign_uid)
    {
        $campaign = $this->loadCampaignModel($campaign_uid);
        
        $campaign->copy();
        
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        if (!$request->isAjaxRequest) {
            $notify->addSuccess(Yii::t('campaigns', 'Your campaign was successfully copied!'));
            $this->redirect($request->getPost('returnUrl', array('campaigns/index')));
        }
    }
    
    /**
     * Delete campaign, will remove all campaign related data
     */
    public function actionDelete($campaign_uid)
    {
        $campaign = $this->loadCampaignModel($campaign_uid);
        
        if ($campaign->removable) {
            
            set_time_limit(0);
            ignore_user_abort(true);
        
            $campaign->delete();
            
            if ($logAction = Yii::app()->customer->getModel()->asa('logAction')) {
                $logAction->campaignDeleted($campaign);    
            }    
        }
        
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        if (!$request->getQuery('ajax')) {
            $notify->addSuccess(Yii::t('campaigns', 'Your campaign was successfully deleted!'));
            $this->redirect($request->getPost('returnUrl', array('campaigns/index')));
        }
    }
    
    /**
     * Allows to pause/unpause the sending of a campaign
     */
    public function actionPause_unpause($campaign_uid)
    {
        $campaign = $this->loadCampaignModel($campaign_uid);
        
        $campaign->pauseUnpause();
        
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        if (!$request->getQuery('ajax')) {
            $notify->addSuccess(Yii::t('campaigns', 'Your campaign was successfully changed!'));
            $this->redirect($request->getPost('returnUrl', array('campaigns/index')));
        }
    }
    
    /**
     * Allows to resume sending of a stuck campaign
     */
    public function actionResume_sending($campaign_uid)
    {
        $campaign = $this->loadCampaignModel($campaign_uid);
        
        if ($campaign->isProcessing) {
            $campaign->status = Campaign::STATUS_SENDING;
            $campaign->save(false);
        }
        
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        if (!$request->isAjaxRequest) {
            $notify->addSuccess(Yii::t('campaigns', 'Your campaign was successfully changed!'));
            $this->redirect($request->getPost('returnUrl', array('campaigns/index')));
        }
    }
    
    /**
     * Tries to get the spam score for campaign.
     * For now this is in beta usage, need to see how it behaves.
     * 
     */
    public function actionSpamcheck($campaign_uid)
    {
        $campaign = $this->loadCampaignModel($campaign_uid);
        
        $score = CampaignHelper::getSpamScore($campaign);
        
        if (!is_array($score) || !isset($score['score'])) {
            return $this->renderJson(array(
                'result' => 'error',
                'message'=> Yii::t('campaigns', 'Unable to get the spam score for your campaign!')
            ));
        }
        
        $message = Yii::t('campaigns', 'Between 0 and 5, your campaign spam score is {score}.', array(
            '{score}' => $score['score'],
        ));
                
        return $this->renderJson(array(
            'result'    => 'success',
            'message'   => $message,
            'response'  => $score,
        ));
    }
    
    /**
     * Remove certain campaign attachment
     */
    public function actionRemove_attachment($campaign_uid, $attachment_id)
    {
        $campaign = $this->loadCampaignModel($campaign_uid);
        $attachment = CampaignAttachment::model()->findByAttributes(array(
            'attachment_id' => (int)$attachment_id,
            'campaign_id'   => (int)$campaign->campaign_id,
        ));
        
        if (!empty($attachment)) {
            $attachment->delete();
        }
        
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        if (!$request->isAjaxRequest) {
            $notify->addSuccess(Yii::t('campaigns', 'Your campaign attachment was successfully removed!'));
            $this->redirect($request->getPost('returnUrl', array('campaigns/index')));
        }
    }
    
    public function actionSync_datetime()
    {
        $request    = Yii::app()->request;
        $date       = $request->getQuery('date', date('Y-m-d H:i:s'));
        $timestamp  = @strtotime($date);
        $date       = Yii::app()->dateFormatter->formatDateTime($timestamp, 'short', 'short');
        
        return $this->renderJson(array(
            'date' => $date,
        ));
    }
    
    /**
     * Helper method to load the campaign AR model
     */
    public function loadCampaignModel($campaign_uid)
    {
        $model = Campaign::model()->findByAttributes(array(
            'customer_id'   => (int)Yii::app()->customer->getId(),
            'campaign_uid'  => $campaign_uid,
        ));
        
        if($model === null) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        
        return $model;
    }
    
    /**
     * Callback method to setup the editor for the template step
     */
    public function _setEditorOptions(CEvent $event)
    {
        if ($event->params['attribute'] == 'content') {
            $options = array();
            if ($event->params['htmlOptions']->contains('wysiwyg_editor_options')) {
                $options = (array)$event->params['htmlOptions']->itemAt('wysiwyg_editor_options');
            }
            $options['id'] = CHtml::activeId($event->sender->owner, 'content');
            $options['fullPage'] = true;
            $options['allowedContent'] = true;
            $options['contentsCss'] = array();
            $options['height'] = 500;
            
            $event->params['htmlOptions']->add('wysiwyg_editor_options', $options);
        }
    }
}