<?php
$app_url = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$app_url = str_replace('/install/setup.php', '', $app_url);

$main_dir = (str_replace(DIRECTORY_SEPARATOR.'public'.DIRECTORY_SEPARATOR.'install', '',__DIR__).DIRECTORY_SEPARATOR);
if(file_exists($main_dir.'storage/app/installed')) {
    echo "<meta http-equiv=\"refresh\" content=\"0;URL='{$app_url}'\" />";
    die;
}

// Function to check if a PHP extension is loaded
function checkExtension($extension)
{
    return extension_loaded($extension) ? "✅ $extension" : "❌ $extension";
}

// Check PHP version
echo "<h5 style='color: #FEC91E'>PHP Version: " . PHP_VERSION . "</h5>";
if (version_compare(PHP_VERSION, '8.1.0', '>=')) {
    echo "<div col-md-12> ✅ PHP version is compatible with Relayzo</div>";
} else {
    echo "<div col-md-12> ❌ PHP version is not compatible with Relayzo. Requires PHP 8.1 or higher.</div>";
}

// Check required PHP extensions
echo "<br><h5 style='color: #FEC91E'>PHP Extensions:</h5>";
$extensions = [
    'bcmath',
    'ctype',
    'curl',
    'fileinfo',
    'json',
    'mbstring',
    'openssl',
    'pdo',
    'tokenizer',
    'xml',
    'imap',
    'zip'
];

echo "<div class='row'>";
foreach ($extensions as $extension) {
    echo "<div class='col-md-2'>".checkExtension($extension) . "</div>";
}
echo "</div>";


// Function to check file_folder permissions
function checkPermissions($key, $file_folder)
{
    $isWritable = is_writable($file_folder);
    $isReadable = is_readable($file_folder);

    $str = "<div class='col-md-3'>";
    $str .= sprintf(
        "<h5>%s</h5> %s Read %s Write<br>",
        $key,
        $isReadable ? "✅ " : "❌ ",
        $isWritable ? "✅ " : "❌ "
    );
    $str.= "</div>";
    return $str;
}

// Check file_folder permissions
echo "<br><h5 style='color: #FEC91E'>Files & Folders Permissions:</h5>";
$files_folders = [
    '.env' => base_path('../../.env'),
    'storage' => base_path('../../storage'),
    'bootstrap/cache' => base_path('../../bootstrap/cache'),
    'public/images' => base_path('../../public/images')
];

echo "<div class='row'>";
foreach ($files_folders as $key => $file_folder) {
    echo checkPermissions($key, $file_folder);
}
echo "</div>";

/**
* Helper functions
*/
function base_path($path = '')
{
    return __DIR__ . ($path ? DIRECTORY_SEPARATOR . $path : $path);
}


?>