<?php
namespace rest\controllers;

use Yii;
use common\models\LoginForm;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use common\models\User;
use common\components\Helper;
use common\models\Log;

/**
 * Site controller
 */
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 mixed
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {
        if (!\Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
        		
        		$geoip = Helper::getGeoIp();
        	
        		$message = "";
        		$user  = User::findOne(\Yii::$app->user->id);
        		if ( isset($geoip)){
        			$ip = isset( $geoip->ip ) ? $geoip->ip : "";
        			$city = isset( $geoip->city ) ? $geoip->city : "";
        			$message = "Bejelentkezés:   " .$user->username. " Ip cím:".  $ip . " Város: " . $city;
        		}
        			
        		Log::log([
        			'type' =>Log::$TYPE_LOGIN,
        			'message' => $message	
        		]);
        	
				return $this->redirect(['account/select']);
        } else {
            return $this->render('login', ['model' => $model,]);
        }
    }
    


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

        return $this->goHome();
    }





}
