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

/**
 * ProcessSubscribersCommand
 * 
 * @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.2
 */
 
class ProcessSubscribersCommand extends CConsoleCommand 
{
    public function actionIndex() 
    {
        $options = Yii::app()->options;
        $unsubscribeDays = (int)$options->get('system.cron.process_subscribers.unsubscribe_days', 7);
        $unconfirmDays   = (int)$options->get('system.cron.process_subscribers.unconfirm_days', 7);
        
        if ($memoryLimit = $options->get('system.cron.process_subscribers.memory_limit')) {
            ini_set('memory_limit', $memoryLimit);
        }
        
        try {
            
            $connection = Yii::app()->getDb();
            
            if ($unsubscribeDays > 0) {
                $interval = 60 * 60 * 24 * $unsubscribeDays;
                $sql = 'DELETE FROM `{{list_subscriber}}` WHERE `status` = :st AND last_updated < DATE_SUB(NOW(), INTERVAL '.(int)$interval.' SECOND)';
                $command = $connection->createCommand($sql)->execute(array(
                    ':st' => ListSubscriber::STATUS_UNSUBSCRIBED,
                ));
            }
            
            if ($unconfirmDays > 0) {
                $interval = 60 * 60 * 24 * $unconfirmDays;
                $sql = 'DELETE FROM `{{list_subscriber}}` WHERE `status` = :st AND last_updated < DATE_SUB(NOW(), INTERVAL '.(int)$interval.' SECOND)';
                $command = $connection->createCommand($sql)->execute(array(
                    ':st' => ListSubscriber::STATUS_UNCONFIRMED,
                ));
            }    
            
        } catch (Exception $e) {
            
        }
    }

}
