<?php
namespace myresto\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\LoginForm;

use myresto\models\SignupForm;
use myresto\models\ChangePasswordForm;
use myresto\models\SetPasswordForm;
use myresto\models\UpdateAccountForm;

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

    /**
     * {@inheritdoc}
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
        ];
    }

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

    public function actionHelp() {
        return $this->render('help');
    }

    public function actionHelpSubmit() {
        $post = Yii::$app->request->post();
        $data = [
            'member_name' =>$post['member_name'],
            'member_email'=>$post['member_email'],
            'priority'=> $post['priority'],
            'subject' => $post['subject'],
            'description' => $post['description'],
            'companyname' => $post['companyname'],
            'cc' => 'support',
        ];
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => "https://interactive.co.id/kb/api/insertSupportTicket/5ed107cb1acd45c14a342cd076e8681f704593c56068be04746510ff5fcb4c30",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => $data
        ));
        $response = json_decode(curl_exec($curl), true);
        curl_close($curl);

        return $response['result'];
    }

    public function actionAbout() {
        return $this->render('about');
    }

    public function actionTermsAndConditions() {
        return $this->render('terms-and-conditions');
    }

    public function actionPrivacyPolicy() {
        return $this->render('privacy-policy');
    }

    public function installDb() {
        $db = Yii::$app->db;

        $dsn = $db->dsn;
        $dsn = explode(';', $dsn);
        
        $dbhost = $dsn[0];
        $dbhost = explode('=', $dbhost);
        $dbhost = $dbhost[1];

        $dbname = $dsn[1];
        $dbname = explode('=', $dbname);
        $dbname = $dbname[1];
        
        $dbuser = $db->username;
        $dbpass = $db->password;
        
        date_default_timezone_set("Asia/Jakarta");
        $conn = mysqli_connect($dbhost, $dbuser, $dbpass);
        if ($conn->connect_error) {
            die("Connection failed: " . $conn->connect_error);
        } 

        $sql = "CREATE DATABASE IF NOT EXISTS $dbname";
        if ($conn->query($sql) === TRUE) {
            // echo "Database created successfully";
        } else {
            // echo "Error creating database: " . $conn->error;
        }

        $conn->close();
        $sql = file_get_contents('../sql/install.sql');
        Yii::$app->db->createCommand($sql)->execute();
    }

    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();
        } else {
            $model->password = '';
            $errorCode = 0;

            try {
                Yii::$app->db->open();

                $tableSchemaMigration = Yii::$app->db->schema->getTableSchema('migration');
                $tableSchemaUser = Yii::$app->db->schema->getTableSchema('user');
                $tableSchemaSyncAccountToJurnal = Yii::$app->db->schema->getTableSchema('sync_account_to_jurnal');
                $tableSchemaSyncConfig = Yii::$app->db->schema->getTableSchema('sync_config');
                $tableSchemaSyncToJurnal = Yii::$app->db->schema->getTableSchema('sync_to_jurnal');

                if ($tableSchemaMigration === null || $tableSchemaUser === null || $tableSchemaSyncAccountToJurnal === null || $tableSchemaSyncConfig === null || $tableSchemaSyncToJurnal === null)
                    self::installDb();
            } catch (yii\db\Exception $e) {
                $errorCode = $e->getCode();
                if ($errorCode == 1049)
                    self::installDb();
            }

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

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

        return $this->goHome();
    }

    public function actionSignup() {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                Yii::$app->session->setFlash('success', 'User berhasil dibuat.');
                return $this->goHome();
            }
        }

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

    public function actionChangePassword() {
        $model = new ChangePasswordForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->changePassword()) {
                Yii::$app->session->setFlash('success', 'Your password has been changed successfully.');
                return $this->redirect('change-password');
            }
        }

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

    public function actionSetPassword() {
        $model = new SetPasswordForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->setPassword()) {
                Yii::$app->session->setFlash('success', 'Password berhasil diubah.');
                return $this->goHome();
            }
        }

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

    public function actionUpdateAccount() {
        $model = new UpdateAccountForm();
        $model->username = Yii::$app->user->identity->username;
        $model->email = Yii::$app->user->identity->email;
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->updateAccount()) {
                Yii::$app->session->setFlash('success', 'Your account information has been updated successfully.');
                return $this->redirect('update-account');
            }
        }

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

    public function replaceFirstMatch($needle, $replace, $haystack) {
        $pos = strpos($haystack, $needle);
        if ($pos !== false)
            $newstring = substr_replace($haystack, $replace, $pos, strlen($needle));
        else
            $newstring = $haystack;
        return $newstring;
    }

    public function actionSetDb() {
        $file = '../../common/config/main-local.php';
        $fileContent = file_get_contents($file);
        $dbhost = $_POST['dbhost'];
        $dbname = $_POST['dbname'];
        $dbusername = $_POST['dbusername'];
        $dbpassword = $_POST['dbpassword'];

        $dsn = explode("'dsn' => ", $fileContent);
        $dsn = explode(",", $dsn[1]);
        $dsn = $dsn[0];
        $dsn = trim($dsn, "'");
        $newDsn = "mysql:host=$dbhost;dbname=$dbname";

        $username = explode("'username' => ", $fileContent);
        $username = explode(",", $username[1]);
        $username = $username[0];
        $username = trim($username, "'");

        $password = explode("'password' => ", $fileContent);
        $password = explode(",", $password[1]);
        $password = $password[0];
        $password = trim($password, "'");

        $fileContent = self::replaceFirstMatch("'dsn' => '$dsn'", "'dsn' => '$newDsn'", $fileContent);
        $fileContent = self::replaceFirstMatch("'username' => '$username'", "'username' => '$dbusername'", $fileContent);
        $fileContent = self::replaceFirstMatch("'password' => '$password'", "'password' => '$dbpassword'", $fileContent);

        file_put_contents($file, $fileContent);
    }
}
