<?php

namespace PloverCRM\Modules\Automations;

use PloverCRM\Core\AbstractModule;
use PloverCRM\Core\AdminMenu;
use PloverCRM\Modules\Automations\Database\Schema;
use PloverCRM\Modules\Automations\Services\AutomationEventManager;

/**
 * Generic Automations module.
 */
class AutomationsModule extends AbstractModule
{
    protected $id = 'automations';
    protected $dependencies = [];

    public function getMetadata(): array
    {
        return [
            'name' => 'Automations',
            'description' => 'Create reusable CRM automations from templates and custom rules',
            'version' => '1.0.0',
            'author' => 'WebPlover',
            'required' => true,
        ];
    }

    public function register(): void
    {
        add_action('rest_api_init', [$this, 'registerEndpoints']);

        AdminMenu::addSubmenu(
            'plover-crm-automations',
            'Automations',
            'Automations',
            [$this, 'renderAdminPage'],
            25,
            'manage_options',
            false
        );
    }

    public function boot(): void
    {
        Schema::maybeCreateTables();

        $eventManager = new AutomationEventManager($this->container);
        $eventManager->init();
    }

    public function isEnabled(): bool
    {
        return true;
    }

    public function renderAdminPage(): void
    {
        wp_safe_redirect(home_url('/plover-crm/automations/'));
        exit;
    }

    public function registerEndpoints(): void
    {
        $this->registerModuleEndpoints([
            new Endpoints\AutomationsBootstrapEndpoint($this->container),
            new Endpoints\AutomationsEmailPreviewEndpoint($this->container),
            new Endpoints\AutomationsEndpoint($this->container),
        ]);
    }
}
