<?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', 'scans'];

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

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

                if (!$created) {
                    foreach ($subFolders as $cleanup) {
                        @rmdir($storagePath . DIRECTORY_SEPARATOR . $cleanup);
                    }
                    @rmdir($storagePath);

                    return;
                }
            }

            // Protect each subfolder against directory listing and direct access
            // (Apache/Nginx via .htaccess + index files, IIS via web.config).
            $protectors = [
                'index.php' => '<?php // Silence is golden.',
                'index.html' => '',
                '.htaccess' => 'deny from all',
                'web.config' => '<configuration><system.webServer><authorization><deny users="*" /></authorization></system.webServer></configuration>',
            ];

            foreach ($protectors as $name => $content) {
                $file = $subPath . DIRECTORY_SEPARATOR . $name;

                if (!file_exists($file)) {
                    @file_put_contents($file, $content);
                }
            }
        }

        // 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);
        });
    }
);
