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

/**
 * BounceHandlerCommand
 * 
 * @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 BounceHandlerCommand extends CConsoleCommand 
{
    public function actionIndex() 
    {
        // because some cli are not compiled same way with the web module.
        if (!function_exists('imap_open')) {
            return;
        }
        
        $options = Yii::app()->options;
        
        $servers = BounceServer::model()->findAll(array(
            'select'    => 't.server_id',
            'condition' => 't.status = :status',
            'params'    => array(':status' => BounceServer::STATUS_ACTIVE),
        ));
        
        if (empty($servers)) {
            return;
        }
        
        $serversIds = array();
        foreach ($servers as $server) {
            $serversIds[] = $server->server_id;
        }
        
        Yii::import('common.vendors.BounceHandler.*');
        
        if ($memoryLimit = $options->get('system.cron.process_delivery_bounce.memory_limit')) {
            ini_set('memory_limit', $memoryLimit);    
        }

        foreach ($serversIds as $serverId) {

            $server = BounceServer::model()->findByPk((int)$serverId);
            if (empty($server) || $server->status == BounceServer::STATUS_CRON_RUNNING) {
                continue;
            }
            $server->status = BounceServer::STATUS_CRON_RUNNING;
            $server->save(false);
            
            $bounceHandler = new BounceHandler($server->getConnectionString(), $server->username, $server->password, array(
                'returnOriginalEmailHeadersArray'   => true,
                'deleteMessages'                    => true,
                'processLimit'                      => 1000
            ));

            $results = $bounceHandler->getResults();
            if (empty($results)) {
                $server->status = BounceServer::STATUS_ACTIVE;
                $server->save(false);
                continue;
            }
            
            foreach ($results as $result) {

                if (!isset($result['originalEmailHeadersArray']['X-MW-CAMPAIGN-UID'], $result['originalEmailHeadersArray']['X-MW-SUBSCRIBER-UID'])) {
                    continue;
                }
                
                $campaignUid    = trim($result['originalEmailHeadersArray']['X-MW-CAMPAIGN-UID']);
                $subscriberUid  = trim($result['originalEmailHeadersArray']['X-MW-SUBSCRIBER-UID']);
                
                $campaign   = Campaign::model()->findByUid($campaignUid);
                $subscriber = ListSubscriber::model()->findByUid($subscriberUid);
                
                if (empty($campaign) || empty($subscriber)) {
                    continue;
                }
                
                $bounceLog = new CampaignBounceLog();
                $bounceLog->campaign_id     = $campaign->campaign_id;
                $bounceLog->subscriber_id   = $subscriber->subscriber_id;
                $bounceLog->message         = $result['diagnosticCode'];
                $bounceLog->bounce_type     = $result['bounceType'] == BounceHandler::BOUNCE_SOFT ? CampaignBounceLog::BOUNCE_SOFT : CampaignBounceLog::BOUNCE_HARD;
                $bounceLog->save();
            }
            
            $server->status = BounceServer::STATUS_ACTIVE;
            $server->save(false);
        }
    }

}