<?php

namespace app\controllers;

use Yii;
use yii\filters\AccessControl;
use yii\web\Controller;
use yii\web\Response;
use yii\filters\VerbFilter;
use app\models\LoginForm;
use app\models\ContactForm;
use app\models\Contact;
use yii\config\db;
use yii\config\thdb;
use yii\config\j4db;
use \yii\db\Query;

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

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

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Login action.
     *
     * @return Response|string
     */
    public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }

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

    /**
     * Logout action.
     *
     * @return Response
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return Response|string
     */
    /*public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }*/
    public function actionContact()
    {
        
        $formelemek = new ContactForm();
        $contactmodel = new Contact();
        //$contactmodel->getOtpConfig(Yii::$app->user->identity->id);
        /*if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }*/
        $validate = Yii::$app->getRequest()->getQueryParam('validate');

        if(isset($validate) && $validate == 1)
        {
           
            $validated = $contactmodel->TOTPValidate();
            if($validated === TRUE)
            {
                Yii::$app->session->setFlash('message', 'Sikeres validáció!');
                Yii::$app->getResponse()->redirect('index.php?r=site%2Fcontact');
                echo 'Sikeres validáció!';
            }
            else
            {
                Yii::$app->session->setFlash('message', 'Sikertelen validáció!');
                Yii::$app->getResponse()->redirect('index.php?r=site%2Fcontact');
                 echo 'Sikertelen validáció!';
            }

        }
        
        return $this->render('contact', [
            'formelemek' => $formelemek,
        ]);
        
        
    }

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

    public function actionMigrator()
    {
        /*$query = new Query();
        $query->select(['*']);
        $query->from(['gigkt_content']);
        $query->where('id > 0');
        $j3content = $query->all();

        $i = 1;
        foreach ($j3content as $key => $value) 
        {
            $query = new Query();
            $query->select(['id']);
            $query->from(['gigkt_assets']);
            $query->where('name = "com_content.category.'.$value['catid'].'"');
            $speckoid = $query->one();

            /*Régi assets*/
           /*Yii::$app->db->createCommand('INSERT INTO uok1r_assets (parent_id, lft, rgt, level, name, title, rules) VALUES ('.$speckoid['id'].', 19, 20, 3, "com_content.article.'.$value['id'].'", "'.$value['title'].'", "")')->execute();
            
            /*Vissza a régi assetsből*/
            /*$query = new Query();
            $query->select(['max(id) lastid']);
            $query->from(['uok1r_assets']);
            $lastid = $query->one();

            Yii::$app->db->createCommand('UPDATE gigkt_content SET asset_id = '.$lastid['lastid'].' WHERE id = '.$value['id'])->execute();

            
        }

        die('ende');*/
    }

    public function actionThmigrator()
    {
        /*$original_catid = '29';
        $new_catid = '11';

        $metadata = '{"robots":"","author":"","rights":""}';
        $langcode = 'hu-HU';
        $images = '';

        $articles_array =Yii::$app->thdb->createCommand('SELECT * FROM cms_articles WHERE category_id = '.$original_catid)->queryAll();

        /*foreach ($articles_array as $key => $value) 
        {
            if($value['language_id'] == 1)
            {
                $langcode = 'hu-HU';
            }
            else
            {
                $langcode = 'en-GB';
            }
            $x = strtotime($value['modified']);
            $modified = date("Y-m-d H:i:s", $x);

            if($value['visible_to'] == '')
            {
                $publish_down = '0000-00-00 00:00:00';
            }
            else
            {
                $publish_down = date("Y-m-d H:i:s", strtotime($value['visible_to']));
            }

            if($value['visible_from'] == '')
            {
                $publish_up = '0000-00-00 00:00:00';
            }
            else
            {
                $publish_up = date("Y-m-d H:i:s", strtotime($value['visible_from']));
            }
                
            $value['lead'] = str_replace('"', '\"', $value['lead']);
            $value['body'] = str_replace('"', '\"', $value['body']);
            $value['title'] = str_replace('"', '\"', $value['title']);
            $value['subtitle'] = str_replace('"', '\"', $value['subtitle']);

            
            Yii::$app->j4db->createCommand('INSERT INTO nlmvl_content (
                `id`, 
                `asset_id`, 
                `title`, 
                `alias`, 
                `introtext`, 
                `fulltext`, 
                `state`, 
                `catid`, 
                `created`, 
                `created_by`, 
                `created_by_alias`, 
                `modified`, 
                `modified_by`, 
                `publish_up`, 
                `publish_down`,
                `images`, 
                `urls`, 
                `attribs`, 
                `ordering`,
                `metakey`, 
                `metadesc`,
                `access`, 
                `hits`,
                `metadata`, 
                `language`, 
                `note`
            ) VALUES ('

                .'"'.$value['id'].'"'
                .',0,'
                .'"'.$value['title'].'"'.','
                .'"'.$value['slug'].'"'.','
                .'"'.$value['lead'].'"'.','
                .'"'.$value['body'].'"'.','
                .'"'.$value['article_status_id'].'"'.','
                .'"'.$new_catid.'"'.','
                .'"'.$value['created'].'"'.','
                .'"141"'.','
                .'"0"'.','
                .'"'.$modified.'"'.','
                .'"0"'.','
                .'"'.$publish_up.'"'.','
                .'"'.$publish_down.'"'.',"'
                .$images.'",'
                .'" "'.','
                .'" "'.','
                .'"0"'.','
                .'" "'.','
                .'" "'.','
                .'"'.$value['article_status_id'].'"'.','
                .'"'.$value['read_count'].'",'
                .'\''.$metadata.'\','
                .'"'.$langcode.'",'
                .'" ")')->execute();
                    
            Yii::$app->j4db->createCommand('INSERT INTO nlmvl_fields_values (`field_id`, `item_id`, `value`) VALUES (1,'.$value['id'].',"'.$value['subtitle'].'")')->execute();
        }*/
        
        /*$articles_for_assets_array = Yii::$app->j4db->createCommand('SELECT * FROM nlmvl_content WHERE id != 1')->queryAll();
        

        
        foreach ($articles_for_assets_array as $key => $value) 
        {

            /*$value['title'] = str_replace('"', '\"', $value['title']);

            $speckoid = Yii::$app->j4db->createCommand('SELECT * FROM nlmvl_assets WHERE name = "com_content.category.'.$value['catid'].'"')->queryOne();

            Yii::$app->j4db->createCommand('INSERT INTO nlmvl_assets (parent_id, lft, rgt, level, name, title, rules) VALUES ('.$speckoid['id'].', 19, 20, 3, "com_content.article.'.$value['id'].'", "'.$value['title'].'", "")')->execute();
            
            $lastid = Yii::$app->j4db->createCommand('SELECT max(id) lastid FROM nlmvl_assets ')->queryOne();
            
            Yii::$app->j4db->createCommand('UPDATE nlmvl_content SET asset_id = '.$lastid['lastid'].' WHERE id = '.$value['id'])->execute();*/

            //Yii::$app->j4db->createCommand('INSERT INTO nlmvl_workflow_associations (item_id, stage_id, extension) VALUES ('.$value['id'].', 1, "com_content.article")')->execute();
            
        //}
        
    }
    public function actionKkimigrator()
    {
        
        /*$original_catid = '29';
        $new_catid = '17';

        $metadata = '{"robots":"","author":"","rights":""}';
        $langcode = 'hu-HU';
        $images = '';

        $articles_array =Yii::$app->thdb->createCommand('SELECT * FROM cms_articles WHERE category_id = '.$original_catid)->queryAll();

        foreach ($articles_array as $key => $value) 
        {
            if(isset($value['language_id']))
            {
                if($value['language_id'] == 1)
                {
                    $langcode = 'hu-HU';
                }
                else
                {
                    $langcode = 'en-GB';
                }
            }
            else
            {
                $langcode = 'hu-HU';
            }
            
            $x = strtotime($value['modified']);
            $modified = date("Y-m-d H:i:s", $x);

            if(isset($value['visible_to']))
            {
                if($value['visible_to'] == '')
                {
                    $publish_down = '0000-00-00 00:00:00';
                }
                else
                {
                    $publish_down = date("Y-m-d H:i:s", strtotime($value['visible_to']));
                }
            }
            else
            {
                $publish_down = '0000-00-00 00:00:00';
            }


            if(isset($value['visible_from']))
            {

                if($value['visible_from'] == '')
                {
                    $publish_up = '0000-00-00 00:00:00';
                }
                else
                {
                    $publish_up = date("Y-m-d H:i:s", strtotime($value['visible_from']));
                }
            }
            else
            {
                $publish_up = '0000-00-00 00:00:00';
            }
    
            /*$value['lead'] = str_replace('"', '\"', $value['lead']);
            $value['body'] = str_replace('"', '\"', $value['body']);
            $value['title'] = str_replace('"', '\"', $value['title']);
            $value['subtitle'] = str_replace('"', '\"', $value['subtitle']);*/

            /*$title = str_replace('"', '\"', $value['title']);
            $lead = str_replace('"', '\"', $value['lead']);
            //$body = str_replace('"', '\"', $value['leiras']);
            $article_status_id = 1;
            $slug = $this->stripAccents($title);
            $slug = str_replace(' ', '-', $slug);

            $read_count = 0;

            /*Yii::$app->kkidb->createCommand('INSERT INTO oe4p1_content (
                `id`, 
                `asset_id`, 
                `title`, 
                `alias`, 
                `introtext`, 
                `fulltext`, 
                `state`, 
                `catid`, 
                `created`, 
                `created_by`, 
                `created_by_alias`, 
                `modified`, 
                `modified_by`, 
                `publish_up`, 
                `publish_down`,
                `images`, 
                `urls`, 
                `attribs`, 
                `ordering`,
                `metakey`, 
                `metadesc`,
                `access`, 
                `hits`,
                `metadata`, 
                `language`, 
                `note`
            ) VALUES ('

                .'"'.$value['id'].'"'
                .',0,'
                .'"'.$title.'"'.','
                .'"'.$slug.'"'.','
                .'"'.$lead.'"'.','
                .'"'.$body.'"'.','
                .'"'.$article_status_id.'"'.','
                .'"'.$new_catid.'"'.','
                .'"'.$value['created'].'"'.','
                .'"510"'.','
                .'"0"'.','
                .'"'.$modified.'"'.','
                .'"0"'.','
                .'"'.$publish_up.'"'.','
                .'"'.$publish_down.'"'.',"'
                .$images.'",'
                .'" "'.','
                .'" "'.','
                .'"0"'.','
                .'" "'.','
                .'" "'.','
                .'"'.$article_status_id.'"'.','
                .'"'.$read_count.'",'
                .'\''.$metadata.'\','
                .'"'.$langcode.'",'
                .'" ")')->execute();
            */

            /*$value['lead'] = str_replace('"', '\"', $value['lead']);
            $value['body'] = str_replace('"', '\"', $value['body']);
            $value['title'] = str_replace('"', '\"', $value['title']);
            $value['subtitle'] = str_replace('"', '\"', $value['subtitle']);

            
            Yii::$app->kkidb->createCommand('INSERT INTO oe4p1_content (
                `id`, 
                `asset_id`, 
                `title`, 
                `alias`, 
                `introtext`, 
                `fulltext`, 
                `state`, 
                `catid`, 
                `created`, 
                `created_by`, 
                `created_by_alias`, 
                `modified`, 
                `modified_by`, 
                `publish_up`, 
                `publish_down`,
                `images`, 
                `urls`, 
                `attribs`, 
                `ordering`,
                `metakey`, 
                `metadesc`,
                `access`, 
                `hits`,
                `metadata`, 
                `language`, 
                `note`
            ) VALUES ('

                .'"'.$value['id'].'"'
                .',0,'
                .'"'.$title.'"'.','
                .'"'.$value['slug'].'"'.','
                .'"'.$value['lead'].'"'.','
                .'"'.$value['body'].'"'.','
                .'"'.$value['article_status_id'].'"'.','
                .'"'.$new_catid.'"'.','
                .'"'.$value['created'].'"'.','
                .'"141"'.','
                .'"0"'.','
                .'"'.$modified.'"'.','
                .'"0"'.','
                .'"'.$publish_up.'"'.','
                .'"'.$publish_down.'"'.',"'
                .$images.'",'
                .'" "'.','
                .'" "'.','
                .'"0"'.','
                .'" "'.','
                .'" "'.','
                .'"'.$value['article_status_id'].'"'.','
                .'"'.$value['read_count'].'",'
                .'\''.$metadata.'\','
                .'"'.$langcode.'",'
                .'" ")')->execute();

            Yii::$app->kkidb->createCommand('INSERT INTO oe4p1_fields_values (`field_id`, `item_id`, `value`) VALUES (5,'.$value['id'].',"'.$value['subtitle'].'")')->execute();

            /*Yii::$app->kkidb->createCommand('INSERT INTO oe4p1_fields_values (`field_id`, `item_id`, `value`) VALUES (3,'.$value['id'].',"'.$value['kezdo_datum'].'")')->execute();
            Yii::$app->kkidb->createCommand('INSERT INTO oe4p1_fields_values (`field_id`, `item_id`, `value`) VALUES (4,'.$value['id'].',"'.$value['zaro_datum'].'")')->execute();*/

        //}

        
        /*$articles_for_assets_array = Yii::$app->kkidb->createCommand('SELECT * FROM oe4p1_content WHERE asset_id = 0')->queryAll();
        
        foreach ($articles_for_assets_array as $key => $value) 
        {
           //alias correction
           $x = str_replace('.','',$value['title']);
           $x = str_replace('   ',' ',$x);
           $x = str_replace(' ','-',$x);
           $x = str_replace('---','-',$x);
           $x = $this->stripAccents($x);

           Yii::$app->kkidb->createCommand('UPDATE oe4p1_content SET alias = "'.$x.'" WHERE id = '.$value['id'])->execute();


            $value['title'] = str_replace('"', '\"', $value['title']);

            $speckoid = Yii::$app->kkidb->createCommand('SELECT * FROM oe4p1_assets WHERE name = "com_content.category.'.$value['catid'].'"')->queryOne();

            Yii::$app->kkidb->createCommand('INSERT INTO oe4p1_assets (parent_id, lft, rgt, level, name, title, rules) VALUES ('.$speckoid['id'].', 19, 20, 3, "com_content.article.'.$value['id'].'", "'.$value['title'].'", "")')->execute();
            
            $lastid = Yii::$app->kkidb->createCommand('SELECT max(id) lastid FROM oe4p1_assets ')->queryOne();
            
            Yii::$app->kkidb->createCommand('UPDATE oe4p1_content SET asset_id = '.$lastid['lastid'].' WHERE id = '.$value['id'])->execute();

            Yii::$app->kkidb->createCommand('INSERT INTO oe4p1_workflow_associations (item_id, stage_id, extension) VALUES ('.$value['id'].', 1, "com_content.article")')->execute();
            
        }*/
        
        /*Könyvleírások*/
        /*$articles_array = Yii::$app->thdb->createCommand('SELECT leiras, id FROM cms_biographies WHERE portal_id = 1')->queryAll();*/
        //9843

        /*foreach ($articles_array as $key => $value) 
        {
            //echo 'INSERT INTO oe4p1_fields_values (`field_id`, `item_id`, `value`) VALUES (36,'.$value['id'].',"'.$value['leiras'].'");<br>';
            /*$value['leiras']= str_replace('"','\"',$value['leiras']);
            Yii::$app->kkidb->createCommand('INSERT INTO oe4p1_fields_values (`field_id`, `item_id`, `value`) VALUES (36,'.$value['id'].',"'.$value['leiras'].'")')->execute();*/
        //}

        $content = Yii::$app->kkidb->createCommand('SELECT * FROM oe4p1_content WHERE catid = 8')->queryAll();
        $time = strtotime('1944. szeptember 12.');

        $newformat = date('Y-m-d',$time);

        echo $newformat;
        /*foreach ($variable as $key => $value) 
        {
           $month = array('1' => 'januar', );
        }*/

    }

    public function stripAccents($str) 
    {
        return strtr(utf8_decode($str), utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'), 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
    }

    public function actionCorrector()
    {
        /*$articles_for_assets_array = Yii::$app->kkidb->createCommand('SELECT * FROM oe4p1_content')->queryAll();

        foreach ($articles_for_assets_array as $key => $value) 
        {
           $x = str_replace('.','',$value['title']);
           $x = str_replace('   ',' ',$x);
           $x = str_replace(' ','-',$x);
           $x = str_replace('---','-',$x);
           $x = $this->stripAccents($x);

           echo $x.'<br>';

           Yii::$app->kkidb->createCommand('UPDATE oe4p1_content SET alias = "'.$x.'" WHERE id = '.$value['id'])->execute();
        }*/

    }
}


