<?php

class NewsletterController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = 'newsletter';

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
            'postOnly + delete', // we only allow deletion via POST request
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('index', 'view', 'create', 'update', 'admin', 'delete', 'ajaxupdate',
                    'updateProductGroup', 'updateProductCategory', 'sendmail','Sendemail', 'SenduserMail','updateProduct', 'newsletterTemp', 'automatedletter', 'log', 'Testgroup', 'test'
                ),
                'expression' => '$user->isAdmin()'
            ),
            array('allow',
                'actions' => array('newsletterTemp', 'NewsletterCron', 'unsubscription', 'test'),
                'users' => array('*'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
        $this->render('view', array(
            'model' => $this->loadModel($id),
        ));
    }

    public function actionSendmail($id) {        
        $model = $this->loadModel($id);
        $mailContent = array();
        $mailContent['title'] = $model->title;
        $mailContent['news_letter_body'] = $model->news_letter_body;

        $message = new YiiMailMessage;
        $message->view = 'newsLetter';

        $message->setBody(array('mailContent' => $mailContent), 'text/html');
        $message->subject = 'Message from administartor ' . $model->title;

        $message->from = 'noreply@me.dlink.com';//Yii::app()->params['adminEmail'];
        $message->addTo(Yii::app()->params['adminEmail']);
        $allUsers = ($_GET['to'] == 'all') ? (User::getAllusers()) : (User::getAllusers(2)); //send to all members
        //$count1 = User::model()->count(array('condition' => 'isActive="Y"'));
        //$count = intval($count1 / 5);
        //$offset = $count;
        //$limit0 = 0;
        // $limit1 = $count + 1;
        //$limit2 = (2 * $count) + 2;
        //$limit3 = (3 * $count) + 3;
        //$limit4 = (4 * $count) + 4;
        //$us=User::model()->findAll(array('condition'=>'isActive="Y"','limit'=>$offset,'offset'=>$limit3));
        //foreach($us as $eachus)
        //{
        //  print_r($eachus);die();
        //}
        // print_r($us);die("rrrrr"); 

        foreach ($allUsers as $row)
            $message->addBcc($row->company_email_address);
        Yii::app()->user->setFlash('success', 'Message sent');
        Yii::app()->mail->send($message);
        $this->redirect(array('index'));
    }
     public function actionSendemail($id,$to=null) {     
        $model = $this->loadModel($id);
        $mailContent = array();
        $mailContent['title'] = $model->title;
        $mailContent['news_letter_body'] = $model->news_letter_body;

        $message = new YiiMailMessage;
        $message->view = 'newsLetter';

        $message->setBody(array('mailContent' => $mailContent), 'text/html');
        $message->subject = 'Message from administartor ' . $model->title;

        $message->from = 'noreply@me.dlink.com';//Yii::app()->params['adminEmail'];
        $message->addTo(Yii::app()->params['adminEmail']);
        $allUsers = ($type == 'all') ? (User::getAllusers()) : (User::getAllusers(2)); //send to all members
        foreach ($allUsers as $row)
            $message->addBcc($row->company_email_address);   
        Yii::app()->user->setFlash('success', 'Message sent');
        Yii::app()->mail->send($message);
        $this->redirect(array('index'));
    }

    public function actionNewsletterTemp() {
        // $caseStudies = Paper::model()->findAll(array('condition' => 'isActive="Y"', 'limit' => 4, 'order' => 'id DESC'));
        // $newProducts = Product::model()->findAll(array('condition' => 'isActive="Y"', 'limit' => 10, 'order' => 'id DESC'));
        $caseStudies = Paper::model()->findAll(array('condition' => 'isActive="Y"', 'limit' => 3, 'order' => 'id DESC'));
        $newProducts = Product::model()->findAll(array('condition' => 'isActive="Y"', 'limit' => 6, 'order' => 'id DESC'));
        $this->renderPartial('newsletter_template', array('model' => $caseStudies, 'newProducts' => $newProducts));
    }

    /* public function actionTest() {
      $mailContent = array();
      $mailContent['title'] = "Test";
      $mailContent['news_letter_body'] = "test body";

      $message = new YiiMailMessage;
      $message->view = 'newsLetter';

      $message->setBody(array('mailContent' => $mailContent), 'text/html');
      $message->subject = 'D-Link Partner Newsletter';

      $message->from = Yii::app()->params['adminEmail'];
      //setFrom(array('john@doe.com' => 'John Doe'))
      $message->addTo("arun.kumar@mailbluesky.com");

      Yii::app()->mail->send($message);
      } */

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate() {
        $model = new Newsletter;
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST) > 0 && isset($_POST['Newsletter'])){
            $model->attributes = $_POST['Newsletter'];
            if ($model->save()) {
                Yii::app()->user->setFlash('success', 'Message saved.');
                if (isset($_POST['yt0']) || isset($_POST['yt1']) || isset($_POST['yt2'])) {
                    $mailContent = array();
                    $mailContent['title'] = $model->title;
                    $mailContent['news_letter_body'] = $model->news_letter_body;

                    $message = new YiiMailMessage;
                    $message->view = 'newsLetter';

                    $message->setBody(array('mailContent' => $mailContent), 'text/html');
                    $message->subject = 'D-Link Partner Newsletter';

                    $message->from = 'noreply@me.dlink.com';//Yii::app()->params['adminEmail'];
                    $message->addTo(Yii::app()->params['adminEmail']);
                    if (!isset($_POST['yt2'])) {
                        $allUsers = (isset($_POST['yt0'])) ? (User::getAllusers()) : User::getAllusers(2); //send to all members
                        foreach ($allUsers as $row)
                            $message->addBcc($row->company_email_address);
                        Yii::app()->user->setFlash('success', 'Message saved and sent to members .');
                    } else {
                        $message->subject = 'D-Link Partner Newsletter:Test message';
                        $testers = explode(',', TestGroup::model()->findbyPK(1)->email_id);
                        foreach ($testers as $eachTester) {
                            $message->addBcc(trim($eachTester));
                        }
                        Yii::app()->user->setFlash('success', 'Msg test ok .');
                    }
                    Yii::app()->mail->send($message);
                }
            }
            $this->redirect(array('index'));
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }

    public function actionTestgroup() {
        $modelTest = TestGroup::model()->findByPK(1);
        if (isset($_POST['TestGroup'])) {
            $modelTest->attributes = $_POST['TestGroup'];
            $modelTest->save();
        }

        $this->render('testgroup', array(
            'model' => $modelTest,
        ));
    }

    public function actionAutomatedletter() {
        // $model = NewsletterAutomodel::model()->find(array('order' => 'id desc'));
        $model = NewsletterAutomodel::model()->find(array('condition' => 'isActive="Y"'));
        if (count($model) == 0) {
            $model = new NewsletterAutomodel;
            $model->content = file_get_contents(Yii::app()->createAbsoluteUrl('newsletter/newsletterTemp'));
        }
        if (isset($_POST['NewsletterAutomodel'])) {
            if (isset($_POST['yt0'])) {
                $model->attributes = $_POST['NewsletterAutomodel'];
                $model->created_date = date('Y-m-d');
                if ($model->save()) {
                    Yii::app()->user->setFlash('success', 'Message saved.');
                    $this->redirect(array('automatedletter'));
                }
            } else if (isset($_POST['yt1'])) {
                $model->isActive = ($_POST['yt1'] == "Stop") ? "N" : "Y";
                $model->save(false);
            } else if (isset($_POST['yt2'])) {
                $model->attributes = $_POST['NewsletterAutomodel'];
                $mailContent = array();
                $mailContent['title'] = "test";
                $mailContent['news_letter_body'] = $model->content;

                $message = new YiiMailMessage;
                $message->view = 'newsLetter';

                $message->setBody(array('mailContent' => $mailContent), 'text/html');
                $message->from = 'noreply@me.dlink.com';//Yii::app()->params['adminEmail'];
                $message->subject = 'D-Link Automated NewsLetter Testing';
                $testers = explode(',', TestGroup::model()->findbyPK(1)->email_id);
                foreach ($testers as $eachTester) {
                    $message->addBcc(trim($eachTester));
                }
                Yii::app()->user->setFlash('success', 'Msg test ok .');
                Yii::app()->mail->send($message);
            }
        }
        $this->render('automodelnewsletter', array(
            'model' => $model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {

        $model = $this->loadModel($id);

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

       $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST) > 0 && isset($_POST['Newsletter'])){
            ini_set("memory_limit", "128G");
            ini_set('max_execution_time', 10000);
            $model->attributes = $_POST['Newsletter'];
            if ($model->save()) {
                Yii::app()->user->setFlash('success', 'Message updated');
                if (isset($_POST['yt0']) || isset($_POST['yt1']) || isset($_POST['yt2'])) {
                    $mailContent = array();
                    $mailContent['title'] = $model->title;
                    $mailContent['news_letter_body'] = $model->news_letter_body;
                    $message = new YiiMailMessage;
                    $message->view = 'newsLetter';
                    $message->setBody(array('mailContent' => $mailContent), 'text/html');
                    $message->subject = 'D-Link Partner Newsletter';
                    //$message->from	=	Yii::app()->params['adminEmail'];
                    //$message->from	=	Yii::app()->params['adminEmail'];					
                    //$message->from = "Dlink-Portal@me.dlink.com";
                    $message->from = 'noreply@me.dlink.com';//Yii::app()->params['adminEmail'];
                    $message->addTo(Yii::app()->params['adminEmail']);
                    if (!isset($_POST['yt2'])) {
                        $siteMembers = (isset($_POST['yt0'])) ? (User::getAllusers()) : (User::getAllusers(2)); //send to all members //send to all staff
                        foreach ($siteMembers as $row)
                            $message->addBcc($row->company_email_address);
                        Yii::app()->user->setFlash('success', 'Message updated and sent to members .');
                    } else {
                        $message->subject = 'D-Link Partner Newsletter:Test message';
                        $testers = explode(',', TestGroup::model()->findbyPK(1)->email_id);
                        foreach ($testers as $eachTester) {
                            $message->addBcc(trim($eachTester));
                        }
                        Yii::app()->user->setFlash('success', 'Message updated and sent to Test Group .');
                    }
                    /* $message->addBcc("arun.kumar@mailbluesky.com");
                      $message->addTo("dabi@mailbluesky.com"); */

                    Yii::app()->mail->send($message);
                }
                $this->redirect(array('index'));
            }
        }

        $this->render('update', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'admin' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
        $this->loadModel($id)->delete();

        // if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
        if (!isset($_GET['ajax']))
            $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
    }

    /**
     * Manages all models.
     */
    public function actionIndex() {
        $model = new Newsletter('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Newsletter']))
            $model->attributes = $_GET['Newsletter'];

        $this->render('admin', array(
            'model' => $model,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
        $model = Newsletter::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'newsletter-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    public function SendMail($model, $type = null) {      
     $allUsers = User::getAllusers($type);
        $emailIds = array();
        foreach ($allUsers as $i => $row) {
            if (count(Unsubsription::model()->find(array('condition' => 'email="' . $row->company_email_address . '" AND unsub="Y"'))) == 0) {
                $emailIds[] = $row->company_email_address;
            }
        }
        $date1 = date('Y-m-d');
        $sql = "insert into {{_newsletter_log}} (email_id,date1,status) values ";
        $vals = '';
        foreach ($emailIds as $i => $each_id) {
            //print_r($emailIds);
            $message = new YiiMailMessage;
            $message->view = 'subscription_newsletter';
            $mailContent = array();
            $mailContent['news_letter_body'] = $model->content;
            $mailContent['email'] = $each_id;
            $message->setBody(array('mailContent' => $mailContent), 'text/html');
            $message->subject = 'D-Link Partner Newsletter';
            //$message->from	=	Yii::app()->params['adminEmail'];
            //$message->from = "Dlink_Portal@me.dlink.com";
            $message->from = 'noreply@me.dlink.com';//Yii::app()->params['adminEmail'];
            $message->addTo($each_id);
            if (Yii::app()->mail->send($message)) {
                $status = "Success";
                $vals .=($vals == '') ? "('" . $each_id . "','" . $date1 . "','" . $status . "')" : ",('" . $each_id . "','" . $date1 . "','" . $status . "')";
                echo ($i + 1) . $each_id . " ok <br/>";
            } else {
                $status = "Fail";
                $vals .=($vals == '') ? "('" . $each_id . "','" . $date1 . "','" . $status . "')" : ",('" . $each_id . "','" . $date1 . "','" . $status . "')";
            }
            if ((($i + 1) % 200) == 0)
                sleep(3600);
        }
        $sql .= $vals;
        //echo $sql;
        Yii::app()->db->createCommand($sql)->execute();
    }

    public function actionNewsletterCron() {
        switch (date('d')) {
            case 1:
            case 15:
                $model = new NewsletterAutomodel;
                $content = file_get_contents(Yii::app()->createAbsoluteUrl('newsletter/newsletterTemp'));
                if (count(NewsletterAutomodel::model()->findAll(array())) == 0) {
                    $model->content = $content;
                    $model->save(false);
                } else {
                    $model->updateAll(array('content' => $content));
                }
                break;
            case 3:
            case 18:
                //send a mail to admin
                $model = NewsletterAutomodel::model()->find(array('condition' => 'isActive="Y"'));
                if (count($model) > 0)
                    $this->sendMails($model, 3);
                break;
            case 5:
            case 20:
                //mail send to all members
                $model = NewsletterAutomodel::model()->find(array('condition' => 'isActive="Y"'));
                //echo "count:".count($model);
                if (count($model) > 0)
                    $this->sendMail($model);
                break;
        }
    }

    public function actionUnsubscription($email) {
        $model = new Unsubsription;
        $model->email = $email;
        $model->save(false);
        echo "Unsubscribed";
    }

    public function actionLog() {
        $model = new NewsletterLog('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['NewsletterLog']))
            $model->attributes = $_GET['NewsletterLog'];

        $this->render('log', array(
            'model' => $model,
        ));
    }

}
