<?php

use Illuminate\Contracts\Http\Kernel;
use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

//防止正式域名产生预览主题连接
$_HTTP_HOST = $_SERVER['HTTP_HOST'] ?? null;
$_HTTP_METHOD = $_SERVER['REQUEST_METHOD'] ?? 'GET';

if ($_HTTP_HOST && $_HTTP_METHOD == 'GET') {
    $conditions = [
        str_contains($_HTTP_HOST, 'debug'),
        str_contains($_HTTP_HOST, 'dev'),
    ];

    $input_get = $_GET;
    $input_query = $_SERVER['QUERY_STRING'] ?? null;
    $isDebug = in_array(true, $conditions);//命中其中一个则视为Debug域名

    if (!$isDebug && !empty($input_get)) {//当前不是debug域名，且有url参数
        //移除特定参数
        foreach (['preview', 'theme_name'] as $key) {//过滤调试参数
            if (isset($input_get[$key])) unset($input_get[$key]);
        }

        $input_query_filter = http_build_query($input_get);//过滤后的地址

        if ($input_query_filter != $input_query) {
            header("HTTP/1.1 301 Moved Permanently");
            header("Location:?" . $input_query_filter);
        }
    }
}

//语种自动引导模式
$pathAutoRedirection = __DIR__ . '/../storage/app/front/auto_redirect.json';
if (file_exists($pathAutoRedirection)) {
    $fileContent = file_get_contents($pathAutoRedirection);
    if (empty($fileContent)) {
        $fileJson = json_decode($fileContent, true);
        foreach ($fileJson as $item) {
            if ($item['path'] != $_SERVER['PATH_INFO']) continue;
            //检查当前path是否一致,则操作跳转
            $type = $item['type'] ?? 302;
            header("HTTP/1.1 {$type} Moved Permanently");
            header("Location:{$item['to']}");
            return;
        }
    }
}

//图片附件处理
require_once __DIR__ . '/../bootstrap/includes/ImageHelper.php';

$imgCoverSuffix = '/webp';
if (image_url_suffix_match($imgCoverSuffix)) {//是否转到指定后缀
    $file_str_length = 0 - strlen($imgCoverSuffix);//转换后缀字符长度

    $file_real_url = substr($_SERVER['REQUEST_URI'], 0, $file_str_length);//原图路径
    $file_real_path = __DIR__ . $file_real_url;//原图路径

    $file_cover_path = image_cover_suffix($file_real_path, 'webp');//转换后路径
    $file_cover_url = str_replace(__DIR__, '', $file_cover_path);//转换后webp的url

    if (image_exist($file_cover_path) && filemtime($file_cover_path) > filemtime($file_real_path)) {//新格式图存在且比原图新
        if (!filesize($file_cover_path)) {//文件体积异常0
            header("Location:{$file_real_url}");//跳转原图

        } else {//读取webp
            header('HTTP/1.1 301 Moved Permanently'); //永久跳转
            header("Location:{$file_cover_url}");//跳转原图
            //$image = image_read($file_cover_path);
            //echo $image;
        }
        return;
    }
}

//检查访问密码
$pathSystemParams = '../storage/app/conf/system_params.json';
$systemAuthPassword = null;
if (file_exists($pathSystemParams)) {
    $systemJsonRaw = file_get_contents($pathSystemParams);
    if (!empty($systemJsonRaw)) {
        $systemJsonData = json_decode($systemJsonRaw, true);
        $systemAuthPassword = $systemJsonData['authentication_password'] ?? null;
    }
}


/**
 * 超级静态
 */
require_once __DIR__ . '/../bootstrap/includes/CacheHTMLHelper.php';

$cacheDisableConditions = [//缓存屏蔽条件
    url_is_debug(),//地址符合调试特征
    url_is_dynamic(),//动态页面
    url_auto_entry(),//开启自动引导模式
    !empty($systemAuthPassword),//已设置访问密码(则不输出缓存，让程序继续执行到密码验证页面)
];

$cacheDisableStatus = in_array(true, $cacheDisableConditions);//是否需要屏蔽缓存

if (!$cacheDisableStatus && $html = url_cache_flush()) {//输出缓存且缓存存在
    $host = $_SERVER['HTTP_HOST'];

    ## 请求头安全协议(Content-Security-Policy)
    //header("Content-Security-Policy: default-src * 'self' 'unsafe-inline' 'unsafe-eval' data: gap: content: https://ssl.gstatic.com; media-src * blob: 'self' https://* 'unsafe-inline' 'unsafe-eval'; style-src * 'self' 'unsafe-inline'; img-src * 'self' data: content:; connect-src * blob: wss: *.tawk.to; script-src 'self' ".$host." *.digood.cc *.digoodcms.com *.google.com *.googletagmanager.com *.google-analytics.com *.doubleclick.net *.jsdelivr.net *.tawk.to 'unsafe-inline' 'unsafe-eval';");

    ## 输出缓存内容
    echo $html;//默认输出现有缓存内容

    if (!url_cache_expired()) return;//缓存未过期，不需要继续执行动态生成新缓存

    define('VIEW_FLUSH_ONLY', true);//定义只渲染和生成缓存，并继续执行业务程序，而本次生成不输出到客户端留待下次访问时输出
}


/*
|--------------------------------------------------------------------------
| Check If The Application Is Under Maintenance
|--------------------------------------------------------------------------
|
| If the application is in maintenance / demo mode via the "down" command
| we will load this file so that any pre-rendered content can be shown
| instead of starting the framework, which could cause an exception.
|
*/

if (file_exists($maintenance = __DIR__ . '/../storage/framework/maintenance.php')) {
    require $maintenance;
}

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| this application. We just need to utilize it! We'll simply require it
| into the script here so we don't need to manually load our classes.
|
*/

require __DIR__ . '/../vendor/autoload.php';


/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request using
| the application's HTTP kernel. Then, we will send the response back
| to this client's browser, allowing them to enjoy our application.
|
*/

$app = require_once __DIR__ . '/../bootstrap/app.php';

$kernel = $app->make(Kernel::class);

$response = $kernel->handle(
    $request = Request::capture()
)->send();

$kernel->terminate($request, $response);
