<?
//Vendor Autoloader
include(rtrim($_SERVER['DOCUMENT_ROOT'],'/') . '/vendor/autoload.php');
//Load environment variables from config if exists
$envDir = rtrim(dirname(dirname(__DIR__)),'/') . '/config';
if (is_dir($envDir)) {
    $dotenv = new \Dotenv\Dotenv($envDir);
    $dotenv->load();
}
\DynCom\dcLog\Handler\IntegrationHelper::entrypoint();

// Redirects url without / at the end and preserves get parameters
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $uri = $_SERVER['REQUEST_URI'];
    $parsed = parse_url($uri);

    if (
        substr($parsed['path'], -1) !== '/' &&
        !pathinfo($parsed['path'], PATHINFO_EXTENSION)
    ) {
        $newUrl = $parsed['path'] . '/';
        if (!empty($parsed['query'])) {
            $newUrl .= '?' . $parsed['query'];
        }

        header('Location: ' . $newUrl, true, 301);
        exit;
    }
}

//include(rtrim($_SERVER['DOCUMENT_ROOT'],'/') . '/mysyde/common/classes/GeneralErrorExceptionHandling.php');

$redirectToPath = '';
//$redirectToPath = 'http://dc-one.dev/';
$redirectMsg = 'We\'re sorry - an internal error occurred. The error has been logged and support notified. We except the problem to be solved shorty.';

//GeneralErrorExceptionHandling::setErrorHandler($redirectToPath,$redirectMsg);
//GeneralErrorExceptionHandling::setExceptionHandler($redirectToPath,$redirectMsg);

$displayErrors = (bool)getenv('DISPLAY_ERRORS');

ini_set('display_errors',$displayErrors);

error_reporting(E_ERROR|E_WARNING|E_PARSE);
header("Content-Type: text/html; charset=utf-8");
header_remove('X-Frame-Options');
//header("Content-Security-Policy: frame-ancestors 'self';");
mb_internal_encoding('UTF-8');
require_once("../common/common_functions.inc.php");
require_once((local_environment()) ? "../mysyde.config.php" : "../mysyde-server.config.php");
try {
    require_once("frontend_functions.inc.php");
    require_once("start.inc.php");
    require_once($GLOBALS["layout"]["frontend_include"]);
    require_once("close.inc.php");
    error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
} catch (Throwable $e) {
    \DynCom\dcLog\Handler\IntegrationHelper::exceptionHandler($e);
    $logger = get_logger("main");
    $logger->error($e->getMessage() . " | " . $e->getTraceAsString());
}

function extract_request_uri_variables() {
    $is_shop = strpos($_SERVER['REQUEST_URI'],'/shop/') !== false;
    if ($is_shop) {
        extract_shop_request_uri_variables();
    } else {
        extract_site_request_uri_variables();
    }
}

function extract_shop_request_uri_variables() {
    $shop_base_pattern = '#/([^/]+)/([^/]+)/shop/([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}#';
    $shop_base_pattern_matches = [];
    preg_match($shop_base_pattern,$_SERVER['REQUEST_URI'],$shop_base_pattern_matches);
    if (
        array_key_exists(1,$shop_base_pattern_matches)
        && !empty($shop_base_pattern_matches[1])
        && array_key_exists(2,$shop_base_pattern_matches)
        && !empty($shop_base_pattern_matches[2])
    ) {
        $_GET['site'] = filter_var($shop_base_pattern_matches[1],FILTER_SANITIZE_STRING);
        $_GET['language'] = filter_var($shop_base_pattern_matches[2],FILTER_SANITIZE_STRING);


        //Try to max category level 5 (index 3 to 8)
        $noOfPathSegments = count($shop_base_pattern_matches);
        if ($noOfPathSegments > 8) {
            $noOfPathSegments = 8;
        }

        for ($i=3;$i<=$noOfPathSegments;$i++) {
            $levelindex = $i - 2;
            $code = filter_var(rtrim($shop_base_pattern_matches[$i],'/'),FILTER_SANITIZE_STRING);
            $_GET['slevel_' . $levelindex] = $code;
        }
    }
}

function extract_site_request_uri_variables() {
    $shop_base_pattern = '#/([^/]+)/([^/]+)/([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}#';
    $shop_base_pattern_matches = [];
    preg_match($shop_base_pattern,$_SERVER['REQUEST_URI'],$shop_base_pattern_matches);
    if (
        array_key_exists(1,$shop_base_pattern_matches)
        && !empty($shop_base_pattern_matches[1])
        && array_key_exists(2,$shop_base_pattern_matches)
        && !empty($shop_base_pattern_matches[2])
    ) {
        $_GET['site'] = filter_var($shop_base_pattern_matches[1],FILTER_SANITIZE_STRING);
        $_GET['language'] = filter_var($shop_base_pattern_matches[2],FILTER_SANITIZE_STRING);


        //Try to max category level 5 (index 3 to 8)
        $noOfPathSegments = count($shop_base_pattern_matches);
        if ($noOfPathSegments > 8) {
            $noOfPathSegments = 8;
        }

        for ($i=3;$i<=$noOfPathSegments;$i++) {
            $levelindex = $i - 2;
            $code = filter_var(rtrim($shop_base_pattern_matches[$i],'/'),FILTER_SANITIZE_STRING);
            $_GET['level_' . $levelindex] = $code;
        }
    }
}