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

namespace ZenoChatbot\Boot;

use ZenoChatbot\ServiceProvider\PluginServiceProvider;
use ZenoChatbot\ServiceProvider\AppServiceProvider;
use ZenoChatbot\Framework\Foundation\Application;
use ZenoChatbot\Framework\Http\Request;
use ZenoChatbot\Services\Scheduler\Scheduler;
use ZenoChatbot\Support\Hooks;

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

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

    static $app = null;
    $bindings = require __DIR__ . '/bindings.php';

    if ($app === null) {
        // Create the application using fluent configuration
        $app = Application::configure(ZENOCHATBOT_PLUGIN_DIR)
            ->withRequest(Request::capture())
            ->exceptions(\ZenoChatbot\Framework\Exceptions\Handler::class)
            ->debug(defined('WP_DEBUG') && WP_DEBUG)
            ->providers([
                AppServiceProvider::class,
                PluginServiceProvider::class,
            ])
            ->create()
        ;

        // Configure routes
        $routes = [
            'api' => 'src/routes/api.php',
            'ajax' => 'src/routes/ajax.php'
        ];

        $routes = Hooks::applyFilters(Hooks::CORE_ROUTES, $routes);
        $app->routes($routes);


    }

    add_action('plugins_loaded', function() use ($app) {
        Hooks::doAction(Hooks::CORE_LOADED, $app);
    });

    // Apply custom bindings
    Hooks::doAction(Hooks::CORE_BINDINGS_LOADING, $app);
    $bindings($app);
    Hooks::doAction(Hooks::CORE_BINDINGS_LOADED, $app);

    register_activation_hook($dir, function() use ($app, $dir) {
        $activationHandler = $app->make(\ZenoChatbot\Hooks\Handler\Plugin\ActivationHandler::class);
        $activationHandler->handle();
    });


    add_action('shutdown', function() use ($app) {
        $app->terminate();
    });

    add_filter('wp_plugin_check_ignore_directories', function($excluded_directories){
        // add scheduler into ignored directories
        $excluded_directories[] = 'scoped-vendor';
        return $excluded_directories;
    });

    // Action Scheduler init
    Scheduler::boot();

    return $app;
};
