<?php

if (!defined('ABSPATH')) {
    exit;
}

/*
|--------------------------------------------------------------------------
| Register The Composer Auto Loader
|--------------------------------------------------------------------------
|
| Composer provides a convenient, automatically generated class loader
| for our application. We just need to utilize it! We'll require it
| into the script here so we do not have to manually load any of
| our application's PHP classes. It just feels great to relax.
|
*/

use Modular\Connector\Exceptions\Handler as ExceptionHandler;
use Modular\Connector\Http\Kernel as HttpKernel;
use Modular\ConnectorDependencies\Ares\Framework\Foundation\Application;
use Modular\ConnectorDependencies\Ares\Framework\Foundation\Bootloader;
use Modular\ConnectorDependencies\Illuminate\Contracts\Debug\ExceptionHandler as IlluminateExceptionHandler;
use Modular\ConnectorDependencies\Illuminate\Contracts\Http\Kernel as IlluminateHttpKernel;
use Modular\ConnectorDependencies\Illuminate\Support\Facades\Log;
use Modular\ConnectorDependencies\Illuminate\Support\Facades\Storage;

$_autoload = __DIR__ . '/../../vendor/scoper-autoload.php';

if (!file_exists($_autoload)) {
    return false;
}

require_once $_autoload;

/**
 * @var Application $app
 */
$bootloader = Bootloader::getInstance();

function modular_connector_register_storage(Application $app)
{
    try {
        $storagePath = MODULAR_CONNECTOR_STORAGE_PATH;

        if (!file_exists($storagePath)) {
            $created = @mkdir($storagePath, 0755, true);

            if (!$created) {
                return; // If the storage path could not be created, we can't continue
            }
        }

        $subFolders = ['views', 'logs', 'cache', 'upgrades'];

        foreach ($subFolders as $subFolder) {
            $subPath = $storagePath . DIRECTORY_SEPARATOR . $subFolder;

            if (!file_exists($subPath)) {
                $created = @mkdir($subPath, 0775, true);

                if (!$created) {
                    @rmdir($storagePath . DIRECTORY_SEPARATOR . 'views'); // Remove the storage path
                    @rmdir($storagePath . DIRECTORY_SEPARATOR . 'logs'); // Remove the storage path
                    @rmdir($storagePath . DIRECTORY_SEPARATOR . 'cache'); // Remove the storage path
                    @rmdir($storagePath . DIRECTORY_SEPARATOR . 'upgrades'); // Remove the storage path
                    @rmdir($storagePath); // Remove the storage path

                    return;
                }
            }

            // Create index.php, index.html and .htaccess files
            $indexPhp = $subPath . DIRECTORY_SEPARATOR . 'index.php';
            $indexHtml = $subPath . DIRECTORY_SEPARATOR . 'index.html';
            $htaccess = $subPath . DIRECTORY_SEPARATOR . '.htaccess';

            if (!file_exists($indexPhp)) {
                @file_put_contents($indexPhp, '<?php // Silence is golden.');
            }

            if (!file_exists($indexHtml)) {
                @file_put_contents($indexHtml, '');
            }

            if (!file_exists($htaccess)) {
                @file_put_contents($htaccess, 'deny from all');
            }
        }

        // If the storage path was created, we can set it as the storage path for the application
        $app->useStoragePath($storagePath);
    } catch (\Throwable $e) {
        // Silence is golden
    }
}

function modular_connector_register_must_use_content($basename)
{
    return <<<EOF
<?php

/**
 * Plugin Name: Modular Connector Loader
 * Plugin URI: https://modulards.com/herramienta-gestion-webs/
 * Description: Automatically generated by the Modular Connector. Do not remove. It is automatically disabled when disabling the main plugin.
 * Version: 1.0.0
 * License: GPL v3.0
 * Author: Modular DS
 * Author URI: https://modulards.com/
 * Network: true
 */

if (!function_exists('untrailingslashit') || !defined('WP_PLUGIN_DIR')) {
    return;
}

if (!file_exists(untrailingslashit(WP_PLUGIN_DIR) . '/$basename')) {
    return;
}

if (
    in_array('$basename', (array)get_option('active_plugins')) ||
    function_exists('get_site_option') && array_key_exists('$basename', (array)get_site_option('active_sitewide_plugins'))
) {
    \$GLOBALS['modular_is_mu_plugin'] = true;
    
    include_once untrailingslashit(WP_PLUGIN_DIR) . '/$basename';
}
EOF;
}

function modular_connector_register_must_use(string $name)
{
    try {
        $disk = Storage::disk('mu_plugins');

        if (!is_writable($disk->path(''))) {
            return;
        }

        $path = $disk->path($name);
        $content = modular_connector_register_must_use_content(MODULAR_CONNECTOR_BASENAME);

        if ($disk->exists($name) && hash('sha256', $content) === hash_file('sha256', $path)) {
            return;
        }

        $disk->put($name, $content);
    } catch (\Throwable $e) {
        // Silence is golden
        Log::debug($e->getMessage(), [
            'file' => $e->getFile(),
            'line' => $e->getLine(),
        ]);
    }
}

$bootloader->boot(
    dirname(__DIR__),
    function (Application $app) {
        $app->singleton(IlluminateHttpKernel::class, HttpKernel::class);
        $app->singleton(IlluminateExceptionHandler::class, ExceptionHandler::class);

        modular_connector_register_storage($app);

        $app->booted(function (Application $app) {
            modular_connector_register_must_use(MODULAR_CONNECTOR_MU_BASENAME);
        });
    }
);
