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

/**
 * Campaign_reports_export
 * 
 * Handles the actions for exporting campaign reports
 * 
 * @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.2
 */
 
class Campaign_reports_exportController extends Controller
{

    public function actionBasic($campaign_uid)
    {
        $campaign   = $this->loadCampaignModel($campaign_uid);
        $request    = Yii::app()->request;
        $notify     = Yii::app()->notify;
        $redirect   = array('campaigns/overview', 'campaign_uid' => $campaign->campaign_uid);
        
        $campaign->attachBehavior('stats', array(
            'class' => 'customer.components.behaviors.CampaignStatsProcessorBehavior',
        ));
        
        $tempDir = FileSystemHelper::getTmpDirectory();
        if (!file_exists($tempDir) || !is_dir($tempDir)) {
            $notify->addError(Yii::t('campaign_reports', 'Cannot create export temporary directory!'));
            $this->redirect($redirect);
        }
        
        @touch($tempFile = $tempDir . '/basic-stats-' . $campaign->campaign_uid . '-' . date('Y-m-d-h-i-s') . '.csv');
        if (!is_file($tempFile)) {
            $notify->addError(Yii::t('campaign_reports', 'Cannot create export temporary file!'));
            $this->redirect($redirect);
        }
        
        if (!($fp = @fopen($tempFile, 'w'))) {
            $notify->addError(Yii::t('campaign_reports', 'Cannot open export temporary file!'));
            $this->redirect($redirect);
        }
        
        $csvData = array();
        $csvData[] = array(Yii::t('campaign_reports', 'Processed'), $campaign->stats->getProcessedCount(true));
        $csvData[] = array(Yii::t('campaign_reports', 'Delivery success'), $campaign->stats->getDeliverySuccessCount(true));
        $csvData[] = array(Yii::t('campaign_reports', 'Delivery success rate'), $campaign->stats->getDeliverySuccessRate(true) . '%');
        $csvData[] = array(Yii::t('campaign_reports', 'Delivery error'), $campaign->stats->getDeliveryErrorCount(true));
        $csvData[] = array(Yii::t('campaign_reports', 'Delivery error rate'), $campaign->stats->getDeliveryErrorRate(true) . '%');
        $csvData[] = array(Yii::t('campaign_reports', 'Unique opens'), $campaign->stats->getUniqueOpensCount(true));
        $csvData[] = array(Yii::t('campaign_reports', 'Unique open rate'), $campaign->stats->getUniqueOpensRate(true) . '%');
        $csvData[] = array(Yii::t('campaign_reports', 'All opens'), $campaign->stats->getOpensCount(true));
        $csvData[] = array(Yii::t('campaign_reports', 'All opens rate'), $campaign->stats->getOpensRate(true) . '%');
        $csvData[] = array(Yii::t('campaign_reports', 'Bounced back'), $campaign->stats->getBouncesCount(true));
        $csvData[] = array(Yii::t('campaign_reports', 'Bounce rate'), $campaign->stats->getBouncesRate(true) . '%');
        $csvData[] = array(Yii::t('campaign_reports', 'Hard bounce'), $campaign->stats->getHardBouncesCount(true));
        $csvData[] = array(Yii::t('campaign_reports', 'Hard bounce rate'), $campaign->stats->getHardBouncesRate(true) . '%');
        $csvData[] = array(Yii::t('campaign_reports', 'Soft bounce'), $campaign->stats->getSoftBouncesCount(true) . '%');
        $csvData[] = array(Yii::t('campaign_reports', 'Soft bounce rate'), $campaign->stats->getSoftBouncesRate(true) . '%');
        $csvData[] = array(Yii::t('campaign_reports', 'Unsubscribe'), $campaign->stats->getUnsubscribesCount(true));
        $csvData[] = array(Yii::t('campaign_reports', 'Unsubscribe rate'), $campaign->stats->getUnsubscribesRate(true) . '%');
        
        if ($campaign->option->url_tracking == CampaignOption::TEXT_YES) {
            $csvData[] = array(Yii::t('campaign_reports', 'Total urls for tracking'), $campaign->stats->getTrackingUrlsCount(true));
            $csvData[] = array(Yii::t('campaign_reports', 'Unique clicks'), $campaign->stats->getUniqueClicksCount(true));
            $csvData[] = array(Yii::t('campaign_reports', 'Unique clicks rate'), $campaign->stats->getUniqueClicksRate(true) . '%');
            $csvData[] = array(Yii::t('campaign_reports', 'All clicks'), $campaign->stats->getClicksCount(true));
            $csvData[] = array(Yii::t('campaign_reports', 'All clicks rate'), $campaign->stats->getClicksRate(true) . '%');
        }
        
        foreach ($csvData as $row) {
            fputcsv($fp, $row, ',', '"');  
        }
        
        fclose($fp);
        
        if (!($fp = @fopen($tempFile, "rb"))) {
            $notify->addError(Yii::t('campaign_reports', 'Cannot open export temporary file!'));
            $this->redirect($redirect);
        }
        
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header('Content-type: application/csv');
        header("Content-Transfer-Encoding: Binary");
        header('Content-Disposition: attachment; filename="'.basename($tempFile).'"');
        header("Content-Length: ".filesize($tempFile)); 
        
        while(!feof($fp)) {
            echo fread($fp, 8192);
            flush();
            if (connection_status() != 0) {
                @fclose($fp);
                @unlink($tempFile);
                die();
            }
        }
        @fclose($fp);
        @unlink($tempFile);
    }

    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;
    }

}