<?php
header("Content-Type: text/html; charset=utf-8");
header("X-Frame-Options: sameorigin");
header("X-XSS-Protection: 1; mode=block");
header("X-Content-Type-Options: nosniff");
header("Strict-Transport-Security: max-age=31536000");
header("Referrer-Policy: no-referrer-when-downgrade");

/*$headerCSP = "Content-Security-Policy:".
    "connect-src 'self' ;". // XMLHttpRequest (AJAX request), WebSocket or EventSource.
    "default-src 'self';". // Default policy for loading html elements
    "frame-ancestors 'self' ;". //allow parent framing - this one blocks click jacking and ui redress
    "frame-src 'none';". // vaid sources for frames
    "media-src 'self' ;". // vaid sources for media (audio and video html tags src)
    "object-src 'none'; ". // valid object embed and applet tags src
    "script-src 'nonce' ;". // allows js from self, jquery and google analytics.  Inline allows inline js
    "style-src 'nonce' ;";// allows css from self and inline allows inline css
//Sends the Header in the HTTP response to instruct the Browser how it should handle content and what is whitelisted
//Its up to the browser to follow the policy which each browser has varying support
header($headerCSP);
*/
//opcache_reset();
//ini_set('output_buffering','On');
date_default_timezone_set('Europe/Berlin');
// ini_set('display_errors',0);
// error_reporting(E_ALL);
//Vendor Autoloader
$currDir = __DIR__;
$rootDir = dirname(dirname($currDir));
$dcDir = $rootDir . '/mysyde';
include($rootDir .  '/vendor/autoload.php');


//Dc Autoloader
/*
include(rtrim($_SERVER['DOCUMENT_ROOT'],'/') . '/mysyde/DcAutoloader.php');
$dcAutoloader = new DcAutoloader();
$dcAutoloader->register();*/

//Load environment variables from config if exists
try {
    //code...

$baseDir = rtrim(dirname(__DIR__,2),'/');
$envDir = $baseDir . '/config';
$envFilePath = $envDir . '/.env';
if (is_dir($envDir) && file_exists($envFilePath) && is_file($envFilePath) && is_readable($envFilePath)) {
    $dotenv = new \Dotenv\Dotenv($envDir);
    $dotenv->load();
}

$envDirTracking = $envDir . '/tracking';
$envTrackingFilePath = $envDirTracking . '/.env';
if (is_dir($envDirTracking) && file_exists($envTrackingFilePath) && is_file($envTrackingFilePath) && is_readable($envTrackingFilePath)) {
    $dotenvTracking = new \Dotenv\Dotenv($envDirTracking);
    $dotenvTracking->load();
}

$trackingAPIRoot = getenv('TRACKING_API_ROOT');
$trackingAPIVersionString = getenv('TRACKING_API_VERSION');
$trackingAPIIndexRelPath = getenv('TRACKING_API_INDEX_FILE_PATH');
$trackingAPIIndexFilePath = $baseDir . DIRECTORY_SEPARATOR . $trackingAPIIndexRelPath;
$trackingAPIRequestURLPattern = '#\/' . $trackingAPIRoot . '\/' . $trackingAPIVersionString . '\/[^\/]+#i';


//extract_request_uri_variables();

// extract_request_uri_variables();

/* include($rootDir . '/mysyde/common/classes/GeneralErrorExceptionHandling.php');
$redirectToPath =  '/error.html';
if($_GET['language']!= "de")
{
    $redirectToPath = '/error_'.$_GET['language'].'.html';
}

$redirectMsg = 'We\'re sorry - an internal error occurred. The error has been logged and support notified. We expect the problem to be solved shorty.';


\DynCom\mysyde\common\classes\GeneralErrorExceptionHandling::setErrorHandler($redirectToPath,$redirectMsg);
\DynCom\mysyde\common\classes\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");
// mb_internal_encoding('UTF-8');

// require_once($dcDir . "/common/common_functions.inc.php");
// require_once($dcDir . "/dc-server.config.php");
// dcBasicAuth();


// require_once("frontend_functions.inc.php");

// require_once("start.inc.php");
 
// require_once("check_ip_switch.php");
// require_once("check_language_switch.php");
// if(isset($_GET['action']) && ($_GET['action'] == 'frontend_collection')){
     
//     $_GET['action'] = 'frontend_collection';
//     require_once(MODULE_PATH.'collection/edit_collection.inc.php');
     
// }else{
//     require_once($GLOBALS["layout"]["frontend_include"]);
// }

// require_once("close.inc.php");



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)
        &&  array_key_exists(2,$shop_base_pattern_matches)
        &&  !empty($shop_base_pattern_matches[1])
        &&  !empty($shop_base_pattern_matches[2])
    ) {
        $_GET['site'] = filter_var($shop_base_pattern_matches[1],FILTER_SANITIZE_STRING);
        if (empty($_GET['site'])) { $_GET['site'] = get_site_code_from_domain(); }
        $_GET['language'] = filter_var($shop_base_pattern_matches[2],FILTER_SANITIZE_STRING);
        $_GET['level_1'] = 'shop';


        //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;
            $matchedPattern = array_key_exists($i,$shop_base_pattern_matches) ? $shop_base_pattern_matches[$i] : '';
            $code = filter_var(rtrim($matchedPattern,'/'),FILTER_SANITIZE_STRING);
            if (!empty($code)) {
                $_GET['slevel_' . $levelindex] = $code;
            }
        }
    }
    if (!(strlen((string)$_GET['site']) > 0)) {
        $_GET['site'] = get_site_code_from_domain();
    }
}

function extract_site_request_uri_variables() {
    $site_base_pattern = '#/([^/]+)/([^/]+)/([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}#';
    //$site_base_pattern = '#/([^/]+)/([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}([^/]+/){0,1}#';
    $site_base_pattern_matches = [];
    preg_match($site_base_pattern,$_SERVER['REQUEST_URI'],$site_base_pattern_matches);

    if (
        array_key_exists(1,$site_base_pattern_matches)
        && !empty($site_base_pattern_matches[1])
        && array_key_exists(2,$site_base_pattern_matches)
        && !empty($site_base_pattern_matches[2])
    ) {
        $_GET['site'] = filter_var($site_base_pattern_matches[1],FILTER_SANITIZE_STRING);
        if (empty($_GET['site'])) { $_GET['site'] = get_site_code_from_domain(); }
        $_GET['language'] = filter_var($site_base_pattern_matches[2],FILTER_SANITIZE_STRING);

        $urlId = (int)substr( strrchr( $_SERVER['REQUEST_URI'], '-' ), 1 );

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

        // last number in the url is the collection id
        if($urlId > 0) {
            $noOfPathSegments -= 2;
            $_GET['collection_id'] = $urlId;
        }

        for ($i=3;$i<=$noOfPathSegments;$i++) {
            $levelindex = $i - 2;
            $matchedPattern = array_key_exists($i,$site_base_pattern_matches) ? $site_base_pattern_matches[$i] : '';
            $code = filter_var(rtrim($matchedPattern,'/'),FILTER_SANITIZE_STRING);
            if (!empty($code)) {
                $_GET['level_' . $levelindex] = $code;
            }
        }
    }
    if (!(strlen((string)$_GET['site']) > 0)) {
        $_GET['site'] = get_site_code_from_domain();
    }
   
}

function get_site_code_from_domain() {
    $prepStatement = 'SELECT id,code,is_standard_site FROM main_site WHERE site_url = :domain ORDER BY id';

    $siteDomain = $_SERVER['SERVER_NAME'];
    $siteDomain = str_replace('www.', '', $siteDomain);
    $siteCode = '';
    $dbHost = getenv('MAIN_MYSQL_DB_HOST');
    $dbPort = (int)getenv('MAIN_MYSQL_DB_PORT');
    $dbUser = getenv('MAIN_MYSQL_DB_USER');
    $dbSchema = getenv('MAIN_MYSQL_DB_SCHEMA');
    $dbPass = getenv('MAIN_MYSQL_DB_PASS');

    try {
        $pdo = new \DynCom\mysyde\common\classes\PDOQueryWrapper($dbHost,$dbPort,$dbSchema,$dbUser,$dbPass);
        $params = [
            [':domain',$siteDomain,PDO::PARAM_STR],
        ];
        $pdo->setQuery($prepStatement);
        $pdo->prepareQuery();
        $pdo->bindParameters($params);
        $pdo->executePreparedStatement();
        $resArr = $pdo->getResultArray();
        if (count($resArr) > 1) {
             foreach ($resArr as $site) {
                 if ($site["is_standard_site"] == 1) {
                     $resArr = array();
                     $resArr[0] = $site;
                     break;
                 }
             }
        }
        if (array_key_exists(0,$resArr) && array_key_exists('id',$resArr[0]) && $resArr[0]['id'] > 0) {
            $siteCode = $resArr[0]['code'];
        }
    } catch (Exception $e) {
        //Do noting
    }
    return $siteCode;
}

function check_and_redirect_tracking_api_requests($regexPattern,$tracking_index_path)
{
    $matches = [];
    $reqURI = $_SERVER['REQUEST_URI'];
    preg_match($regexPattern,$reqURI,$matches);
    if (array_key_exists(0,$matches) && file_exists($tracking_index_path) && is_file($tracking_index_path) && is_readable($tracking_index_path)) {
         include $tracking_index_path;
         exit(0);
    }
}

/* country Codes list
    http://dev.maxmind.com/geoip/legacy/codes/iso3166/
*/
function get_site_from_domain_countryCode($countryCode) {
    $prepStatement = "
      SELECT 
            id,
            code
      FROM
           main_site
      WHERE
          site_url = :domain 
            AND
              default_country_codes LIKE   CONCAT('%',:countryCode,'%')
      ORDER BY id LIMIT 1";

    $siteDomain = $_SERVER['SERVER_NAME'];
    $siteCode = '';
    $dbHost = getenv('MAIN_MYSQL_DB_HOST');
    $dbPort = (int)getenv('MAIN_MYSQL_DB_PORT');
    $dbUser = getenv('MAIN_MYSQL_DB_USER');
    $dbSchema = getenv('MAIN_MYSQL_DB_SCHEMA');
    $dbPass = getenv('MAIN_MYSQL_DB_PASS');

    try {
        $pdo = new \DynCom\mysyde\common\classes\PDOQueryWrapper($dbHost,$dbPort,$dbSchema,$dbUser,$dbPass);
        $params = [
            [':domain',$siteDomain,PDO::PARAM_STR],
            [':countryCode',$countryCode,PDO::PARAM_STR],
        ];
        $pdo->setQuery($prepStatement);
        $pdo->prepareQuery();
        $pdo->bindParameters($params);
        $pdo->executePreparedStatement();
        $resArr = $pdo->getResultArray();
        if (array_key_exists(0,$resArr) && array_key_exists('id',$resArr[0]) && $resArr[0]['id'] > 0) {
            $site = $resArr[0];
        }
    } catch (Exception $e) {
        //Do noting
    }
    return $site;
}
function get_language_by_site_id($siteId)
{

    $dbHost = getenv('MAIN_MYSQL_DB_HOST');
    $dbPort = (int)getenv('MAIN_MYSQL_DB_PORT');
    $dbUser = getenv('MAIN_MYSQL_DB_USER');
    $dbSchema = getenv('MAIN_MYSQL_DB_SCHEMA');
    $dbPass = getenv('MAIN_MYSQL_DB_PASS');

    $pdo = new \DynCom\mysyde\common\classes\PDOQueryWrapper($dbHost,$dbPort,$dbSchema,$dbUser,$dbPass);

    $prepStatement = '
              SELECT 
                id,
                code,
                name,
                std_main_navigation_id,
                related_language_codes
              FROM 
                main_language  
              WHERE 
                    main_site_id = :mainSiteId 
                  AND 
                    active = 1
               ORDER BY id   
            ';

    $params = [
        [':mainSiteId', $siteId, PDO::PARAM_STR],
    ];
    $pdo->setQuery($prepStatement);
    $pdo->prepareQuery();
    $pdo->bindParameters($params);
    $pdo->executePreparedStatement();
    $siteLanguagesArray = $pdo->getResultArray();

    return $siteLanguagesArray;

}



extract_request_uri_variables();

$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");
mb_internal_encoding('UTF-8');

require_once($dcDir . "/common/common_functions.inc.php");
require_once($dcDir . "/dc-server.config.php");
dcBasicAuth();


require_once("frontend_functions.inc.php");

require_once("start.inc.php");

if (isset($_POST["fgztiknxbhhk"])) {
    $con_user_id = $_POST["fgztiknxbhhk"];
}

if (isset($_GET["fgztiknxbhhk"])) {
    $iphone = $_GET["app"];
}
 
require_once("check_ip_switch.php");
require_once("check_language_switch.php");
if(isset($_GET['action']) && ($_GET['action'] == 'frontend_collection')){
     
    $_GET['action'] = 'frontend_collection';
    require_once(MODULE_PATH.'collection/edit_collection.inc.php');
     
}else{
    require_once($GLOBALS["layout"]["frontend_include"]);
}

require_once("close.inc.php");

} catch (\Throwable $th) {
    echo $th;
}