<?php

/*
|--------------------------------------------------------------------------
| Sakina front controller
|--------------------------------------------------------------------------
| This folder is the web root (upload its contents to public_html or point
| your domain here). The application itself lives in "core/", which the
| .htaccess files keep private.
*/

use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

if (file_exists($maintenance = __DIR__.'/core/storage/framework/maintenance.php')) {
    require $maintenance;
}

// First visit: create core/.env with a fresh encryption key for the installer.
if (! is_file(__DIR__.'/core/.env') && is_file(__DIR__.'/core/.env.example')) {
    $env = (string) file_get_contents(__DIR__.'/core/.env.example');
    $env = preg_replace('/^APP_KEY=.*$/m', 'APP_KEY=base64:'.base64_encode(random_bytes(32)), $env);
    if (@file_put_contents(__DIR__.'/core/.env', $env) === false) {
        http_response_code(500);
        exit('<h1>Almost there</h1><p>Make the <code>core</code> folder writable (permission 755 or 775), or copy <code>core/.env.example</code> to <code>core/.env</code>, then reload this page.</p>');
    }
}

// The PHP libraries are installed with Composer (documentation, "Install the admin panel").
if (! is_file(__DIR__.'/core/vendor/autoload.php')) {
    http_response_code(503);
    exit('<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Almost there</title>'
        .'<body style="font-family:system-ui,sans-serif;max-width:640px;margin:60px auto;padding:0 20px;line-height:1.55;color:#161a3a">'
        .'<h1>Almost there</h1><p>The admin panel\'s PHP libraries are not installed yet. Run this command in the <code>core</code> folder, '
        .'on your computer before uploading or in cPanel &gt; Terminal on the server:</p>'
        .'<pre style="background:#f3f4fa;padding:12px 14px;border-radius:8px;white-space:pre-wrap">composer install --no-dev --optimize-autoloader</pre>'
        .'<p>Then reload this page. The documentation shows each step ("Install the admin panel").</p></body>');
}

require __DIR__.'/core/vendor/autoload.php';

/** @var \Illuminate\Foundation\Application $app */
$app = require_once __DIR__.'/core/bootstrap/app.php';

$app->handleRequest(Request::capture());
