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

/**
 * ListsController
 * 
 * Handles the actions for lists 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 ListsController extends Controller
{
    public function init()
    {
        $scripts = array(
            'lists' => AssetsUrl::js('lists.js'),
        );

        foreach ($scripts as $handler => $src) {
           Yii::app()->clientScript->registerScriptFile($src, null, array('id' => 'script-' . $handler));
        }
        
        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',
        ), parent::filters());
    }
    
    /**
     * Show available lists
     */
    public function actionIndex()
    {
        $request = Yii::app()->request;
        $list = new Lists('search');
        $list->attributes = (array)$request->getQuery($list->modelName, array());
        $list->customer_id = (int)Yii::app()->customer->getId();

        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | ' . Yii::t('lists', 'Your lists'),
            'pageBreadcrumbs'   => array(
                Yii::t('lists', 'Lists') => $this->createUrl('lists/index'),
                Yii::t('app', 'View all')
            )
        ));
        
        $this->render('list', compact('list'));
    }
    
    /**
     * Create a new list
     */
    public function actionCreate()
    {
        $request    = Yii::app()->request;
        $notify     = Yii::app()->notify;
        $customer   = Yii::app()->customer->getModel();
        
        $list = new Lists();
        $list->customer_id = $customer->customer_id;
        
        $listDefault = new ListDefault();
        $listCompany = new ListCompany();
        $listCustomerNotification = new ListCustomerNotification();

        // to create the default mail list fields.
        $list->attachBehavior('listDefaultFields', array(
            'class' => 'customer.components.db.behaviors.ListDefaultFieldsBehavior',
        ));
        
        if (!empty($customer->company)) {
            $listCompany->mergeWithCustomerCompany($customer->company);    
        }
        
        $listDefault->mergeWithCustomerInfo($customer);

        if ($request->isPostRequest && $request->getPost($list->modelName)) {
            $models = array($list, $listCompany, $listCustomerNotification, $listDefault);
            $hasErrors = false;
            foreach ($models as $model) {
                $model->attributes = (array)$request->getPost($model->modelName, array());
                if (!$model->validate()) {
                    $hasErrors = true; // don't break to collect errors for all models.
                }
            }
            if (!$hasErrors) {
                foreach ($models as $model) {
                    if (!($model instanceof Lists)) {
                        $model->list_id = $list->list_id;
                    }
                    $model->save(false);
                }
                
                if ($logAction = Yii::app()->customer->getModel()->asa('logAction')) {
                    $logAction->listCreated($list);    
                }
                
                $notify->addSuccess(Yii::t('app', 'Your form has been successfully saved!'));
                $this->redirect(array('lists/update', 'list_uid' => $list->list_uid));
            } else {
                $notify->addError(Yii::t('app', 'Your form contains errors, please correct them and try again.'));
            }
        }
        
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | ' . Yii::t('lists', 'Create new list'),
            'pageBreadcrumbs'   => array(
                Yii::t('lists', 'Lists') => $this->createUrl('lists/index'),
                Yii::t('app', 'Create new')
            )
        ));
        
        $this->render('form', compact('list', 'listDefault', 'listCompany', 'listCustomerNotification'));
    }
    
    /**
     * Update existing list
     */
    public function actionUpdate($list_uid)
    {
        $list       = $this->loadModel($list_uid);
        $request    = Yii::app()->request;
        $notify     = Yii::app()->notify;

        $listDefault = $list->default;
        $listCompany = $list->company;
        $listCustomerNotification = $list->customerNotification;

        if ($request->isPostRequest && $request->getPost($list->modelName)) {
            $models = array($list, $listCompany, $listCustomerNotification, $listDefault);
            $hasErrors = false;
            foreach ($models as $model) {
                $model->attributes = (array)$request->getPost($model->modelName, array());
                if (!$model->validate()) {
                    $hasErrors = true; // don't break to collect errors for all models.
                }
            }
            if (!$hasErrors) {
                foreach ($models as $model) {
                    $model->save(false);
                }
                
                if ($logAction = Yii::app()->customer->getModel()->asa('logAction')) {
                    $logAction->listUpdated($list);    
                }
                
                $notify->addSuccess(Yii::t('app', 'Your form has been successfully saved!'));
                $this->redirect(array('lists/update', 'list_uid' => $list->list_uid));
            } else {
                $notify->addError(Yii::t('app', 'Your form contains errors, please correct them and try again.'));
            }
        }
        
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | ' . Yii::t('lists', 'Update list'), 
            'pageBreadcrumbs'   => array(
                Yii::t('lists', 'Lists') => $this->createUrl('lists/index'),
                $list->name => $this->createUrl('lists/overview', array('list_uid' => $list->list_uid)),
                Yii::t('app', 'Update')
            )
        ));
        
        $this->render('form', compact('list', 'listDefault', 'listCompany', 'listCustomerNotification'));
    }
    
    /**
     * Delete existing list
     * This can take a lot of time if the list is large and has many custom fields. 
     * Just make sure it has enough time to execute.
     */
    public function actionDelete($list_uid)
    {
        $list = $this->loadModel($list_uid);
        
        // on big lists it takes a lot of time to do the deletions
        set_time_limit(0);
        ignore_user_abort(true);
        
        $list->delete();
        
        if ($logAction = Yii::app()->customer->getModel()->asa('logAction')) {
            $logAction->listDeleted($list);    
        }
                
        $request = Yii::app()->request;
        $notify = Yii::app()->notify;
        
        if (!$request->getQuery('ajax')) {
            $notify->addSuccess(Yii::t('app', 'Your item has been successfully deleted!'));
            $this->redirect($request->getPost('returnUrl', array('list/index')));
        }
    }
    
    /**
     * Display list overview
     * This is a page containing shortcuts to the most important list features.
     */
    public function actionOverview($list_uid)
    {
        $list = $this->loadModel($list_uid);
        
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | ' . Yii::t('lists', 'List overview'),
            'pageBreadcrumbs'   => array(
                Yii::t('lists', 'Lists') => $this->createUrl('lists/index'),
                $list->name => $this->createUrl('lists/overview', array('list_uid' => $list->list_uid)),
                Yii::t('lists', 'Overview')
            )
        ));
        
        $subscribersCount   = $list->subscribersCount;
        $segmentsCount      = $list->segmentsCount;
        $customFieldsCount  = $list->fieldsCount;
        $pagesCount         = ListPageType::model()->count();
        
        $this->render('overview', compact('list', 'subscribersCount', 'segmentsCount', 'customFieldsCount', 'pagesCount'));
    }
    
    /**
     * Helper method to load the list AR model
     */
    public function loadModel($list_uid)
    {
        $model = Lists::model()->findByAttributes(array(
            'list_uid'      => $list_uid,
            'customer_id'   => (int)Yii::app()->customer->getId(),
        ));
        
        if ($model === null) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        
        return $model;
    }
}