<?php

namespace frontend\controllers;

use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\Cinema;
use common\models\Programmazione;
use common\models\Sala;
use common\models\Film;
use common\models\Log;
use common\models\Voucher;
use frontend\extensions\VoucherPrime;
use frontend\extensions\Utils;
use frontend\extensions\EngInterface;

/**
 * Site controller
 */
class SiteController extends Controller {

    public static $endDate = "2016-12-23 23:59:59";

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup', 'confirmdati', 'confirmvoucher'],
                'rules' => [
                        [
                        'actions' => ['signup', 'terminato'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                        [
                        'actions' => ['logout', 'confirmdati', 'confirmvoucher'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
//                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function beforeAction($action) {
        $this->enableCsrfValidation = false;

        \Yii::$app->view->registerMetaTag([
            'name' => 'description',
            'content' => 'Con TIM Cinema vai al cinema in 2 al prezzo di 1 solo biglietto. Condividi le emozioni del grande schermo con chi vuoi tu in più di 900 sale in tutta Italia!'
        ]);
        \Yii::$app->view->registerMetaTag([
            'property' => 'og:description',
            'content' => 'Con TIM Cinema vai al cinema in 2 al prezzo di 1 solo biglietto. Condividi le emozioni del grande schermo con chi vuoi tu in più di 900 sale in tutta Italia!'
        ]);


        // if (time() > strtotime(self::$endDate)) {
            if ($action->id != 'terminato' && $action->id != 'error') {
                return $this->redirect(['terminato']);
            }
        // }

        return parent::beforeAction($action);
    }

    /**
     * @inheritdoc
     */
    public function actions() {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    public function actionTerminato() {
        // if (time() < strtotime(self::$endDate)) {
        //     return $this->redirect(['index']);
        // }

        return $this->render('terminato');
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex() {

        return $this->redirect(['terminato']);
        
        $cinema = Cinema::find()->where(['visibile' => 1])->all();

        $regioniQuery = (new \yii\db\Query())
                ->select(['regione'])
                ->distinct()
                ->from('cinema')
                ->orderBy('regione')
                ->all();

        $regioni = \yii\helpers\ArrayHelper::map($regioniQuery, "regione", "regione");

        $citta = Yii::$app->request->get("citta");
        $regione = Yii::$app->request->get("regione");
        $provincia = Yii::$app->request->get("provincia");

        $province = array();
        $cities = array();

        $lastCinema = Voucher::find()->where(['utente' => Yii::$app->user->id, 'valido' => 1])->orderBy('data_creazione DESC')->one();
        if ($lastCinema != NULL && $lastCinema->cinema0->visibile == 0) {
            $lastCinema = NULL;
        }

        if ($lastCinema != NULL && !Yii::$app->request->isAjax) {

            $regione = $lastCinema->cinema0->regione;
            $provincia = $lastCinema->cinema0->provincia;
            $citta = $lastCinema->cinema0->citta;

            $provs = (new \yii\db\Query())
                    ->select(['provincia'])
                    ->distinct()
                    ->from('cinema')
                    ->where(['regione' => $regione, 'visibile' => 1])
                    ->orderBy('provincia')
                    ->all();

            foreach ($provs as $p) {
                $province[$p['provincia']] = $p['provincia'];
            }

            $cts = (new \yii\db\Query())
                    ->select(['citta'])
                    ->distinct()
                    ->from('cinema')
                    ->where(['provincia' => $provincia, 'visibile' => 1])
                    ->orderBy('citta')
                    ->all();

            foreach ($cts as $c) {
                $cities[$c['citta']] = $c['citta'];
            }
        }

        if ($citta != NULL && $citta != "") {
            $cinemaDataProvider = Cinema::searchForCity($citta);
        } else if ($provincia != NULL && $provincia != "") {
            $cinemaDataProvider = Cinema::searchForProvincia($provincia);
        } else if ($regione != NULL && $regione != "") {
            $cinemaDataProvider = Cinema::searchForRegione($regione);
        } else {
            $cinemaDataProvider = new \yii\data\ArrayDataProvider(array());
        }

        $films = Film::find()->where(['>', 'codice', 0])->all();


        return $this->render('index', ['cinema' => $cinema, 'regioni' => $regioni, 'cinemaDataProvider' => $cinemaDataProvider, 'films' => $films, 'province' => $province, 'cities' => $cities, 'lastCinema' => ($lastCinema != NULL) ? $lastCinema->cinema0 : NULL]);
    }

    public function actionConfirmdati() {
        $cinema = Yii::$app->request->post('c');
        $data = Yii::$app->request->post('d');

        $nomeSpettatore = Yii::$app->request->post("nome");
        $cognomeSpettatore = Yii::$app->request->post("cognome");

        $cinemaModel = Cinema::findOne(['id' => $cinema]);

        return $this->renderPartial('_confirm', ['cinema' => $cinemaModel, 'data_scelta' => $data, 'nome' => $nomeSpettatore, 'cognome' => $cognomeSpettatore]);
    }

    public function actionConfirmvoucher() {
        $cinema = Yii::$app->request->post('c');
        $data = Yii::$app->request->post('d');

        $nomeSpettatore = Yii::$app->request->post("nome");
        $cognomeSpettatore = Yii::$app->request->post("cognome");

        $cinemaModel = Cinema::findOne(['id' => $cinema]);

        list($day, $month, $year) = explode("/", $data);
        $data_voucher = $year . '-' . $month . '-' . $day;

        $voucherWeek = Voucher::find()->where(['utente' => Yii::$app->user->identity->msisdn, 'valido' => 1])->exists();

        $festivi = Utils::getFestivi($year);
        if (Utils::isFestivo($festivi, $day, $month, $year)) {
            $voucherWeek = true;
        }

        if ($voucherWeek) {
            echo "ERROR";
            exit;
        } else {
            $voucher = new Voucher;
            $voucher->utente = Yii::$app->user->identity->msisdn;
            $voucher->cinema = $cinema;
            $voucher->nome = $nomeSpettatore;
            $voucher->cognome = $cognomeSpettatore;
            $voucher->email = NULL;
            $voucher->data_voucher = $data_voucher;
            $voucher->data_creazione = date("Y-m-d H:i:s");
            $voucher->valido = 1;

            $detect = new \frontend\extensions\Mobile_Detect;
            $voucher->device = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
            $voucher->useragent = $detect->getUserAgent();

            $voucher->save();

            $codice = $voucher->generateCodice();
            $voucher->codice = $codice;
            $voucher->save();

            VoucherPrime::generatePDF($voucher->nome, $voucher->cognome, $cinemaModel->nome . ' - ' . $cinemaModel->citta, $cinemaModel->indirizzo, $data, $voucher->codice);

            $log = array_merge($voucher->attributes, array('cinema' => $cinemaModel->nome . ' - ' . $cinemaModel->citta . ' - ' . $cinemaModel->indirizzo));
            Log::log(Yii::$app->user->identity->msisdn, 'ConfirmVoucher', $log);

            return $this->renderPartial('_confirmed', ['voucher' => $voucher, 'cinema' => $cinemaModel]);
        }
    }

    public function actionTestws() {

        $ip_client1 = array_values(array_filter(explode(',', self::get_client_ip())));
        $ip = $ip_client1[0];

        $port = $_SERVER['REMOTE_PORT'];

        $res = EngInterface::ip2msisdn($ip, $port);

        var_dump($res);
        exit;
//         $res = EngInterface::moo('338/17.36.334');
//        $res = EngInterface::customerProfile('3776813158');
        // $res = EngInterface::sendOTP('338/17.36.334');
    }

    // public function actionGeneratecustomvoucher() {
    //     if (Yii::$app->user->isGuest) {
    //         echo "Invalid Action";
    //         exit;
    //     }
    //     if (Yii::$app->user->identity->msisdn != '3384024373') {
    //         echo "Invalid User";
    //         exit;
    //     }
    //     $msisdn = '3292970268';
    //     $cinema = 273;
    //     $data_voucher = '2016-06-07';
    //     $user = \common\models\Utente::findIdentity($msisdn);
    //     $cinemaModel = Cinema::findOne(['id' => $cinema]);
    //     if (!$user || !$cinemaModel) {
    //         echo "Invalid Params";
    //         exit;
    //     }
    //     $voucher = new Voucher;
    //     $voucher->utente = $msisdn;
    //     $voucher->cinema = $cinema;
    //     $voucher->nome = $user->nome;
    //     $voucher->cognome = $user->cognome;
    //     $voucher->email = $user->email;
    //     $voucher->data_voucher = $data_voucher;
    //     $voucher->data_creazione = date("Y-m-d H:i:s");
    //     $voucher->valido = 1;
    //     $detect = new \frontend\extensions\Mobile_Detect;
    //     $voucher->device = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
    //     $voucher->useragent = $detect->getUserAgent();
    //     $voucher->save();
    //     $codice = $voucher->generateCodice();
    //     $voucher->codice = $codice;
    //     $voucher->save();
    //     VoucherPrime::generatePDF($voucher->nome, $voucher->cognome, $cinemaModel->nome . ' - ' . $cinemaModel->citta, $cinemaModel->indirizzo, $data_voucher, $voucher->codice);
    //     $log = array_merge($voucher->attributes, array('cinema' => $cinemaModel->nome . ' - ' . $cinemaModel->citta . ' - ' . $cinemaModel->indirizzo));
    //     Log::log($user->msisdn, 'Generatecustomvoucher', $log);
    //     echo "OK";
    //     exit;
    // }
    public function actionTestvoucher() {
        // \app\extensions\Mailer::inviaBigliettoAltraMail(Voucher::findOne(157), 'a.dagostino@adinfosolution.it');
        // \app\extensions\Mailer::inviaBigliettoAltraMail(Voucher::findOne(157), 'a.ercole@armosia.com');
        // \app\extensions\Mailer::inviaBigliettoAltraMail(Voucher::findOne(157), 'annalisaercole@yahoo.it');
        $cinema = 5;
        $data = date("d/m/Y");
        $cinemaModel = Cinema::findOne(['id' => $cinema]);
        list($day, $month, $year) = explode("/", $data);
        $data_voucher = $year . '-' . $month . '-' . $day;
        $voucher = new Voucher;
        $voucher->utente = "123456789"; // TODO MSISDN
        $voucher->cinema = $cinema;
        $voucher->nome = "test";
        $voucher->cognome = "test";
        $voucher->email = "email-test@test.it";
        $voucher->data_voucher = $data_voucher;
        $voucher->data_creazione = date("Y-m-d H:i:s");
        $voucher->valido = 1;
        // $voucher->save();
        // // $voucher->codice = $voucher->generateCodice();
        $voucher->codice = '123AAAAAAAAA';
        // // $voucher->save();
        // $cinemaModel->nome = 'Movie Planet Centro Commerciale San Giuliano';
        VoucherPrime::generatePDF($voucher->nome, $voucher->cognome, $cinemaModel->nome . ' - ' . $cinemaModel->citta, $cinemaModel->indirizzo, $data, $voucher->codice);
        echo "FATTO! " . $voucher->codice;
        exit;
    }

    public function actionLoadprovince() {
        $regione = Yii::$app->request->post('regione');

        $province = (new \yii\db\Query())
                ->select(['provincia'])
                ->distinct()
                ->from('cinema')
                ->where(['regione' => $regione, 'visibile' => 1])
                ->orderBy('provincia')
                ->all();

        echo "<option value=''>PROVINCIA</option>";
        foreach ($province as $p) {
            echo '<option value="' . $p['provincia'] . '">' . $p['provincia'] . '</option>';
        }
    }

    public function actionLoadcitta() {
        $provincia = Yii::$app->request->post('provincia');

        $citta = (new \yii\db\Query())
                ->select(['citta'])
                ->distinct()
                ->from('cinema')
                ->where(['provincia' => $provincia, 'visibile' => 1])
                ->orderBy('citta')
                ->all();

        echo "<option value>CITTÀ</option>";
        foreach ($citta as $c) {
            echo '<option value="' . $c['citta'] . '">' . $c['citta'] . '</option>';
        }
    }

    public function actionVoucher() {
        $vouchers = Voucher::searchForUser(Yii::$app->user->id);

        return $this->render("voucher", ['vouchers' => $vouchers]);
    }

    public function actionStats() {
        $total = Voucher::find()->count();
        $valid = Voucher::find()->where(['valido' => 1])->count();

        echo $valid . '/' . $total . '<br/><br/>';


        // $today = date('Y-m-d');

        $range = self::createDateRangeArray('2016-12-14', date('Y-m-d'));
        array_reverse($range);

        foreach ($range as $date) {
            $from = $date . ' 00:00:00';
            $to = $date . ' 23:59:59';
            $vouchers[$date] = Yii::$app->getDb()->createCommand('SELECT DATE_FORMAT(data_creazione, "%Y-%m-%d") as data, COUNT(*) as tot 
                          FROM voucher WHERE data_creazione BETWEEN "' . $from . '" AND "' . $to . '" GROUP BY DATE_FORMAT(data_creazione, "%Y-%m-%d")')->queryAll();
            $vouchers_valid[$date] = Yii::$app->getDb()->createCommand('SELECT DATE_FORMAT(data_creazione, "%Y-%m-%d") as data, COUNT(*) as tot 
                          FROM voucher WHERE valido = 1 AND data_creazione BETWEEN "' . $from . '" AND "' . $to . '" GROUP BY DATE_FORMAT(data_creazione, "%Y-%m-%d")')->queryAll();
        }

        foreach ($range as $d) {
            // var_dump($vouchers); exit;
            // echo $d.'<br/>';

            if (!isset($vouchers[$d]) || empty($vouchers[$d]))
                $tot = '-';
            else {
                $tot = $vouchers[$d][0]['tot'];
            }

            if (!isset($vouchers_valid[$d]) || empty($vouchers_valid[$d]))
                $valid = '-';
            else {
                $valid = $vouchers_valid[$d][0]['tot'];
            }

            echo $d . ': ' . $valid . '/' . $tot . '<br/>';
        }

        exit;
    }

    public static function createDateRangeArray($strDateFrom, $strDateTo) {
        // takes two dates formatted as YYYY-MM-DD and creates an
        // inclusive array of the dates between the from and to dates.
        // could test validity of dates here but I'm already doing
        // that in the main script

        $aryRange = array();

        $iDateFrom = mktime(1, 0, 0, substr($strDateFrom, 5, 2), substr($strDateFrom, 8, 2), substr($strDateFrom, 0, 4));
        $iDateTo = mktime(1, 0, 0, substr($strDateTo, 5, 2), substr($strDateTo, 8, 2), substr($strDateTo, 0, 4));

        if ($iDateTo >= $iDateFrom) {
            array_push($aryRange, date('Y-m-d', $iDateFrom)); // first entry
            while ($iDateFrom < $iDateTo) {
                $iDateFrom += 86400; // add 24 hours
                array_push($aryRange, date('Y-m-d', $iDateFrom));
            }
        }
        return $aryRange;
    }

    public function actionAssistenza() {


        return $this->render("assistenza");
    }

    public function actionSalvavoucher($c) {
        $v = Voucher::findOne(['MD5(id)' => $c]);

        if (!$v)
            exit;

        $codice = $v->codice;

        header("Content-type:application/pdf");
        header("Content-Disposition:attachment;filename=$codice.pdf");
        readfile(Yii::getAlias("@webroot/voucher_natale2016/pdf/$codice.pdf"));
        exit;
    }

    public function actionInviavoucher() {
        $email = Yii::$app->request->post('email');
        $id = Yii::$app->request->post('id');

        $voucher = Voucher::findOne(['id' => $id]);

        if (\app\extensions\Mailer::inviaBigliettoAltraMail($voucher, $email)) {
            echo json_encode([
                'result' => 1
            ]);
        } else {
            echo json_encode([
                'result' => 0
            ]);
        }

        Yii::$app->end();
    }

    public function actionFilmdetail($id) {
        $film = Film::findOne(['id' => $id]);

        return $this->renderPartial("_film", ['film' => $film]);
    }

    public function actionInviaassistenza() {
        if (Yii::$app->user->isGuest) {
            echo json_encode([
                'result' => 2
            ]);
            Yii::$app->end();
        }


        $nome = Yii::$app->request->post('nome');
        $email = Yii::$app->request->post('email');
        $oggetto = Yii::$app->request->post('oggetto');
        $messaggio = Yii::$app->request->post('messaggio');

        if (\app\extensions\Mailer::inviaEmailAssistenza([
                    'msisdn' => Yii::$app->user->identity->msisdn,
                    'nome' => $nome,
                    'email' => $email,
                    'oggetto' => $oggetto,
                    'messaggio' => $messaggio
                ])) {
            echo json_encode([
                'result' => 1
            ]);
        } else {
            echo json_encode([
                'result' => 0
            ]);
        }

        Yii::$app->end();
    }

    public function actionModificavoucher() {
        $id = Yii::$app->request->post('id');

        $voucher = Voucher::findOne(['id' => $id]);

        $week = date("W", strtotime($voucher->data_voucher));

        // check for voucher already modified
        $existOther = Voucher::find()->where(['utente' => Yii::$app->user->identity->msisdn, 'WEEK(data_voucher)' => $week, 'valido' => 0])->andWhere(['!=', 'id', $id])->exists();
        if ($existOther) {
            echo json_encode([
                'result' => 0
            ]);
            exit;
        }

        $voucher->valido = 0;
        $voucher->save();

        Log::log(Yii::$app->user->identity->msisdn, 'Annulla Voucher', $voucher->attributes);

        echo json_encode([
            'result' => 1
        ]);
        exit;
    }

    public function actionProgrammazione($c) {
        $cinema = Cinema::findOne(['codice' => $c]);
        $programmazione = \common\models\Programmazione::find()->with('idFilm')->where(['cinema' => $c])->all();

        return $this->renderPartial("_programmazione", ['programmazione' => $programmazione, 'cinema' => $cinema]);
    }

//
//    public function actionRefreshposition() {
//        $cinema = Cinema::find()->all();
//        foreach ($cinema as $c) {
//            if ($c->latitudine == NULL && $c->longitudine == NULL) {
//                // Get lat and long by address         
//                $address = $c->indirizzo . " " . $c->citta; // Google HQ
//                $prepAddr = str_replace(' ', '+', $address);
//                $geocode = file_get_contents('http://maps.google.com/maps/api/geocode/json?address=' . $prepAddr . '&sensor=false');
//                $output = json_decode($geocode);
//
//                if (isset($output->results[0])) {
//                    $latitude = $output->results[0]->geometry->location->lat;
//                    $longitude = $output->results[0]->geometry->location->lng;
//
//                    $c->latitudine = $latitude;
//                    $c->longitudine = $longitude;
//                    $c->save(false);
//                }
//                sleep(2);
//            }
//        }
//        echo "END";
//        exit;
//    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin() {
        return $this->goHome();
        
//        $userAgent = $_SERVER['HTTP_USER_AGENT'];
//
//        $match1 = preg_match("/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|mobile.+firefox|netfront|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ ce|xda|xiino/i", $userAgent);
//        $match2 = preg_match("/^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a\ wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r\ |s\ )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1\ u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(\ i|ip)|hs\-c|ht(c(\-|\ |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(\ |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(\ |\/)|klon|kpt\ |kwc\-|kyo(c|k)|le(no|xi)|lg(\ g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-|\ |o|v)|zz)|mt(50|p1|v\ )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v\ )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|\ )|webc|whit|wi(g\ |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-)/i", $userAgent);
//
//        $loginUrl = "https://www.119selfservice.tim.it/area-clienti-119/privata/checkPrime?prize=cinema&backUrl=" . \yii\helpers\Url::to(['site/backurl'], true);
//        // $loginUrl = "https://www.119selfservice.collaudo.tim.it/area-clienti-119/privata/checkPrime?prize=cinema&backUrl=" . \yii\helpers\Url::to(['site/backurl'], true);
//        // $loginUrl = "http://preprod.timprimecinema.tim.it/test_login/checkPrime.php?prize=cinema&backUrl=" . \yii\helpers\Url::to(['site/backurl'], true);  
//        // echo $loginUrl;
//        // exit;
//
//        $loginMobileUrl = "https://m.tim.it/msite/browse/cinema/richiediVoucher.jsp?backUrl=" . \yii\helpers\Url::to(['site/backurl'], true);
//        // $loginMobileUrl = "https://m.collaudo.tim.it/msite/browse/cinema/richiediVoucher.jsp?backUrl=" . \yii\helpers\Url::to(['site/backurl'], true);
//        // $loginMobileUrl = "http://preprod.timprimecinema.tim.it/test_login/checkPrime.php?prize=cinema&backUrl=" . \yii\helpers\Url::to(['site/backurl'], true);
//        // TO CHECK
//        if (Yii::$app->request->getQueryParam("ri") == 1) {
//            $loginMobileUrl .= "?ri=1";
//            $loginUrl .= "?ri=1";
//        }
//
//        if ($match1 || $match2) {
//            $this->redirect($loginMobileUrl);
//        } else {
//            $this->redirect($loginUrl);
//        }


    }

    public function actionCheckLogin() {
        $ip_client1 = array_values(array_filter(explode(',', self::get_client_ip())));
        $ip = $ip_client1[0];

        $port = $_SERVER['REMOTE_PORT'];

        $res = EngInterface::ip2msisdn($ip, $port);

        $result = 0;
        $message = "";
        $headers = null;
        $body = null;
        if ($res != NULL && isset($res['headers']) && isset($res['body'])) {
            $headers = $res['headers'];
            $body = $res['body'];

            if ($headers['response_code'] == 200 && $body != NULL && $body->result == "SUCCESS" && $body->result != 'tel:+') {
                if ($body->result == "SUCCESS") {
                    $msisdn = str_replace(' ','',$body->msisdn);

                    if (Utils::startsWith($msisdn, 'tel:+39'))
                        $msisdn = substr($msisdn, 7);

                    if (Utils::startsWith($msisdn, 'tel:'))
                        $msisdn = substr($msisdn, 4);

                    
//                    $resMoo = EngInterface::moo($msisdn);
//                    if ($resMoo != NULL && isset($resMoo['headers']) && isset($resMoo['body'])) {
//                        $headers = $resMoo['headers'];
//                        $body = $resMoo['body'];
//
//                        if ($headers['response_code'] == 200 && $body != NULL) {
//                            
//                        }
//                    }

                    if ($msisdn != '') {
                        $resP = EngInterface::customerProfile($msisdn);
                        if ($resP != NULL && isset($resP['headers']) && isset($resP['body'])) {
                            $headers = $resP['headers'];
                            $body = $resP['body'];

                            if ($headers['response_code'] == 200 && $body != NULL && $body->result == "SUCCESS" && isset($body->data)) {
                                if ($body->data->tipo_cliente == "C") {
                                    $result = 1;

                                    $this->insertUser($msisdn);
                                } else {
                                    $result = 2;
                                }
                            } else {
                                $message = "ENG-customerProfile-" . $headers['response_code'] . "-$body->result";
                            }
                        }
                    } else { // $msisdn == ''
                        $message = "ENG-ip2msisdn-" . $headers['response_code'] . "-$body->result-$body->msisdn";
                    }
                }
            } else {
                $message = "ENG-ip2msisdn-" . $headers['response_code'] . "-$body->result";
            }
        }

        return json_encode(array(
            'result' => $result,
            'message' => $message,
            'response_code' => ($headers == null) ? null : $headers['response_code'],
            'response_body' => ($body == null) ? null : $body->result,
        ));
    }

    public function actionSendOtp() {
        $c = Yii::$app->request->post('c');

        $result = 0;
        $message = "";
        $headers = null;
        $body = null;

        if ($c != NULL && $c != "") {
            $isValidNumber = false;

            $msisdn = $c;
            $resMoo = EngInterface::moo($msisdn);
            if ($resMoo != NULL && isset($resMoo['headers']) && isset($resMoo['body'])) {
                $headers = $resMoo['headers'];
                $body = $resMoo['body'];

                if ($headers['response_code'] == 200 && $body != NULL && $body->result == "SUCCESS") {
                    if ($body->operator == "TIM") {
                        $resP = EngInterface::customerProfile($msisdn);
                        if ($resP != NULL && isset($resP['headers']) && isset($resP['body'])) {
                            $headers = $resP['headers'];
                            $body = $resP['body'];

                            if ($headers['response_code'] == 200 && $body != NULL && $body->result == "SUCCESS" && isset($body->data)) {
                                if ($body->data->tipo_cliente == "C") {
                                    $isValidNumber = true;
                                } else {
                                    $result = 3;
                                }
                            } else {
                                $message = "ENG - customerProfile [" . $headers['response_code'] . " $body->result]";
                            }
                        }
                    } else {
                        $result = 2;
                    }
                } else {
                    $message = "ENG - moo [" . $headers['response_code'] . " $body->result]";
                }
            }

            if ($isValidNumber) {
                $res = EngInterface::sendOTP($c);
                if ($res != NULL && isset($res['headers']) && isset($res['body'])) {
                    $headers = $res['headers'];
                    $body = $res['body'];

                    if ($headers['response_code'] == 200 && $body != NULL && $body->result == "SUCCESS") {
                        $result = 1;
                    } else {
                        $message = "ENG - sendOTP [" . $headers['response_code'] . " $body->result]";
                    }
                }
            }
        }

        return json_encode(array(
            'result' => $result,
            'message' => $message,
            'response_code' => ($headers == null) ? null : $headers['response_code'],
            'response_body' => ($body == null) ? null : $body->result,
        ));
    }

    public function actionCheckOtp() {
        $msisdn = Yii::$app->request->post('c');
        $otpCode = Yii::$app->request->post('code');

        $result = 0;
        $hasVoucher = 0;
        $message = "";
        if ($msisdn != NULL && $msisdn != "" && $otpCode != NULL && $otpCode != "") {
            $res = EngInterface::checkOTP($msisdn, $otpCode);
            if ($res != NULL && isset($res['headers']) && isset($res['body'])) {
                $headers = $res['headers'];
                $body = $res['body'];

                if ($headers['response_code'] == 200 && $body != NULL && $body->result == "SUCCESS") {
                    $result = 1;
                    $this->insertUser($msisdn);
                    $hasVoucher = Voucher::find()->where(['utente' => $msisdn])->exists();
                } else {
                    $message = "ENG-checkOTP-" . $headers['response_code'] . "-$body->result";
                }
            }
        }

        return json_encode(array(
            'result' => $result,
            'message' => $message,
            'response_code' => ($headers == null) ? null : $headers['response_code'],
            'response_body' => ($body == null) ? null : $body->result,
            'hasVoucher' => $hasVoucher ? 1 : 0
        ));
    }

    private function insertUser($msisdn) {
        $data_registrazione = date("Y-m-d H:i:s");
        $detect = new \frontend\extensions\Mobile_Detect;
        $deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
        $ua = $detect->getUserAgent();

        // find user if exists
        $user = \common\models\Utente::findIdentity($msisdn);
        if ($user == NULL) {
            $user = new \common\models\Utente;
            $user->msisdn = $msisdn;
            // $user->nome = $res->nome;
            // $user->cognome = $res->cognome;
            // $user->data_nascita = $res->data_nascita;
            // $user->email = $res->email;  // aggiornare la mail ad ogni login 
            $user->data_registrazione = $data_registrazione;
            $user->device_registrazione = $deviceType;
            $user->ua_registrazione = $ua;
        }


//        $user->nome = $res->nome; // aggiornare il nome ad ogni login in caso sia cambiata sul db TIM
//        $user->cognome = $res->cognome; // aggiornare il cognome ad ogni login in caso sia cambiata sul db TIM
//        $user->data_nascita = $res->data_nascita; // aggiornare la data di nascita ad ogni login in caso sia cambiata sul db TIM
//        $user->email = $res->email; // aggiornare la mail ad ogni login in caso sia cambiata sul db TIM

        $user->data_ultimo_login = $data_registrazione;
        $user->device_ultimo_login = $deviceType;
        $user->ua_ultimo_login = $ua;
        $user->save();

        Yii::$app->user->login($user);
        Log::log($user->msisdn, 'login');
    }

    public function actionLoginTest($t) {
        $this->insertUser($t);

        return $this->goHome();
    }

    public function actionBackurl($token, $transaction_id, $ri = 0) {
        $headers = getallheaders();
        //$ip_client = isset($headers['X-Forwarded-For']) ? $headers['X-Forwarded-For'] : $_SERVER['REMOTE_ADDR'];
        //$ip_client = $_SERVER['REMOTE_ADDR'];
        // $ip_client = array_values(array_filter(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])));
        $ip_client = array_values(array_filter(explode(',', $this->get_client_ip())));
        // $ip_client = ['10.173.78.135'];
        // $ip_client = ['10.214.84.18'];
        // var_dump($token);
        // var_dump($transaction_id);
        // exit;
        $url = 'https://www.tim.it/authfe/verificaCredenzialiCinema';
        // $url = 'https://156.54.69.70/authfe/verificaCredenzialiCinema';
        // $url = 'http://preprod.timprimecinema.tim.it/test_login/verificaCredenzialiCinema.php';

        $data = array('token' => $token, 'transaction_id' => $transaction_id, 'ip_address' => $ip_client[0]);
        // $data = array();

        Log::log(null, 'verificaCredenzialiCinema', $data);

        // $auth = base64_encode('armosia:4rm0s14');

        $options = array(
            'http' => array(
                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                // 'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Authorization: Basic $auth\r\n",
                'method' => 'POST',
                'content' => http_build_query($data)
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);


        if ($result === FALSE) {
            Log::log(null, 'verificaCredenzialiCinema-ABORT', $data);

            $dateStart = date("Y-m-d") . " 00:00:00";
            $dateEnd = date("Y-m-d") . " 23:59:59";

            $countErrors = Log::find()->where(['azione' => 'verificaCredenzialiCinema-ABORT'])->andWhere(['>=', 'data_azione', $dateStart])->andWhere(['<=', 'data_azione', $dateEnd])->count();
            if ($countErrors == 50 || $countErrors == 100 || $countErrors == 150 || $countErrors == 200) {
                \app\extensions\Mailer::inviaAlertMail($countErrors, 'help.prime@devtime.it');
            }

            throw new \yii\web\NotFoundHttpException();
        }

        // echo ($result); exit;

        $res = json_decode($result);

        if (!$res) {
            Log::log(null, 'verificaCredenzialiCinema-JSON', array($data, $result));

            $dateStart = date("Y-m-d") . " 00:00:00";
            $dateEnd = date("Y-m-d") . " 23:59:59";

            $countErrors = Log::find()->where(['azione' => 'verificaCredenzialiCinema-JSON'])->andWhere(['>=', 'data_azione', $dateStart])->andWhere(['<=', 'data_azione', $dateEnd])->count();
            if ($countErrors == 50 || $countErrors == 100 || $countErrors == 150 || $countErrors == 200) {
                \app\extensions\Mailer::inviaAlertMail($countErrors, 'help.prime@devtime.it');
            }

            throw new \yii\web\NotFoundHttpException('Invalid response format [Invalid JSON]');
        }
        if ($res->error_code >= 1) {
            Log::log(null, 'verificaCredenzialiCinema-ERROR', array_merge($data, (array) $res));

            $dateStart = date("Y-m-d") . " 00:00:00";
            $dateEnd = date("Y-m-d") . " 23:59:59";

            $countErrors = Log::find()->where(['azione' => 'verificaCredenzialiCinema-ERROR'])->andWhere(['>=', 'data_azione', $dateStart])->andWhere(['<=', 'data_azione', $dateEnd])->count();
            if ($countErrors == 50 || $countErrors == 100 || $countErrors == 150 || $countErrors == 200) {
                \app\extensions\Mailer::inviaAlertMail($countErrors, 'help.prime@devtime.it');
            }

            throw new \yii\web\NotFoundHttpException($res->error_desc);
        } else {
            Log::log(null, 'verificaCredenzialiCinema-SUCCESS', array_merge($data, (array) $res));
        }

        $data_registrazione = date("Y-m-d H:i:s");
        $detect = new \frontend\extensions\Mobile_Detect;
        $deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
        $ua = $detect->getUserAgent();

        // find user if exists
        $user = \common\models\Utente::findIdentity($res->msisdn);
        if ($user == NULL) {
            $user = new \common\models\Utente;
            $user->msisdn = $res->msisdn;
            // $user->nome = $res->nome;
            // $user->cognome = $res->cognome;
            // $user->data_nascita = $res->data_nascita;
            // $user->email = $res->email;  // aggiornare la mail ad ogni login 
            $user->data_registrazione = $data_registrazione;
            $user->device_registrazione = $deviceType;
            $user->ua_registrazione = $ua;
        }


        $user->nome = $res->nome; // aggiornare il nome ad ogni login in caso sia cambiata sul db TIM
        $user->cognome = $res->cognome; // aggiornare il cognome ad ogni login in caso sia cambiata sul db TIM
        $user->data_nascita = $res->data_nascita; // aggiornare la data di nascita ad ogni login in caso sia cambiata sul db TIM
        $user->email = $res->email; // aggiornare la mail ad ogni login in caso sia cambiata sul db TIM
        $user->data_ultimo_login = $data_registrazione;
        $user->device_ultimo_login = $deviceType;
        $user->ua_ultimo_login = $ua;
        $user->save();

        Yii::$app->user->login($user);
        Log::log($user->msisdn, 'login');

        if ($ri == 1)
            $this->redirect("index#cinema");
        else
            $this->redirect("index");
    }

    public function actionFailed() {

        $dateStart = date("Y-m-d") . " 00:00:00";
        // $dateStart = "2016-09-06 00:00:00";
        $dateEnd = date("Y-m-d") . " 23:59:59";

        $countErrors = Log::find()->where(['azione' => 'verificaCredenzialiCinema-ERROR'])->andWhere(['like', 'info', 'Failed to read'])->andWhere(['>=', 'data_azione', $dateStart])->andWhere(['<=', 'data_azione', $dateEnd])->count();
        // $countErrors = Log::find()->where(['azione' => 'verificaCredenzialiCinema-ERROR'])->andWhere(['>=', 'data_azione', $dateStart])->andWhere(['<=', 'data_azione', $dateEnd])->count();
        // if ($countErrors == 50 || $countErrors == 100 || $countErrors == 150 || $countErrors == 200) {
        //     \app\extensions\Mailer::inviaAlertMail($countErrors, 'a.dagostino@adinfosolution.it');
        // }

        echo $countErrors;
        exit;
    }

    public function actionTestcinema() {

        $data = http_build_query(array('apikey' => 'wIaNL3AC1U07mPK4', 'date' => date('d-m-Y')));
        $prog = simplexml_load_file('http://contentws.computime4it.com/rest/api/v1/movieteathers/programming/my?' . $data);
        // $prog = file_get_contents('http://contentws.computime4it.com/rest/api/v1/movieteathers/programming/my?apikey=wIaNL3AC1U07mPK4&date=today');

        var_dump($prog);
        // var_dump($prog->CONTENT_MOVIE_THEATERS->MOVIES);
        // var_dump($prog->CONTENT_MOVIE_THEATERS->SCHEDULES);
        // foreach ($prog->CONTENT_MOVIE_THEATERS->SCHEDULES->SCHEDULE as $s) {
        //     $programs = [];
        //     if (isset($s->SCHEDULE_PROGRAMS)) {
        //         foreach ($s->SCHEDULE_PROGRAMS as $sp) {
        //             $programs[] = (string) $sp->PROGRAM_TIME;
        //         }
        //     }
        //     var_dump($programs);
        // }
        exit;
    }

    public function actionTestv() {

        $dateStart = date("Y-m-d") . " 00:00:00";
        // $dateStart = "2016-09-06 00:00:00";
        $dateEnd = date("Y-m-d") . " 23:59:59";

        // $countErrors = Log::find()->where(['azione' => 'verificaCredenzialiCinema-ERROR'])->andWhere(['like', 'info', 'Failed to read'])->andWhere(['>=', 'data_azione', $dateStart])->andWhere(['<=', 'data_azione', $dateEnd])->count();
        $countErrors = Log::find()->where(['azione' => 'verificaCredenzialiCinema-ERROR'])->andWhere(['>=', 'data_azione', $dateStart])->andWhere(['<=', 'data_azione', $dateEnd])->count();
        // if ($countErrors == 50 || $countErrors == 100 || $countErrors == 150 || $countErrors == 200) {
        //     \app\extensions\Mailer::inviaAlertMail($countErrors, 'a.dagostino@adinfosolution.it');
        // }

        echo $countErrors;
        exit;

        // $ip_client1 = isset($headers['X-Forwarded-For']) ? $headers['X-Forwarded-For'] : 'NO';
        // $ip_client1 = isset($headers['X-Forwarded-For']) ? $headers['X-Forwarded-For'] : $_SERVER['REMOTE_ADDR'];
        $ip_client1 = array_values(array_filter(explode(',', $this->get_client_ip())));
        // $ip_client1 = array_values(array_filter(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])));
        // $ip_client2 = $_SERVER['REMOTE_ADDR'];
        // $ip_client1=array_values(array_filter(explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])));
        echo $ip_client1[0] . '<br/>';
        // echo $ip_client2;
        // echo '<br/><br/><br/>';
        // var_dump($_SERVER);

        exit;

        $detect = new \frontend\extensions\Mobile_Detect;
        $deviceType = ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'phone') : 'computer');
        echo $detect->getUserAgent();

        echo $deviceType;

        echo '<br/>';
        echo $detect->getUserAgent();

        exit;

        // $url = 'https://www.tim.it/authfe/verificaCredenzialiCinema';
        // // $data = array('token' => $token, 'transaction_id' => $transaction_id, 'ip_address' => $ip_client);
        // $data = array();
        // $options = array(
        //     'http' => array(
        //         'header' => "Content-type: application/x-www-form-urlencoded\r\n",
        //         // 'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Authorization: Basic $auth\r\n",
        //         'method' => 'POST',
        //         'content' => http_build_query($data)
        //     )
        // );
        // $context = stream_context_create($options);
        // // $result = file_get_contents($url, false, $context);
        // $result = file_get_contents($url);
    }

    public function actionTestv2() {

        // $ip_client1 = isset($headers['X-Forwarded-For']) ? $headers['X-Forwarded-For'] : 'NO';
        // $ip_client1 = isset($headers['X-Forwarded-For']) ? $headers['X-Forwarded-For'] : $_SERVER['REMOTE_ADDR'];
        // $ip_client1 = array_values(array_filter(explode(',', $this->get_client_ip())));
        // $ip_client1 = array_values(array_filter(explode(',', $_SERVER['HTTP_X_FORWARDED_FOR'])));
        // $ip_client2 = $_SERVER['REMOTE_ADDR'];
        // $ip_client1=array_values(array_filter(explode(',',$_SERVER['HTTP_X_FORWARDED_FOR'])));
        // echo $ip_client1[0] . '<br/>';
        // echo $ip_client2;


        $url = 'https://www.tim.it/authfe/verificaCredenzialiCinema';
        $data = array('token' => 'aaa', 'transaction_id' => '$transaction_id', 'ip_address' => '1.1.1.1');
        // $data = array();
        $options = array(
            'http' => array(
                'header' => "Content-type: application/x-www-form-urlencoded\r\n",
                // 'header' => "Content-type: application/x-www-form-urlencoded\r\n" . "Authorization: Basic $auth\r\n",
                'method' => 'POST',
                'content' => http_build_query($data)
            )
        );
        $context = stream_context_create($options);
        $result = file_get_contents($url, false, $context);
        // $result = file_get_contents($url);

        var_dump($result);

        echo '<br/><br/><br/>';

        var_dump($_SERVER);

        exit;
    }

    public function actionTestdate() {
        echo date('Y-m-d H:i:s');
    }

    // Function to get the client IP address
    public function get_client_ip() {
        $ipaddress = '';
        // if (isset($_SERVER['HTTP_CLIENT_IP']))
        //     $ipaddress = $_SERVER['HTTP_CLIENT_IP'];
        // else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
        //     $ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
        // else if(isset($_SERVER['HTTP_X_FORWARDED']))
        //     $ipaddress = $_SERVER['HTTP_X_FORWARDED'];
        // else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
        //     $ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
        // else if(isset($_SERVER['HTTP_FORWARDED']))
        //     $ipaddress = $_SERVER['HTTP_FORWARDED'];
        // else if(isset($_SERVER['REMOTE_ADDR']))
        //     $ipaddress = $_SERVER['REMOTE_ADDR'];
        // else
        //     $ipaddress = 'UNKNOWN';

        if (getenv('HTTP_CLIENT_IP'))
            $ipaddress = getenv('HTTP_CLIENT_IP');
        else if (getenv('HTTP_X_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_X_FORWARDED_FOR');
        else if (getenv('HTTP_X_FORWARDED'))
            $ipaddress = getenv('HTTP_X_FORWARDED');
        else if (getenv('HTTP_FORWARDED_FOR'))
            $ipaddress = getenv('HTTP_FORWARDED_FOR');
        else if (getenv('HTTP_FORWARDED'))
            $ipaddress = getenv('HTTP_FORWARDED');
        else if (getenv('REMOTE_ADDR'))
            $ipaddress = getenv('REMOTE_ADDR');
        else
            $ipaddress = 'UNKNOWN';
        return $ipaddress;
    }

//     public function actionImport() {
//         $cinema_xml = file_get_contents(Yii::getAlias("@webroot/resources/20160218.xml"));
//         $prog = simplexml_load_string($cinema_xml);
//         // empty all
// //        Cinema::deleteAll();
//         Programmazione::deleteAll();
//         $actualCinemas = Cinema::find()->all();
//         $actualSalas = Sala::find()->all();
//         function getCinema($cinemas, $codice) {
//             foreach ($cinemas as $c) {
//                 if ($c->codice == $codice) {
//                     return $c;
//                 }
//             }
//             return null;
//         }
//         function getSala($salas, $codice) {
//             foreach ($salas as $c) {
//                 if ($c->codice == $codice) {
//                     return $c;
//                 }
//             }
//             return null;
//         }
//         foreach ($prog->REGIONE as $regione) {
//             $nomeRegione = (string) $regione->NOME;
//             foreach ($regione->PROV as $prov) {
//                 $nomeProvincia = (string) $prov->NOME;
//                 foreach ($prov->CITTA as $citta) {
//                     $nomeCitta = (string) $citta->NOME;
//                     foreach ($citta->CINEMA as $cinema) {
//                         $codice = (string) $cinema['codice'];
//                         $cinemaModel = getCinema($actualCinemas, $codice);
//                         if ($cinemaModel == NULL) {
//                             $cinemaModel = new Cinema();
//                             $cinemaModel->codice = $codice;
//                             $cinemaModel->ctel = (string) $cinema['ctel'];
//                             $cinemaModel->nome = (string) $cinema->NOME;
//                             $cinemaModel->visione = (string) $cinema->VISIONE;
//                             $cinemaModel->quartiere = (string) $cinema->QUARTIERE;
//                             $cinemaModel->indirizzo = (string) $cinema->INDIRIZZO;
//                             $cinemaModel->regione = $nomeRegione;
//                             $cinemaModel->provincia = $nomeProvincia;
//                             $cinemaModel->citta = $nomeCitta;
//                             $cinemaModel->telefono = (string) $cinema->TELEFONO;
//                             $cinemaModel->bar = (string) $cinema->BAR;
//                             $cinemaModel->serv_dis = (string) $cinema->SERV_DIS;
//                             $cinemaModel->url = (string) $cinema->URL;
//                             $cinemaModel->pren_tel = (string) $cinema->PREN_TEL;
//                             if (!$cinemaModel->save()) {
//                                 print_r($cinemaModel->getErrors());
//                                 die('');
//                             }
//                         }
//                         foreach ($cinema->SALA as $sala) {
//                             $codiceSala = (string) $sala['codice'];
//                             $salaModel = getSala($actualSalas, $codiceSala);
//                             if ($salaModel === NULL) {
//                                 $salaModel = new Sala();
//                                 $salaModel->id_cinema = $cinemaModel->id;
//                                 $salaModel->progressivo = (string) $sala['progressivo'];
//                                 $salaModel->codice = $codiceSala;
//                                 $salaModel->ctel = (string) $sala['ctel'];
//                                 $salaModel->nome = (string) $sala->NOME;
//                                 $salaModel->posti = (string) $sala->POSTI;
//                                 $salaModel->dimensione = (string) $sala->DIMENSIONE;
//                                 $salaModel->suono = (string) $sala->SUONO;
//                                 $salaModel->disabili = (string) $sala->DISABILI;
//                                 $salaModel->audiolesi = (string) $sala->AUDIOLESI;
//                                 $salaModel->aria = (string) $sala->ARIA;
//                                 if (!$salaModel->save()) {
//                                     print_r($salaModel->getErrors());
//                                     die('');
//                                 }
//                             }
//                             foreach ($sala->PROGRAMMAZIONE as $p) {
//                                 $spettArray = array();
//                                 foreach ($p->SPETTACOLO as $spett) {
//                                     $spettArray[] = array('ora' => (string) $spett->ORA, 'prezzo' => (string) $spett->PREZZO);
//                                 }
//                                 $spettacoliJSON = json_encode($spettArray);
//                                 $progModel = new Programmazione();
//                                 $progModel->id_sala = $salaModel->id;
//                                 $progModel->id_cinema = $cinemaModel->id;
//                                 $progModel->variato = (string) $p->VARIATO;
//                                 $progModel->codice_film = (string) $p->FILM['cod'];
//                                 $progModel->ctel_film = (string) $p->FILM['ctel'];
//                                 $progModel->riduzioni = (string) $p->RIDUZIONI;
//                                 $progModel->spettacoli = $spettacoliJSON;
//                                 if (!$progModel->save()) {
//                                     print_r($progModel->getErrors());
//                                     die('');
//                                 }
//                             }
//                         }
//                     }
//                 }
//             }
//         }
//         echo "<br/><br/>CINEMA IMPORTED<br/>";
//         // import film
//         $film_xml = file_get_contents(Yii::getAlias("@webroot/resources/20160218_F.xml"));
//         $filmprog = simplexml_load_string($film_xml);
//         // empty all
//         Film::deleteAll();
//         foreach ($filmprog->FILM as $film) {
//             $codice = (string) $film['cod'];
//             $ctel = (string) $film['ctel'];
//             $trailer = (string) $film['trailer'];
//             $titolo = (string) $film->TITOLO;
//             $vm = (string) $film->VM;
//             $regia = (string) $film->REGIA;
//             $cast = (string) $film->CAST;
//             $anno = (string) $film->ANNO;
//             $colore = (string) $film->COLORE;
//             $tit_orig = (string) $film->TIT_ORIG;
//             $durata = (string) $film->DURATA;
//             $nazione = (string) $film->NAZIONE;
//             $distributore = (string) $film->DISTRIBUTORE;
//             $giudizio = (string) $film->GIUDIZIO;
//             $genere = (string) $film->GENERE;
//             $trama = (string) $film->TRAMA;
//             $immagine = null;
//             $immagineAltezza = null;
//             $immagineTipo = null;
//             if (isset($film->IMMAGINE)) {
//                 $immagine = (string) $film->IMMAGINE['nome'];
//                 $immagineAltezza = (string) $film->IMMAGINE['altezza'];
//                 $immagineTipo = (string) $film->IMMAGINE['tipo'];
//             }
//             $filmModel = new Film();
//             $filmModel->codice = $codice;
//             $filmModel->ctel = $ctel;
//             $filmModel->trailer = $trailer;
//             $filmModel->titolo = $titolo;
//             $filmModel->vm = $vm;
//             $filmModel->regia = $regia;
//             $filmModel->cast = $cast;
//             $filmModel->anno = $anno;
//             $filmModel->colore = $colore;
//             $filmModel->tit_orig = $tit_orig;
//             $filmModel->durata = $durata;
//             $filmModel->nazione = $nazione;
//             $filmModel->distributore = $distributore;
//             $filmModel->giudizio = $giudizio;
//             $filmModel->genere = $genere;
//             $filmModel->trama = $trama;
//             $filmModel->immagine = $immagine;
//             $filmModel->immagine_altezza = $immagineAltezza;
//             $filmModel->immagine_tipo = $immagineTipo;
//             if (!$filmModel->save()) {
//                 print_r($filmModel->getErrors());
//                 die('');
//             }
//         }
//         echo "<br/><br/>FILM IMPORTED<br/>";
//         Yii::$app->end();
//     }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout() {
        Yii::$app->user->logout();

        $this->redirect('index');
        // return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact() {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout() {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup() {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
                    'model' => $model,
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset() {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
                    'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token) {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
                    'model' => $model,
        ]);
    }

}
