<?php
//#### START ########################################################
require(__DIR__ . "/sys/Autoload.php");

$DATA = [];
$CmsService = new CmsService(__DIR__);
$CmsService->Initialize($DATA);
$CmsDatabaseConnection = new DatabaseConnection(CMS_DB_HOSTNAME, CMS_DB_USERNAME, CMS_DB_PASSWORD, CMS_DB_DATABASE);
$CmsSiteService = new CmsSiteService($CmsDatabaseConnection);


//#### SITE ########################################################
if ($CmsDatabaseConnection->STATUS() === true) {
    $LINKS = $CmsSiteService->GetLinkData();
} else {
    $LINKS = [];
}

$DATA['SITE'] = [];
$DATA['SITE']['path'] = rawurldecode(strtok($_SERVER['REQUEST_URI'], '?')); // get path without parameters
$DATA['SITE']['basepath'] = '';
$DATA['SITE']['subpath'] = '';
$DATA['SITE']['template'] = null;
$DATA['SITE']['reference_id'] = null;
$DATA['SITE']['active_link_id'] = null;
$DATA['SITE']['title'] = null;
$DATA['SITE']['custom_settings'] = null;
$DATA['SITE']['custom_html'] = null;
$DATA['SITE']['custom_css'] = null;
$DATA['SITE']['headerscript'] = "";
$DATA['SITE']['footerscript'] = "";
$DATA['SITE']['asset_paths']['photo'] = CmsSiteService::GetAssetPath('photoaccess', '/{slug}', $LINKS); // /path/{slug}
$DATA['SITE']['asset_paths']['album'] = CmsSiteService::GetAssetPath('albumaccess', '/{slug}', $LINKS); // /path/{slug}
$DATA['SITE']['asset_paths']['article'] = CmsSiteService::GetAssetPath('articleaccess', '/{slug}', $LINKS); // /path/{slug}
$DATA['SITE']['asset_paths']['phototags'] = CmsSiteService::GetAssetPath('phototags', '/{slug}', $LINKS); // /path/{slug}
$DATA['SITE']['asset_paths']['photosearch'] = CmsSiteService::GetAssetPath('photosearch', '', $LINKS);
$DATA['SITE']['META'] = ['title' => null, 'description' => null, 'keywords' => null];
// remove website directory from $DATA['SITE']['path']
if (WEBSITE_DIRECTORY !== "" && str_starts_with($DATA['SITE']['path'], WEBSITE_DIRECTORY)) {
    $DATA['SITE']['path'] = substr($DATA['SITE']['path'], strlen(WEBSITE_DIRECTORY));
}

if (empty($LINKS)) {
    $DATA['SITE']['template'] = 'error404';
    $DATA['SITE']['basepath'] = '/error404';
}

// 1. Redirects and Adaptions
// redirect non www
if (str_contains(WEBSITE_URL, '//www.') && substr($_SERVER['HTTP_HOST'], 0, 4) !== "www.") {
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: " . strtok(WEBSITE_URL, '//www.') . "//www." . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit;
}
// redirect non https
if (str_starts_with(WEBSITE_URL, 'https://') && !CoreService::connectionHasSSL()) {
    header("HTTP/1.1 301 Moved Permanently");
    header("Location: https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']);
    exit;
}

// redirect front page
if ($DATA['SITE']['path'] === "" || $DATA['SITE']['path'] === "/") {
    $DATA['SITE']['path'] = null;
    foreach ($LINKS as $LINK) if ($LINK['frontpage'] === true) {
        //header("Location: " . $LINK['path'] . WEBSITE_TRAILINGSLASH); //exit;
        $DATA['SITE']['path'] = WEBSITE_DIRECTORY . $LINK['path'] . WEBSITE_TRAILINGSLASH;
        $DATA['SITE']['path'] = substr($DATA['SITE']['path'], strlen(WEBSITE_DIRECTORY));
        break;
    }
    if ($DATA['SITE']['path'] === null) {
        foreach ($LINKS as $LINK) if ($LINK['section'] !== 0) {
            header("Location: " . WEBSITE_URL . $LINK['path'] . WEBSITE_TRAILINGSLASH);
            exit;
        }
        $DATA['SITE']['path'] = "";
    }
}
// redirect trailing slash
if (str_ends_with($DATA['SITE']['path'], '/') !== TRAILINGSLASH) {
    if (TRAILINGSLASH) {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: " . WEBSITE_URL . $DATA['SITE']['path'] . "/");
    } else {
        header("HTTP/1.1 301 Moved Permanently");
        header("Location: " . WEBSITE_URL .  substr($DATA['SITE']['path'], 0, -1));
    }
    exit;
}
// check trailing slash
if (str_ends_with($DATA['SITE']['path'], '/') !== TRAILINGSLASH) {
    $DATA['SITE']['template'] = 'error404';
    $DATA['SITE']['basepath'] = '/error404';
}
// remove trailing slash from $DATA['SITE']['path']
if (str_ends_with($DATA['SITE']['path'], '/')) {
    $DATA['SITE']['path'] =  substr($DATA['SITE']['path'], 0, -1);
}

// 2. Path Template Matching
// check menu links [template: ...]
if ($DATA['SITE']['template'] === null) {
    foreach ($LINKS as $LINK) if ($LINK['template'] !== null) {
        if (
            $DATA['SITE']['path'] === $LINK['path'] ||
            (!in_array($LINK['template'], ['page', 'site', 'photoshowcase', 'photolanding']) && str_starts_with($DATA['SITE']['path'] . '/', $LINK['path'] . '/'))
        ) {
            $DATA['SITE']['basepath'] = $LINK['path'];
            $DATA['SITE']['subpath'] = substr($DATA['SITE']['path'], strlen($LINK['path']));
            $DATA['SITE']['template'] = $LINK['template'];
            $DATA['SITE']['reference_id'] = $LINK['reference_id'];
            $DATA['SITE']['active_link_id'] = $LINK['id'];
            $DATA['SITE']['title'] = $LINK['title'];
            $DATA['SITE']['custom_settings'] = $LINK['custom_settings'];
            $DATA['SITE']['custom_html'] = $LINK['custom_html'];
            $DATA['SITE']['custom_css'] = $LINK['custom_css'];
            CmsService::ApplySettings($DATA['SETTINGS'], CmsService::GetSettingsFromJson($DATA['SITE']['custom_settings']));
            break;
        }
    }
}
// no match found [template: error404]
if ($DATA['SITE']['template'] === null || $DATA['SITE']['template'] === 'index') {
    $DATA['SITE']['template'] = 'error404';
    $DATA['SITE']['basepath'] = '/error404';
}

// 3. Protection Check
// check url protection
if (CmsSiteService::CheckPathAccess($DATA['SITE']['path'], $DATA['SETTINGS']['PATH_PROTECTIONS']) === false) {
    $DATA['SITE']['template'] = '_password';
}

// 4. Service Starting 
$CmsPortfolioService = new CmsPortfolioService($CmsDatabaseConnection, __DIR__);
$CmsTextService = new CmsTextService($CmsDatabaseConnection);
$CmsOutputService = new CmsOutputService($DATA);
$CmsTagReplacementService = new CmsTagReplacementService($CmsOutputService, $CmsPortfolioService, __DIR__);

// 5. Content Serving 
// include template file
if (file_exists(__DIR__ . "/templates/" . $DATA['SITE']['template']  . ".php")) {
    require(__DIR__ . "/templates/{$DATA['SITE']['template']}.php");
} else {
    header("HTTP/1.1 400 Bad Request");
    echo "Template not found!";
}
