<?php

namespace frontend\controllers;

use Yii;
//use yii\web\Controller;
//use yii\web\NotFoundHttpException;
//use yii\filters\VerbFilter;
//use yii\db\Query;
//use yii\data\ActiveDataProvider;
use yii\filters\AccessControl;
use yii\web\ForbiddenHttpException;
use yii\db\Expression;
use yii\helpers\Html;
use yii\helpers\ArrayHelper;

use common\models\User;
use common\models\Condo;
use common\models\CondoUnit;
use common\models\CondoUnitSearch;


class MailchimpController extends BaseController {

    public $enableCsrfValidation = false;

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['index', 'csvemail', 'mailchimp','bulk'],
                'rules' => [
                    [
                        'actions' => ['index', 'csvemail', 'mailchimp','bulk'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }
    
    public function beforeAction($action) {
        $session = Yii::$app->session;
        if (parent::beforeAction($action)) {
            if (in_array($action->id, array('index', 'csvemail', 'mailchimp','bulk'))) {
                if (!(($session['currentRole'] == Yii::$app->params['role.name.default.management']) || ($session['currentRole'] == Yii::$app->params['role.name.administrator']) || ($session['currentRole'] == Yii::$app->params['role.name.support']))) {
                    throw new ForbiddenHttpException('You are trying to access restricted area.', 403);
                }
            }
            return true;
        }else {
            return false;
        }
    }
    
    public function actionIndex() {
        $session = Yii::$app->session;
        $model = new \frontend\models\MailchimpSynForm();
        if (Yii::$app->request->isPost) {
            $model->load(Yii::$app->request->post());
            //echo $model->condoname;
            //print_r($model->condoname);
            if (isset ($model->status)){
                $liststatus = array_values($model->status);
                if (in_array('cactive', $liststatus) && in_array('nonactive', $liststatus)) {
                    $status = 'user.date_last_login IS NULL OR user.date_last_login IS NOT NULL';
                } else if (in_array('cactive', $liststatus)) {
                    $status = 'user.date_last_login IS NULL';
                } else if (in_array('nonactive', $liststatus)) {
                    $status = 'user.date_last_login IS NOT NULL';
                }
            }else{
                $status = '';
            }
            $list_id = $model->list_id;

            $fromdate = $model->date_from;
            $date_from = date('Y-m-d', strtotime($fromdate)).' 00:00:00';
            $date_to = date('Y-m-d').' 23:59:59';

            if(!empty($date_from) && !empty($date_to)){
                //$mydaterange = ' AND user.created_datetime BETWEEN '.$date_from.' AND '.$date_to;
                $mydaterange = "AND user.updated_datetime BETWEEN '$date_from' AND '$date_to'";
            }else{
               $mydaterange = ''; 
            }
            
            $mc = \Yii::$app->mailchimp;
            $mstatus = 'subscribed';
            $_params = array("id" => $list_id, "status" => $mstatus);
            $result = $mc->call('lists/members', $_params);
            $removeemails = '';
            
            if(!empty($result)){
                $out = '';
                $arr1 = $result['data'];
                $countemails = count($arr1);
                foreach ($arr1 as $key => $value){
                    //$out .= array_merge(array($value['email']));
                    //print_r($value['email']);
                    $out .= '"'.$value['email'].'",';
                }
                $apiemaillist = rtrim($out,',');
                /*$apiemaillist = $out;
                echo '<pre>';
                print_r($apiemaillist);
                die();*/
                if($countemails > 0){
                    $removeemails = 'AND user.email NOT IN ('.$apiemaillist.')';
                }
                
            }

            $connection = \Yii::$app->db;
            $sql = 'SELECT condo.id, condo.name, condo.url, user.id, user.username, user.email, user.updated_datetime, user_condo_unit.condo_id, user_condo_unit.residence_type, condo_unit.house_no
                    FROM condo, user, user_condo_unit, condo_unit
                    WHERE user.id = user_condo_unit.user_id
                    AND user_condo_unit.condo_unit_id = condo_unit.id
                    AND (user.email >  "")
                    '.$removeemails.'                    
                    AND ('.$status.')'.$mydaterange.' GROUP BY user_condo_unit.user_id ORDER BY user_condo_unit.id DESC';

            $model = $connection->createCommand($sql);
            $query = $model->queryAll();
            $jobTitleList = ArrayHelper::toArray($query,'');

            return $this->render('mailchimp_view', [
                'query' => $jobTitleList,
                'list_id' => $list_id,
            ]);
            Yii::$app->end();
            
        }else{
            return $this->render('mailchimpform', [
                        'model' => $model
            ]);
        }
    }
    
    public function actionBulk1()
    {
        $list_id = '7c2715f339';
        $mc = \Yii::$app->mailchimp;
        $merge_vars = array('UNIQUEID' => "1234566", 'NAME' => "sssss", 'PNAME' => "wwwwwwwe", 'POSITION' => "Owner", 'URL' => "http://bistari.iresidenz.com");
        $email = "test@example.com";

        try {
            $result = $mc->call('lists/subscribe', array(
                    'id'                => $list_id,
                    'email'             => array('email'=>$email),
                    'merge_vars'        => $merge_vars,
                    'double_optin'      => false,
                    'update_existing'   => true,
                    'replace_interests' => false,
                    'send_welcome'      => false,
                ));
        } catch (\Mailchimp_Error $email) {
            if ($email->getMessage()) {
                $error = 'Code:' . $email->getCode() . ': ' . $email->getMessage();
            }
        }
        echo $error;
        die();
        if ($mc->success()) {
            print_r($result);   
        } else {
            echo $mc->getLastError();
        }

        //print_r($result);
    }
    
    public function actionBulk(){
        $action=Yii::$app->request->post('action');
        $selection=(array)Yii::$app->request->post('product');//typecasting
        $counter = count($_POST["product"]); 
        $list_id = $_POST["list_id"];
        $msg = '';
        
        foreach($selection as $key=>$id) {
            if(!empty($selection)){
                $uid = $_POST["uid"][$id];
                $name = $_POST["name"][$id];
                $url = $_POST["url"][$id];
                $username = $_POST["username"][$id];
                $email = $_POST["email"][$id];
                $house_no = $_POST["house_no"][$id];
                $stype = $_POST["stype"][$id];

                /*$data = "[" . $name . "] [" . $url . "] [" . preg_replace("/[^a-zA-Z0-9\s]/", "", $username) . "] [" . $email . "," . $house_no . "] [" . $stype . "]<br><br>";
                echo $data;*/
                $mc = \Yii::$app->mailchimp;
                $merge_vars = array('UNIQUEID' => $uid, 'NAME' => preg_replace("/[^a-zA-Z0-9\s]/", "", $username), 'PNAME' => $name, 'POSITION' => $stype, 'URL' => $url);
                $email = $email;

                try {
                    $result = $mc->call('lists/subscribe', array(
                        'id'                => $list_id,
                        'email'             => array('email'=>$email),
                        'merge_vars'        => $merge_vars,
                        'double_optin'      => false,
                        'update_existing'   => true,
                        'replace_interests' => false,
                        'send_welcome'      => false,
                    ));
                    if(!empty($result['leid'])){
                        $msg .= '<li class="list-group-item"><span class="badge pull-right bg-success"><i class="fa fa-check" aria-hidden="true"></i></span>  This email <b>('.$email.')</b> has been added to the list.</li>';
                    }else{
                        $msg .= '<li class="list-group-item"><span class="badge pull-right bg-warning"><i class="fa fa-thumbs-o-down" aria-hidden="true"></i></span>  This <b>('.$email.')</b> is not added to the list. Please try again.</li>';
                    }
                } catch (\Mailchimp_Error $email) {
                    if ($email->getMessage()) {
                        $error = $email.'-'.'Code:' . $email->getCode() . ': ' . $email->getMessage();
                        //$msg .= '<li class="list-group-item"><span class="badge pull-right bg-danger"><i class="fa fa-exclamation" aria-hidden="true"></i></span>'.$error.'</li>';
                        $msg .= '<li class="list-group-item"><span class="badge pull-right bg-warning"><i class="fa fa-thumbs-o-down" aria-hidden="true"></i></span>  This <b>('.$email.')</b> is not added to the list. Please try again.</li>';
                    }
                }
            } 
        }
        return $this->render('mailchimp_report', [
            'msg' => $msg,
        ]);
        
    }



    public function actionMailchimp() {
        $session = Yii::$app->session;
        $model = new \frontend\models\MailchimpSynForm();
        if (Yii::$app->request->isPost) {
            $model->load(Yii::$app->request->post());
            //echo $model->condoname;
            //print_r($model->condoname);
            if (isset ($model->status)){
                $liststatus = array_values($model->status);
                if (in_array('cactive', $liststatus) && in_array('nonactive', $liststatus)) {
                    $status = 'user.date_last_login IS NULL OR user.date_last_login IS NOT NULL';
                } else if (in_array('cactive', $liststatus)) {
                    $status = 'user.date_last_login IS NULL';
                } else if (in_array('nonactive', $liststatus)) {
                    $status = 'user.date_last_login IS NOT NULL';
                }
            }else{
                $status = '';
            }
            $list_id = $model->list_id;

            $fromdate = $model->date_from;
            $date_from = date('Y-m-d', strtotime($fromdate)).' 00:00:00';
            $date_to = date('Y-m-d').' 23:59:59';

            if(!empty($date_from) && !empty($date_to)){
                //$mydaterange = ' AND user.created_datetime BETWEEN '.$date_from.' AND '.$date_to;
                $mydaterange = "AND user.updated_datetime BETWEEN '$date_from' AND '$date_to'";
            }else{
               $mydaterange = ''; 
            }
            
            
            $searchModel = new CondoUnitSearch();
            //$searchModel->condo_id = $session['currentCondoId'];

            $dataProvider = $searchModel->searchlisting(Yii::$app->request->queryParams);

            $dataProvider->pagination->pageSize=50;
            return $this->render('mailchimp_view', [
                        'searchModel' => $searchModel,
                        'dataProvider' => $dataProvider,
            ]);
            die();
            $n = 1;
                      
            $mc = \Yii::$app->mailchimp;
            $list_id = '4983f9dca0';
            $email = 'shihan1@yahoo.com';

            //$_params = array("id" => $id, "status" => $status, "opts" => $opts);
            //$_params = array("id" => $list_id, "emails" => array($emails));
            $result = $mc->call('lists/member-info', array(
            'id'        => $list_id,
            'emails'    => array(array('email'=>$email))
          ));
            //echo $result['success_count'];
            //echo $result['error_count'];
            echo '<pre>';
            //echo $result
            print_r($result);
            //$subscripbe = $result['data'][0];
            //echo $subscripbe['status'];
            die();
            
            //$list_id = '4983f9dca0';
            if(count($query) > 0){
                foreach ($query as $value) {
                    if ($value['residence_type'] == 'O') {
                        $stype = 'Owner';
                    } elseif ($value['residence_type'] == 'T') {
                        $stype = 'Tenant';
                    }
                    $merge_vars = array('FNAME' => $value['name'], 'LNAME' => $value['url']);
                    $email = $value['email'];
                    $email = 'shmshihan@yahoo.com';
                    $result = $mc->call('lists/subscribe', array(
                        'id'                => $list_id,
                        'email'             => array('email'=>$email),
                        'merge_vars'        => $merge_vars,
                        'double_optin'      => false,
                        'update_existing'   => true,
                        'replace_interests' => false,
                        'send_welcome'      => false,
                    ));
                    if(!empty($result['leid'])){
                       echo "success<br>";
                    }else{
                       echo "fail<br>";
                    }
                }
                //echo $email.'<br>';
                
                //$data .= $n . "-" . $value['name'] . "," . $value['url'] . "," . $value['id'] . "," . preg_replace("/[^a-zA-Z0-9\s]/", "", $value['username']) . "," . $value['email'] . "," . $value['house_no'] . "," . $stype . "\r\n";
            }
            Yii::$app->end();
        }else{
            return $this->render('mailchimpform', [
                        'model' => $model
            ]);
        }
    }

}
