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

/**
 * Transactional_emailsController
 * 
 * Handles the actions for transactional emails 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.3.4.6
 */
 
class Transactional_emailsController extends Controller
{
    public function init()
    {
        $this->getData('pageScripts')->add(array('src' => AssetsUrl::js('transactional-emails.js')));
        parent::init();
    }
    
    /**
     * Define the filters for various controller actions
     * Merge the filters with the ones from parent implementation
     */
    public function filters()
    {
        $filters = array(
            'postOnly + delete',
        );
        
        return CMap::mergeArray($filters, parent::filters());
    }
    
    /**
     * List all available emails
     */
    public function actionIndex()
    {
        $request = Yii::app()->request;
        $email   = new TransactionalEmail('search');
        $email->unsetAttributes();
        
        $email->attributes = (array)$request->getQuery($email->modelName, array());
        
        $this->setData(array(
            'pageMetaTitle'     => $this->data->pageMetaTitle . ' | '. Yii::t('transactional_emails', 'View transactional emails'),
            'pageHeading'       => Yii::t('transactional_emails', 'View transactional emails'),
            'pageBreadcrumbs'   => array(
                Yii::t('transactional_emails', 'Transactional emails') => $this->createUrl('transactional_emails/index'),
                Yii::t('app', 'View all')
            )
        ));
        
        $this->render('list', compact('email'));
    }

    public function actionPreview($id)
    {
        $request = Yii::app()->request;
        $email   = TransactionalEmail::model()->findByPk((int)$id);
        
        if (empty($email)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }

        $this->renderPartial('preview', compact('email'), false, true);
    }
    
    /**
     * Delete existing email
     * Warning, all data related to this email will also be deleted!
     */
    public function actionDelete($id)
    {
        $email = TransactionalEmail::model()->findByPk((int)$id);
        
        if (empty($email)) {
            throw new CHttpException(404, Yii::t('app', 'The requested page does not exist.'));
        }
        
        $email->delete();
 
        $request = Yii::app()->request;
        $notify  = Yii::app()->notify;
        
        if (!$request->getQuery('ajax')) {
            $notify->addSuccess(Yii::t('app', 'The item has been successfully deleted!'));
            $this->redirect($request->getPost('returnUrl', array('transactional_emails/index')));
        }
    }
}