<?php

namespace PloverCRM\Modules\AdminSettings;

use PloverCRM\Core\AbstractModule;
use PloverCRM\Core\AdminMenu;

/**
 * Admin Settings Module
 * 
 * Handles all admin settings pages and tabs
 */
class AdminSettingsModule extends AbstractModule
{
    public const APP_SETTINGS_MENU_SLUG = 'plover-crm-settings';
    public const ADMIN_SETTINGS_MENU_SLUG = 'plover-crm-admin-settings';

    protected $id = 'admin_settings';
    protected $dependencies = [];

    /**
     * {@inheritdoc}
     */
    public function getMetadata(): array
    {
        return [
            'name' => 'Admin Settings',
            'description' => 'Core admin settings and configuration',
            'version' => '1.0.0',
            'author' => 'WebPlover',
            'icon' => '⚙️',
            'required' => true, // This module cannot be disabled
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function register(): void
    {
        $moduleManagerTab = new Tabs\ModuleManagerTab();
        $moduleManagerTab->register();

        // Determine priority based on the built-in CRM status
        // When Built-in CRM is disabled, Settings should be first (priority 5)
        // When Built-in CRM is active, Settings should be last (priority 100)
        $disabledModules = get_option('plover_crm_disabled_modules', []);
        $isNativeCRMActive = !in_array('native_crm', $disabledModules);
        $priority = $isNativeCRMActive ? 100 : 5;

        // Register settings submenu via centralized AdminMenu
        AdminMenu::addSubmenu(
            self::APP_SETTINGS_MENU_SLUG,
            'Settings',
            'Settings',
            [$this, 'renderAppSettingsPage'],
            $priority,
            'manage_options',
            false
        );

        AdminMenu::addSubmenu(
            self::ADMIN_SETTINGS_MENU_SLUG,
            'Admin Settings',
            'Admin Settings',
            [$this, 'renderAdminPage'],
            $priority + 1
        );
    }

    /**
     * {@inheritdoc}
     */
    public function boot(): void
    {
        // Boot logic if needed
    }

    /**
     * {@inheritdoc}
     */
    public function isEnabled(): bool
    {
        // Admin settings should always be available
        // Don't check CRM availability as it would block access to settings
        return true;
    }

    public static function renderAppSettingsPageStatic(): void
    {
        $instance = new self(new \PloverCRM\Core\Container());
        $instance->renderAppSettingsPage();
    }

    public function renderAppSettingsPage(): void
    {
        $targetUrl = $this->resolveAppSettingsTargetUrl();

        wp_safe_redirect($targetUrl);
        exit;
    }

    private function resolveAppSettingsTargetUrl(): string
    {
        $section = sanitize_key($_GET['section'] ?? '');
        $tab = sanitize_key($_GET['tab'] ?? '');

        $routeMap = [
            'users' => home_url('/plover-crm/settings/users/'),
            'roles' => home_url('/plover-crm/settings/roles/'),
            'access' => home_url('/plover-crm/settings/access/'),
            'crm' => home_url('/plover-crm/settings/crm/'),
            'custom-fields' => home_url('/plover-crm/settings/custom-fields/'),
            'display' => home_url('/plover-crm/settings/display/'),
            'notifications' => home_url('/plover-crm/settings/notifications/'),
            'business' => home_url('/plover-crm/settings/business/'),
            'stages' => home_url('/plover-crm/settings/stages/'),
            'workspaces' => home_url('/plover-crm/settings/workspaces/'),
        ];

        if ($section !== '' && isset($routeMap[$section])) {
            return $routeMap[$section];
        }

        if ($tab !== '' && isset($routeMap[$tab])) {
            return $routeMap[$tab];
        }

        return home_url('/plover-crm/settings/');
    }

    /**
     * Render admin page
     */
    public function renderAdminPage(): void
    {
        $requestedTab = sanitize_text_field($_GET['tab'] ?? '');

        echo '<div class="wrap">';
        echo '<h1>PloverCRM Admin Settings</h1>';
        echo '<p class="description">Only technical and system-level tools live here. CRM/product configuration now happens in the full-screen app.</p>';
        echo '<p>';
        echo '<a class="button button-primary" href="' . esc_url(home_url('/plover-crm/settings/')) . '">Open App Settings</a> ';
        echo '<a class="button" href="' . esc_url(home_url('/plover-crm/settings/users/')) . '">Open CRM Users</a>';
        echo ' <a class="button" href="' . esc_url(home_url('/plover-crm/settings/roles/')) . '">Open CRM Roles</a>';
        echo '</p>';

        $tabs = [
            'modules' => 'Module Manager',
        ];

        // Set default tab
        $default_tab = array_key_first($tabs) ?: 'modules';
        $active_tab = $requestedTab ?: $default_tab;

        if (!isset($tabs[$active_tab])) {
            $active_tab = $default_tab;
        }

        // Render tabs
        echo '<h2 class="nav-tab-wrapper">';
        foreach ($tabs as $tab_key => $tab_label) {
            $active_class = ($active_tab === $tab_key) ? 'nav-tab-active' : '';
            $tab_url = admin_url('admin.php?page=' . self::ADMIN_SETTINGS_MENU_SLUG . '&tab=' . $tab_key);
            echo '<a href="' . esc_url($tab_url) . '" class="nav-tab ' . esc_attr($active_class) . '">' . esc_html($tab_label) . '</a>';
        }
        echo '</h2>';

        // Render tab content
        // Some tabs need the WordPress settings form, others don't
        $tabsWithSettingsForm = ['modules'];

        if (in_array($active_tab, $tabsWithSettingsForm)) {
            echo '<form method="post" action="options.php">';
        }

        settings_fields('plover_crm_module_manager_settings');
        do_settings_sections('plover_crm_module_manager');

        if (in_array($active_tab, $tabsWithSettingsForm)) {
            echo '</form>';
        }
        echo '</div>';
    }
}
