<?php

namespace common\modules\sessions\controllers;

use Yii;
use yii\web\Response;

use common\components\BaseController;
use common\modules\sessions\models\Session;
use common\modules\sessions\models\SessionUrl;

/**
 * Default controller for the `sessions` module
 */
class DefaultController extends BaseController
{
	public static function actionsTitles()
    {
        return [
            'Add'           => 'Фиксация сессии',
            'Update'        => 'Фиксация пребывания на странице',
        ];
    }

    /**
     * @return mixed
     */
    public function actionAdd()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

    	if(!Yii::$app->session->has('SessionId'))
        {
	    	$session = $this->createSession();
	    }
        else
        {
            $session = Session::findOne(Yii::$app->session->get('SessionId'));
            if(!$session)
            {
                $session = $this->createSession();
            }
        }

        if(!$session->user_id && !Yii::$app->user->isGuest)
        {
            $session->user_id = Yii::$app->user->id;
            $session->save(false, ['user_id']);
        }

        list($url, $referer) = Yii::$app->session->get('SessionData');

        $sUrl = new SessionUrl;
        $sUrl->session_id = $session->id;
        $sUrl->url = $url;
        $sUrl->referer = $referer;

        $sUrl->save();
        
        return ['success' => true];
    }

    /**
     * @return mixed
     */
    public function actionUpdate()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        try 
        {
            list($url, $referer) = Yii::$app->session->get('SessionData');

            $url = SessionUrl::find()->where([
                'url' => $url,
                'referer' => $referer,
                'session_id' => Yii::$app->session->get('SessionId')
            ])->orderBy('created_at DESC')->one();

            if($url)
            {
                $url->save(false, ['updated_at']);

                return ['success' => true]; 
            }

            return ['success' => false]; 
        } 
        catch (Exception $e)
        {
            return ['error' => true]; 
        }
    }

    /**
     * @return Session
     */
    private function createSession()
    {
        $request = Yii::$app->request;

        $session = new Session;
        $session->PHPSESSID = Yii::$app->session->id;
        $session->ip = $request->userIP;

        if(!Yii::$app->user->isGuest)
        {
            $session->user_id = Yii::$app->user->id;
        }

        $session->save();

        Yii::$app->session->set('SessionId', $session->id);

        return $session;
    }
}
