<?php

require_once 'overall.inc.php';

use Mnv\Core\BotBlockIp;
use Mnv\Core\Config;
use Mnv\Core\Utilities\Cookie\Cookie;
use Mnv\Core\Utilities\Cookie\Session;
use Mnv\Core\Auth\Exceptions\UnknownIdException;

/* shop */

use Mnv\Models\Users\UserTypes;
use Mnv\Modules\Shop\Cart;
use Mnv\Modules\User\Auth;

// Проверка текущего ip-адреса
BotBlockIp::checkIp();

$adminIp = '';
$userIp = request()->ip();
if (!empty(Config::getValue('listIp'))) {
    $listIps = explode(",", Config::getValue('listIp'));
    foreach ($listIps as $listIp) {
        if ($listIp == $userIp) {
            $adminIp = $listIp;
        }
    }
}

/** если сайте отключен вывести шаблон или сообщение */
if (Config::getValue('website_down') == 0 && $adminIp == '') {
    header("HTTP/1.0 503 Service Unavailable");
    if (file_exists(THEME_ROOT.'/maintenance.tpl')) {
        $smarty->display('maintenance.tpl');
    } else {
        print "<html><head><title>Сервис недоступен</title><style> html, body {height : 100vh;width : 100%;overflow : hidden;margin: 0 auto;font-family: -apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen-Sans,Ubuntu,Cantarell,'Helvetica Neue',sans-serif;}.wrapper {height : 100%;width : 100%;padding: 0px;text-align: center;}.content {position:absolute; width:100%; top:50%;transform: translateY(-100%);}h3{color: #424242;font-weight: 400;}</style></head><body><div class='wrapper'><div class='content'><h3>".nl2br(Config::getValue('maintenance_message'))."</h3></div></div></body></html>";
    }
    exit;
}

//ini_set('session.gc_maxlifetime', 172800);
//ini_set('session.cookie_lifetime', 172800);

	/* сессия */
if (\session_status() == \PHP_SESSION_NONE) {
    // использовать файлы cookie для хранения идентификаторов сеансов
    \ini_set('session.use_cookies', 1);
    // использовать только файлы cookie (не отправлять идентификаторы сеанса в URL-адресах)
    \ini_set('session.use_only_cookies', 1);
    // не отправлять идентификаторы сеанса в URL-адресах
    \ini_set('session.use_trans_sid', 0);

    // запустить сеанс (запрашивает запись cookie на клиенте)
    @Session::start($visitorSessionName);
}

$smarty->assign('sessionId', Session::id());
Cookie::setcookie($visitorSessionName, Session::id(),time() + 604800, '/', '', '', true, 'Lax');

$userAuth = new Auth($userIp,false, $visitorSessionName);
$siteUser = [];
try {
    if ($userAuth->checkUser() && $userAuth->doesUserHaveRole($userAuth->id(), UserTypes::CUSTOMER)) {
        $siteUser = $userAuth->loadSiteUser($userAuth->id(), true);
        $smarty->assign('siteUser', $siteUser);
    } else {
        $smarty->assign('siteUser', $siteUser);
        $userAuth->logOutUser();
    }
}  catch (UnknownIdException $e) {
    $userAuth->logOutUser();
}

/* shop */
$cart = new Cart();
$smarty->assign('basket', $cart->cart);

	/* Загрузка активных баннеров */
//    $bannersArr =  DB::init()->connect()->table('banners')->where('isActive', 1)->getAll();
//    foreach ($bannersArr as $banner) $banners[$banner->bannerId] = $banner->generatedCode;
//	if(!empty($banners)) $smarty->assign('banners', $banners);


// 	// Default currency
 	$defaultCurrency = connect('shop_currency')->where('isDefault','=',1)->get('array');
 	$smarty->assign('defaultCurrency', $defaultCurrency);

 	$action = request()->get('action');
     if (isset($action['setActiveCurrency'])) {
         $activeCurrencyId =  (int) request()->get('activeCurrencyId');
     } else	{
         $activeCurrencyId = Cookie::exists('activeCurrencyId') ? Cookie::get('activeCurrencyId') : $defaultCurrency['id'];
     }

 	setActiveCurrency($activeCurrencyId);

 	function setActiveCurrency($currencyId) {
         global $smarty, $allCurrency, $defaultCurrency;
         if (!empty($allCurrency))
         foreach ($allCurrency as $c) {
         	if ($c['id'] == $currencyId) {
         		$currency = $c;
         		break;
         	}
         }
         if (empty($currency)) $currency = $defaultCurrency;
         Cookie::setcookie('activeCurrencyId', $currency['id'], 0, '/', '', '', true, 'Lax');
         $GLOBALS['activeCurrency'] = $currency;
         $smarty->assign('activeCurrency', $currency);
     }

    $favoriteCount = 0;
    $favoriteKeys = [];
    if (Cookie::exists('_favorites')) {
        $favoriteKeys = explode(',', Cookie::get('_favorites'));
        $favoriteCount = count($favoriteKeys);
    } elseif ($userAuth->checkUser()) {
        $favoriteKeys = connect('users')->select('favorites')->where('userId',  $userAuth->id())->getValue();
        if (!empty($favoriteKeys)) {
            $favoriteKeys = explode(',', $favoriteKeys);
            $favoriteCount = count($favoriteKeys);
        }
    }

    $smarty->assign('favoriteKeys', $favoriteKeys);
    $smarty->assign('favoriteCount', $favoriteCount);


    $cartCountProducts = 0;
    if (Session::id()) {
        $cartCountProducts = connect('shop_cart')->sum('quantity', 'count')->where('token', Session::id())->getValue('array');
    } elseif ($userAuth->checkUser()) {
        $cartCountProducts = connect('shop_cart')->sum('quantity', 'count')->where('userId', $userAuth->id())->getValue('array');
    }

    $smarty->assign('cartCountProducts', $cartCountProducts);


//    $stock = 0;
//    $discount = 0;
//    if (Cookie::exists('_discount')) $discount =  Cookie::get('_discount');
//    if (Cookie::exists('_stock')) $stock =  Cookie::get('_stock');
//
//    $smarty->assign('discount', $discount);
//    $smarty->assign('stock', $stock);

//print_r(GLOBAL_ROOT);

?>