<?php

// Laravel - A PHP Framework For Web Artisans.
define('LARAVEL_START', microtime(true));

if (file_exists('../storage/devmode') || file_exists('../rvsitebuildercms/storage/devmode')) {
    ini_set('error_reports', 'E_ALL');
    ini_set('display_errors', 'On');
}

register_shutdown_function(function () {
    //require APP_DEBUG=false
    $error = error_get_last();
    if (null !== $error) {
        if (file_exists(__DIR__.'/troubleshooting.php')) {
            include_once __DIR__.'/troubleshooting.php';
            show_solution_msg();
        }
    }
});

/*
|--------------------------------------------------------------------------
| Register The Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader for
| our application. We just need to utilize it! We'll simply require it
| into the script here so that we don't have to worry about manual
| loading any of our classes later on. It feels great to relax.
|
*/

$domainName = getDomainName();
$mainHome = getMainHome();

//TODO virtualhost homepath (find /home/amarin)
//require __DIR__.'/../vendor/autoload.php';
//set_include_path('.:..:/opt/cpanel/ea-php71/root/usr/share/pear');

$domainAppPath = $mainHome.'/rvsitebuildercms/'.$domainName;

if (is_dir($mainHome . '/rvsitebuildercms')) {
    if (is_dir($mainHome . '/rvsitebuildercms/' . $domainName)) {
        $domainAppPath = $mainHome . '/rvsitebuildercms/' . $domainName;
    } else {
        if (is_dir($mainHome . '/rvsitebuildercms/localhost')) {
            $domainAppPath = $mainHome . '/rvsitebuildercms/localhost';
        }
    }
}

if (file_exists($domainAppPath.'/vendor/autoload.php')) {
    // Should load as a first autoload to allow package to have its own vendor package
    // but different version than the framework vendor
    require $domainAppPath.'/vendor/autoload.php';

    //TODO 1: Cached?

    //TODO 2: load only ENABLED app vendor according to
    // $vendor_names = enabled app, should not scandir()
    $packagesPath = $domainAppPath.'/packages';
    $vendor_names = scandir($packagesPath);

    foreach ($vendor_names as $vendor_name) {
        if (preg_match("/^\./", $vendor_name)) {
            continue;
        }
        if (is_file($packagesPath.'/'.$vendor_name)) {
            continue;
        }
        $package_names = scandir($packagesPath.'/'.$vendor_name);

        //  $package_names = [];
        //  $package_names = ['scheduler'];
        //$package_names = ['filemanager'];
        //$package_names = ['filemanager', 'scheduler'];

        foreach ($package_names as $package_name) {
            if (preg_match("/^\./", $package_name)) {
                continue;
            }
            if (is_file($packagesPath.'/'.$vendor_name.'/'.$package_name)) {
                continue;
            }
            $auto_load_file = $packagesPath.'/'.$vendor_name.'/'.$package_name.'/vendor/autoload.php';

            //echo "$package_name <br/>";
            if (is_file($auto_load_file)) {
                //echo '<h2>' . $auto_load_file . '</h2>';
                require $auto_load_file;
            }
        }
        //exit;
    }
    // echo '<pre>';
    // print_r(spl_autoload_functions());
    // echo '</pre>';
    // exit;
} else {
    echo '<h1>Not found RVSiteBuilder CMS App in '.get_include_path().'<h1>';
    echo '<pre>
Please contact your provider with info:
1. RVSitebuilder CMS App have not install.
2. Not found vendor path.
3. Your PHP version not compatible, Our system require PHP 7.1+
</pre>';
    exit;
}

/*
|--------------------------------------------------------------------------
| Turn On The Lights
|--------------------------------------------------------------------------
|
| We need to illuminate PHP development, so let us turn on the lights.
| This bootstraps the framework and gets it ready for use, then it
| will load up this application so that we can run it and send
| the responses back to the browser and delight our users.
|
*/

//$app = require_once __DIR__.'/../bootstrap/app.php';
$app = require_once $domainAppPath.'/bootstrap/app.php';

/*
|--------------------------------------------------------------------------
| Run The Application
|--------------------------------------------------------------------------
|
| Once we have the application, we can handle the incoming request
| through the kernel, and send the associated response back to
| the client's browser allowing them to enjoy the creative
| and wonderful application we have prepared for them.
|
*/

$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);

$response = $kernel->handle(
    $request = Illuminate\Http\Request::capture()
);

$response->send();

$kernel->terminate($request, $response);

function file_exists_include_path($include_file)
{
    $included_path_lists = explode(':', get_include_path());
    $found = 0;
    foreach ($included_path_lists as $include_path) {
        if (file_exists($include_path.'/'.$include_file)) {
            $found = 1;
            break;
        }
    }

    return $found;
}

function getMainHome()
{
    $user_path = '';
    $document_root = $_SERVER['DOCUMENT_ROOT'];
    $user_paths = [];
    $open_basedir_paths = get_open_basedir_paths();
    if (count($open_basedir_paths)) {
        $user_paths = $open_basedir_paths;
    }

    if (isset($_SERVER['HOME'])) {
        if (!in_array($_SERVER['HOME'], $user_paths)) {
            array_push($user_paths, $_SERVER['HOME']);
        }
    }
    $posix_user_path = '';
    if (function_exists('posix_getuid')) {
        $webuid = posix_getuid();
        $userinfo = posix_getpwuid($webuid);
        if (is_dir($userinfo['dir'])) {
            if (!in_array($userinfo['dir'], $user_paths)) {
                array_push($user_paths, $userinfo['dir']);
            }
        }
    }
    // case  have posix_getpwuid get uid by owner dir
    if (function_exists('posix_getpwuid')) {
        $stat = stat($document_root);
        $userinfo = posix_getpwuid($stat['uid']);
        if (is_dir($userinfo['dir'])) {
            if (!in_array($userinfo['dir'], $user_paths)) {
                array_push($user_paths, $userinfo['dir']);
            }
        }
        $userinfo = posix_getpwuid($stat['gid']);
        if (is_dir($userinfo['dir'])) {
            if (!in_array($userinfo['dir'], $user_paths)) {
                array_push($user_paths, $userinfo['dir']);
            }
        }
    }
    // case  find home path from document_root ( /home/amarin/public_html => /home/amarin )
    if ($posix_user_path == '') {
        $paths = preg_split("/\//", $document_root);
        $loop_dim = count($paths);
        for ($i = 0; $i < $loop_dim; ++$i) {
            $test_path = implode('/', $paths);
            if (is_dir($test_path)) {
                if (!in_array($test_path, $user_paths)) {
                    array_push($user_paths, $test_path);
                }
            }
            array_pop($paths);
        }
    }

    foreach ($user_paths as $user_path_var) {
        if (is_file($user_path_var)) {
            continue;
        }
        if ($user_path_var == $document_root) {
            continue;
        }
        if (preg_match("/(^\/tmp)|(\/tmp$)/", $user_path_var)) {
            continue;
        }
        if (preg_match("/\/session/", $user_path_var)) {
            continue;
        }
        if (is_writable($user_path_var)) {
            $user_path = $user_path_var;
            break;
        }
    }

    return $user_path;
}

function get_open_basedir_paths()
{
    $open_basedir_paths = [];
    if (function_exists('ini_get')) {
        $open_basedir_str = ini_get('open_basedir');
        $open_basedir_str = trim($open_basedir_str);
        if ($open_basedir_str != '') {
            $open_basedir_str = strtolower($open_basedir_str);
            $open_basedir_paths = explode(':', $open_basedir_str);
        }
    }

    return $open_basedir_paths;
}

function getDomainName()
{
    $domainName = '';

    if (PHP_SAPI === 'cli') {
        if (posix_getuid() != 0) {
            $paths = preg_split("/\//", dirname(__DIR__));
            $domainName = array_pop($paths);
        }
    } else {
        $parts = parse_url($_SERVER['HTTP_HOST']);
        if (isset($parts['path'])) {
            $domainName = $parts['path'];
        }
        if (isset($parts['host'])) {
            $domainName = $parts['host'];
        }
    }
    //$domainName = preg_replace('/^www\./i', '',$domainName);
    return $domainName;
}

function getFrameworkVendorPath($filePath = '')
{
    $vendorDir = realpath(dirname($filePath).'/../../../../../').'/vendor';

    return $vendorDir;
}

function getPackageBaseDir($filePath = '')
{
    $baseDir = realpath(dirname($filePath).'/../../');

    return $baseDir;
}
