<?php

require_once __DIR__ . '/system/libs/Env.php';
require_once __DIR__ . '/system/libs/TenantResolver.php';
require_once __DIR__ . '/system/libs/RobotsRenderer.php';
require_once __DIR__ . '/system/libs/SitemapRenderer.php';

Env::load(__DIR__ . '/system/libs/.env');

$host = normalizeHost($_SERVER['HTTP_HOST'] ?? '');
$uri  = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';

/*
|--------------------------------------------------------------------------
| Apex custom domain -> www redirect
|--------------------------------------------------------------------------
|
| skychoose.com      -> www.skychoose.com
| elifreizen.nl      -> www.elifreizen.nl
|
| Ama:
| demo.acenteyazilim.com  -> redirect olmaz
| sub.skychoose.com       -> redirect olmaz
| www.skychoose.com       -> redirect olmaz
|
*/
if (shouldRedirectApexToWww($host)) {
    redirectApexToWww($host);
}

/*
|--------------------------------------------------------------------------
| Lookup host
|--------------------------------------------------------------------------
|
| www.skychoose.com      -> skychoose.com
| skychoose.com          -> skychoose.com
| sub.skychoose.com      -> sub.skychoose.com
| demo.acenteyazilim.com -> demo.acenteyazilim.com
|
*/
$lookupHost = getLookupHost($host);

$tenant = getTenant($lookupHost);

if (!$tenant || !is_array($tenant)) {
    showProjectNotFound();
}

applyTenantTimezone($tenant);

/*
|--------------------------------------------------------------------------
| Domain type and tenant rules
|--------------------------------------------------------------------------
*/
validateDomainType($tenant, $host);
runTenantRules($tenant);

/*
|--------------------------------------------------------------------------
| Active tenant constants
|--------------------------------------------------------------------------
*/
define('TENANT_ID', (int)$tenant['id']);
define('THEME', (string)$tenant['theme_code']);
define("DOMAIN",$tenant['company_domain_name']);

$activePortal = is_array($tenant['portal'] ?? null) ? $tenant['portal'] : [];
$activePortalPolicy = is_array($activePortal['accessPolicy'] ?? null) ? $activePortal['accessPolicy'] : [];
$GLOBALS['ACTIVE_PORTAL'] = $activePortal;

define('PORTAL_ID', (int)($activePortal['id'] ?? 0));
define('PORTAL_MODE', strtolower(trim((string)($activePortal['mode'] ?? 'b2c'))));
define('PORTAL_THEME_ID', (int)($activePortal['themeId'] ?? 0));
define('ACTIVE_PORTAL_DOMAIN', strtolower(trim((string)($activePortal['domain'] ?? $lookupHost))));
define('PORTAL_REGISTRATION_MODE', strtolower(trim((string)($activePortal['registrationMode'] ?? 'inherit'))));
define('PORTAL_REQUIRES_AUTHENTICATION', !empty($activePortalPolicy['requiresAuthentication']));
define('PORTAL_REQUIRES_TRADE_ACCOUNT', !empty($activePortalPolicy['requiresTradeAccount']));
define('PORTAL_REQUIRES_CORPORATE_CONTEXT', !empty($activePortalPolicy['requiresCorporateContext']));
/*
|--------------------------------------------------------------------------
| Special files
|--------------------------------------------------------------------------
*/
if ($uri === '/robots.txt') {
    if (PORTAL_ID > 0 && PORTAL_MODE !== 'b2c') {
        header('Content-Type: text/plain; charset=utf-8');
        header('X-Robots-Tag: noindex, nofollow', true);
        echo "User-agent: *\nDisallow: /\n";
        exit;
    }

    $robots = '/var/www/themes/' . THEME . '/robots.php';

    if (is_file($robots)) {
        require $robots;
    } else {
        renderRobotsFile((int)TENANT_ID);
    }

    exit;
}

if ($uri === '/sitemap.xml' || preg_match('#^/sitemap/([a-z0-9][a-z0-9._-]*\.xml)$#i', $uri, $sitemapMatch)) {
    if (PORTAL_ID > 0 && PORTAL_MODE !== 'b2c') {
        header('X-Robots-Tag: noindex, nofollow', true);
        http_response_code(404);
        exit;
    }

    $sitemap = '/var/www/themes/' . THEME . '/sitemap.php';

    if ($uri === '/sitemap.xml' && is_file($sitemap)) {
        require $sitemap;
    } else {
        renderSitemapXml((int)TENANT_ID, $sitemapMatch[1] ?? '');
    }

    exit;
}

if ($uri === '/manifest.json' || isset($_GET['ay_manifest'])) {
    $tenantDomain = strtolower((string) ($tenant['company_domain_name'] ?? ''));
    $tenantSlug = '';

    if ($tenantDomain !== '') {
        $tenantParts = explode('.', $tenantDomain);
        $tenantSlug = trim((string) ($tenantParts[0] ?? ''));
    }

    $manifestStatic = $tenantSlug !== ''
        ? '/var/www/static/' . $tenantSlug . '/images/companylogo/manifest.json'
        : null;

    $statusProtocol = $_SERVER['SERVER_PROTOCOL'] ?? 'HTTP/1.1';
    http_response_code(200);
    header('Status: 200 OK', true, 200);
    header($statusProtocol . ' 200 OK', true, 200);
    header('Content-Type: application/manifest+json; charset=utf-8');

    if ($manifestStatic && is_file($manifestStatic)) {
        readfile($manifestStatic);
        exit;
    }

    $iconBase = $tenantSlug !== ''
        ? 'https://static.acenteyazilim.com/' . $tenantSlug . '/images/companylogo'
        : '';
    $tenantName = trim((string)($tenant['company_name'] ?? $tenantDomain ?: 'Acenta Yazilim'));
    $manifest = [
        'name' => $tenantName,
        'short_name' => $tenantName,
        'start_url' => '/',
        'scope' => '/',
        'display' => 'standalone',
        'background_color' => '#ffffff',
        'theme_color' => '#ffffff',
        'icons' => [],
    ];

    if ($iconBase !== '') {
        $manifest['icons'] = [
            [
                'src' => $iconBase . '/android-chrome-192x192.png',
                'sizes' => '192x192',
                'type' => 'image/png',
            ],
            [
                'src' => $iconBase . '/android-chrome-512x512.png',
                'sizes' => '512x512',
                'type' => 'image/png',
            ],
        ];
    }

    echo json_encode($manifest, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT);
    exit;
}

if ($uri === '/favicon.ico') {
    $tenantDomain = strtolower((string) ($tenant['company_domain_name'] ?? ''));
    $faviconStatic = null;

    if ($tenantDomain !== '') {
        $tenantParts = explode('.', $tenantDomain);
        $tenantSlug = trim((string) ($tenantParts[0] ?? ''));
        if ($tenantSlug !== '') {
            $faviconStatic = '/var/www/static/' . $tenantSlug . '/images/companylogo/favicon.ico';
        }
    }

    if ($faviconStatic && is_file($faviconStatic)) {
        header('Content-Type: image/x-icon');
        readfile($faviconStatic);
        exit;
    }

    $favicon = '/var/www/themes/' . THEME . '/favicon.ico';

    if (is_file($favicon)) {
        header('Content-Type: image/x-icon');
        readfile($favicon);
    } else {
        http_response_code(404);
    }

    exit;
}

/*
|--------------------------------------------------------------------------
| Autoload
|--------------------------------------------------------------------------
*/
spl_autoload_register(function ($class) {
    $file = __DIR__ . '/system/libs/' . $class . '.php';

    if (is_file($file)) {
        require_once $file;
    }
});

/*
|--------------------------------------------------------------------------
| Application bootstrap
|--------------------------------------------------------------------------
*/
$boot = new Bootstrap();

if (isset($_GET['announcement'])) {
    header('HTTP/1.1 410 Gone');
    exit;
}

include_once __DIR__ . '/app/otherClasses/SchemaBuilder.php';
include_once __DIR__ . '/app/otherClasses/OGBuilder.php';
include_once __DIR__ . '/app/otherClasses/SEOBuilder.php';
include_once __DIR__ . '/app/config/config.php';
include_once __DIR__ . '/app/config/func.php';

$boot->run();
