<?php

//$mem_start = memory_get_usage();
//$time_start = microtime( true );

ini_set( "display_errors", "Off" );

// PHP_VERSION_ID available in PHP 5.2.7 and above
if ( ! defined( "PHP_VERSION_ID" ) ) {
    $version = explode( ".", PHP_VERSION );
    define( "PHP_VERSION_ID", ( $version[0] * 10000 + $version[1] * 100 + $version[2] ) );
}

$cms["cms_dir"] = dirname( __FILE__ );

// fix for windows
if ( DIRECTORY_SEPARATOR === "\\" ) {
    $cms["cms_dir"] = str_replace( "\\", "/", $cms["cms_dir"] );
}

$cms["site_dir"] = dirname( $cms["cms_dir"] );

if ( empty( $_SERVER["HTTPS"] ) ) {
    $protocol = "http";
} else {
    $protocol = "https";
}

// fix DocumentRoot
$_SERVER["DOCUMENT_ROOT"] = rtrim( $_SERVER["DOCUMENT_ROOT"], "/\\" );

// https://coffee-cms.com/base_path/
//                       ^         ^
$cms["base_path"] = str_replace( $_SERVER["DOCUMENT_ROOT"], "", $cms["site_dir"] ) . "/";
$base_path  = str_replace( "/", "\\/", $cms["base_path"] ); // escape / for regexp

$url = "{$protocol}://{$_SERVER['SERVER_NAME']}/" . preg_replace( "/^{$base_path}/", "", $_SERVER['REQUEST_URI'] );
$cms["url"] = parse_url( $url );
// file in .cms/ directory (for prevent sql query in pages module)
$cms["cms_file"] = $cms["cms_dir"] . $cms["url"]["path"];
$cms["url"]["path"] = substr( $cms["url"]["path"], 1 );

$cms["status"] = "404";


// Load config.php
$cms["config_file"] = "{$cms['cms_dir']}/config.php";
if ( is_file( $cms["config_file"] ) && $config_file = fopen( $cms["config_file"], "r" ) ) {
    flock( $config_file, LOCK_SH );
    include( $cms["config_file"] );
    flock( $config_file, LOCK_UN );
}

    
// Init hooks
$cms["hook"]  = "query"; // Default hook
$cms["hooks"] = array(
    "query"    => array( "next" => "template" ), 
    "template" => array( "next" => "echo"     ), 
    "echo"     => array( "next" => "write"    ), 
    "write"    => array( "next" => ""         ), 
    "admin"    => array( "next" => "template" ), 
    "api"      => array( "next" => ""         ), 
    "cron"     => array( "next" => ""         ),
);

// route array
$cms["urls"] = array();

// Load functions files
foreach( glob( $cms["cms_dir"] . "/*.fn.php" ) as $fn_file ) {
    include_once( $fn_file );
}

// Load modules
foreach( glob( $cms["cms_dir"] . "/mod/*.mod.php" ) as $module ) {
    include_once( $module );
}

// sort routes
function urls_sort( $a, $b ) {
    if ( strlen( $a ) >= strlen( $b ) )
        return -1;
    else
        return 1;
}
uksort( $cms["urls"], "urls_sort" );

// select route
foreach( $cms["urls"] as $url => $hook ) {
    $url = preg_replace( "/\//", "\\/", $url ); // Escape / for regexp
    if ( preg_match( "/{$url}/", $cms["base_path"] . $cms["url"]["path"], $cms["url"]["match"] ) ) {
        $cms["hook"] = $hook;
        break;
    }
}

// RUN
while ( ! empty( $cms["hook"] ) ) {
    do_hook( $cms["hook"] );
    $cms["hook"] = $cms["hooks"][ $cms["hook"] ]["next"];
}

// Сброс накопленной отладочной информации в файл
if ( ! empty( $cms["config"]["debug"] ) && ! empty( $cms["debug"] ) ) {
    $debug_file = $cms["cms_dir"] . "/debug.log.php";
    $new_debug = $cms["debug"];
    if ( $f = fopen( $debug_file, "r" ) ) {
        flock( $f, LOCK_SH );
        include( $debug_file );
        flock( $f, LOCK_UN );
        $cms["debug"] = array_replace_recursive( $cms["debug"], $new_debug );
    }
    file_put_contents( $debug_file, '<?php $cms["debug"] = ' . var_export( $cms["debug"], true ) . ";\n", LOCK_EX );
}

//file_put_contents( __DIR__ . "/mem.log", memory_get_usage() - $mem_start . "\n", FILE_APPEND );
//file_put_contents( __DIR__ . "/time.log", microtime( true ) - $time_start . "\n", FILE_APPEND );
