<?php
/**
 * Application Bootstrapper
 *
 * @package Licenzo
 */

namespace Licenzo\Boot;

use Licenzo\Hooks\Handler\Terminate;
use Licenzo\ServiceProvider\EventServiceProvider;
use Licenzo\ServiceProvider\PluginServiceProvider;
use Licenzo\ServiceProvider\AppServiceProvider;
use Licenzo\Framework\Foundation\Application;
use Licenzo\ServiceProvider\RouteServiceProvider;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

/**
 * Bootstrap the application
 *
 * @return void
 *
 */
return function ($dir) {

    $config = [
        'debug'              => defined('WP_DEBUG') && WP_DEBUG,
        'root_path'          => LICENZO_PLUGIN_DIR,
        'providers'          => [
            AppServiceProvider::class,
            PluginServiceProvider::class,
            EventServiceProvider::class,
            RouteServiceProvider::class,
        ],
        'exception_handlers' => [\Licenzo\Framework\Exceptions\Handler::class],
    ];

    $licenzoBootConfig = apply_filters('licenzo_bootstrap_config', $config);
    $licenzoTerminators = apply_filters('licenzo_terminators', [Terminate::class]);

    $app = Application::configure($licenzoBootConfig)
        ->after(function (Application $app) {
            do_action('licenzo_before_bindings_loaded', $app);
            $bindings = require __DIR__ . '/bindings.php';
            $bindings($app);
            do_action('licenzo_after_bindings_loaded', $app);
        })
        ->create()
    ;

    // Register terminate handlers
    $app->terminator($licenzoTerminators);

    add_action('plugins_loaded', function () use ($app) {
        do_action('licenzo_loaded', $app);
    });

    // Register WordPress shutdown hook (Application Layer)
    add_action('shutdown', function () use ($app) {
        // Get context to check if we have request/response
        $context = $app->make('request.context');

        if ($context->hasContext()) {
            // Fire WordPress hook before termination
            do_action('licenzo_shutdown', $context->getRequest(), $context->getResponse());
        }

        // Execute framework termination
        $app->terminate();
    }, 999);

    register_activation_hook($dir, function () use ($app, $dir) {
        // Check minimum PHP version
        if (version_compare(PHP_VERSION, '8.0', '<')) {
            deactivate_plugins(plugin_basename($dir));
            wp_die(
                esc_html__('Licenzo requires PHP 8.0 or higher. Your server is running PHP ', 'licenzo') . PHP_VERSION,
                esc_html__('Plugin Activation Error', 'licenzo'),
                ['back_link' => true]
            );
        }

        // Check minimum WordPress version
        global $wp_version;
        if (version_compare($wp_version, '5.0', '<')) {
            deactivate_plugins(plugin_basename($dir));
            wp_die(
                esc_html__('Licenzo requires WordPress 5.0 or higher.', 'licenzo'),
                esc_html__('Plugin Activation Error', 'licenzo'),
                ['back_link' => true]
            );
        }

        $activationHandler = $app->make(\Licenzo\Hooks\Handler\Plugin\ActivationHandler::class);
        $activationHandler->handle();
    });

    register_deactivation_hook($dir, function () {
        wp_clear_scheduled_hook('licenzo_cron_daily');
        wp_clear_scheduled_hook('licenzo_cron_hourly');
        wp_clear_scheduled_hook('licenzo_process_renewals');
        wp_clear_scheduled_hook('licenzo_check_dunning');
        wp_clear_scheduled_hook('licenzo_check_expiring_licenses');
    });
};
