<?php

/**
 * Plugin Service Provider (Core + API)
 *
 * Combines CoreServiceProvider and ApiServiceProvider responsibilities
 * without changing behavior.
 */

namespace Licenzo\ServiceProvider;

use Licenzo\Framework\Foundation\ServiceProvider;
use Licenzo\Framework\Http\Ajax;
use Licenzo\Hooks\CLI\Commands;

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

class PluginServiceProvider extends ServiceProvider
{
    public function register()
    {
        // Register Middleware Registry
        $this->app->singleton('middleware.registry', function ($app) {
            return new \Licenzo\Framework\Http\Middleware\MiddlewareRegistry($app);
        });

        // Register Request Context
        $this->app->singleton('request.context', function ($app) {
            return new \Licenzo\Framework\Http\RequestContext();
        });

        // Register Performance Optimizer
        $this->app->singleton('performance.optimizer', function ($app) {
            return new \Licenzo\Framework\Http\Performance\Optimizer($app);
        });

        $this->registerCommands();
    }

    /**
     * Boot services (merged Core + Api boot)
     */
    public function boot()
    {
        // Register middleware from config
        $this->registerMiddleware();

        // WP hooks
        $this->initializeHooks();
    }

    /**
     * Register middleware from config
     */
    private function registerMiddleware()
    {
        $registry = $this->app->make('middleware.registry');
        $middlewares = $this->app->config('app.middlewares', []);
        $registry->register($middlewares);
    }

    /** Initialize WordPress hooks (from Core) */
    private function initializeHooks()
    {
        $this->loadCustomHooks();
    }

    /** Load custom hooks */
    private function loadCustomHooks()
    {
        $actionsFile = $this->app->basePath('src/Hooks/actions.php');

        if (file_exists($actionsFile) && is_readable($actionsFile)) {
            // Call the actions file with the app instance
            $actions = require $actionsFile;
            $actions($this->app);
        }
    }

    /** Initialize AJAX handlers (from Core) */
    private function initializeAjaxHandlers()
    {
        Ajax::setApp($this->app);
        Ajax::clearRoutes();

        $routeConfig = $this->app->getRouteConfig();
        if (isset($routeConfig['ajax'])) {
            $ajaxPath = $this->app->basePath($routeConfig['ajax']);
            if (file_exists($ajaxPath)) {
                require_once $ajaxPath;
            }
        }
    }

    public function registerCommands()
    {
        if (defined('WP_CLI') && WP_CLI) {
            \WP_CLI::add_command('licenzo', Commands::class);
        }
    }
}
