<?php

namespace AtlasAiDev\Awfah\Admin;

use AtlasAiDev\Awfah\Plugin;
use AtlasAiDev\Awfah\Service\Error_Email_Notifier;
use AtlasAiDev\Awfah\Service\Error_Tracker;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

class Menu {

    /**
     * The option name in the WordPress options table.
     */
    const OPTION_NAME = 'wordpress_mcp_settings';

    /**
     * The tool states option name.
     */
    const TOOL_STATES_OPTION = 'wordpress_mcp_tool_states';

    public function __construct() {
        add_action( 'admin_menu', [ $this, 'register_menu' ] );
        add_action( 'admin_enqueue_scripts', [ $this, 'enqueue_assets' ] );
        add_action( 'admin_head', [ $this, 'menu_icon_css' ] );
    }

    /**
     * Override WP core 20px cap on SVG menu icons for our menu item.
     */
    public function menu_icon_css(): void {
        echo '<style>#adminmenu .toplevel_page_ai-workflow-automation-ai-agent-hub div.wp-menu-image.svg{background-size:27px auto}</style>';
    }

    /**
     * Get the Brain Circuit SVG icon as a base64 data URI for the admin menu.
     *
     * @return string Base64-encoded SVG data URI.
     */
    private static function get_menu_icon(): string {
        $css = '.mb{stroke-dasharray:60;stroke-dashoffset:60;animation:ab 4.5s ease infinite}'
            . '.ml{stroke-dasharray:30;stroke-dashoffset:30;animation:al 4.5s ease infinite}'
            . '@keyframes ab{0%,93%,to{stroke-dashoffset:60}27%,84%{stroke-dashoffset:0}}'
            . '@keyframes al{0%,27%,93%,to{stroke-dashoffset:30}40%,84%{stroke-dashoffset:0}}';

        $svg = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="34" height="34">'
            . '<defs><style>' . $css . '</style></defs>'
            . '<path class="mb" d="M12 2C8.5 2 6 4 6 7c-2 .5-3 2.5-3 4.5 0 2.5 1.5 4 3.5 4.5.5 2.5 2.5 4 5.5 4s5-1.5 5.5-4c2-.5 3.5-2 3.5-4.5 0-2-1-4-3-4.5C18 4 15.5 2 12 2z" fill="none" stroke="black" stroke-width="1.8"/>'
            . '<path class="ml" d="M13 6L10 12h3l-2 6" fill="none" stroke="black" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/>'
            . '</svg>';

        // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
        return 'data:image/svg+xml;base64,' . base64_encode( $svg );
    }

    public function register_menu(): void {
        add_menu_page(
            'AtlasAI Connector',
            'AtlasAI Connector',
            'manage_options',
            'ai-workflow-automation-ai-agent-hub',
            [ $this, 'render_app' ],
            self::get_menu_icon(),
            20
        );

        // ✅ Add submenus under "AtlasAI Connector"
        add_submenu_page(
            'ai-workflow-automation-ai-agent-hub', // Parent slug (must match main menu slug)
            'AtlasAI Connector', // Page title
            'AtlasAI Connector', // Menu title
            'manage_options', // Capability
            'ai-workflow-automation-ai-agent-hub', // Menu slug (same as main menu)
            [ $this, 'render_app' ] // Callback function
        );

    }

    public function render_mcp_page(): void {

        if ( ! current_user_can( 'manage_options' ) ) {
            return;
        }
        ?>
        <div class="wrap">
            <h1><?php echo esc_html( get_admin_page_title() ); ?></h1>
            <div id="awfah-settings-app"></div>
        </div>
        <?php
    }

    /**
     * Checks if WordPress Feature API is available.
     *
     * @return bool True if WP Feature API is available, false otherwise.
     */
    private function is_feature_api_available(): bool {
        return defined( 'WP_FEATURE_API_VERSION' );
    }

    public function render_app(): void {
        echo '<div id="ai-workflow-automation-ai-agent-hub-root"></div>';
    }

    public function enqueue_assets( $hook ): void {
        if ( 'toplevel_page_ai-workflow-automation-ai-agent-hub' !== $hook ) {
            return;
        }

        $js  = AWFAH_PLUGIN_URL . 'assets/js/admin-app.min.js';
        $css = AWFAH_PLUGIN_URL . 'assets/css/admin.css';

        wp_enqueue_style(
            'ai-workflow-automation-ai-agent-hub-admin',
            $css,
            [],
            AWFAH_VERSION
        );

        wp_enqueue_script(
            'ai-workflow-automation-ai-agent-hub-admin',
            $js,
            [],
            AWFAH_VERSION,
            true
        );

        $settings = Plugin::get_settings();

        $wp_roles = wp_roles();
        $roles    = [];
        foreach ( $wp_roles->get_names() as $slug => $label ) {
            $roles[] = [
                'slug'  => $slug,
                'label' => translate_user_role( $label ),
            ];
        }

        wp_localize_script(
            'ai-workflow-automation-ai-agent-hub-admin',
            'AwfahConfig',
            [
                'restUrl'          => esc_url_raw( rest_url( 'awfah/v1' ) ),
                'providersRestUrl' => esc_url_raw( rest_url( 'awfah/v1/providers' ) ),
                'abilitiesRestUrl' => esc_url_raw( rest_url( 'awfah/v1/abilities' ) ),
                'workflowsRestUrl' => esc_url_raw( rest_url( 'awfah/v1/workflows' ) ),
                'usageRestUrl'     => esc_url_raw( rest_url( 'awfah/v1/settings/usage' ) ),
                'wpNonce'          => wp_create_nonce( 'wp_rest' ),
                'version'          => apply_filters( 'awfah_version_label', AWFAH_VERSION ),
                'modules'          => $settings['modules'],
                'roles'            => $roles,
                'roleAbilities'    => $settings['role_abilities'] ?? [],
                'roleWorkflows'    => $settings['role_workflows'] ?? [],
                'isProActive'      => awfah_is_pro_active(),
                'wooActive'        => class_exists( 'WooCommerce' ),
                'oauthEnabled'     => self::is_oauth_enabled(),
                'clientConnected'  => self::has_client_ever_connected(),
                'aiApproval'       => \AtlasAiDev\Awfah\Service\AI_Provider_Manager::connector_approval_status(),
                'aiPreference'     => \AtlasAiDev\Awfah\Service\AI_Provider_Manager::get_default_preference(),
                'errorNotification' => array_merge(
                    Error_Email_Notifier::get_default_notification_settings(),
                    $settings['error_notification'] ?? []
                ),
                'adminEmail'       => get_option( 'admin_email' ),
                'logMonitor'       => Error_Email_Notifier::get_log_monitor_status(),
                'errorGroups'      => Error_Tracker::instance()->get_groups( 'count', 50 ),
                'errorTrends'      => [
                    'daily_counts' => Error_Tracker::instance()->get_daily_counts( 7 ),
                    'weekly_trend' => Error_Tracker::instance()->get_weekly_trend(),
                ],
                'backups'          => apply_filters( 'awfah_backups_list', [] ),
                'supportUrl'       => 'https://atlasaidev.com/contact-us/',
                'proUrl'           => 'https://atlasaidev.com/atlas-ai-connector-pro/?utm_source=atlas-ai-connector&utm_medium=plugin&utm_campaign=pro_upgrade&utm_content=dashboard',
            ]
        );
    }

    /**
     * Whether the OAuth server is enabled (Get started step 2).
     */
    private static function is_oauth_enabled(): bool {
        $oauth = get_option( 'awfah_oauth_settings', [] );

        return is_array( $oauth ) && ! empty( $oauth['enabled'] );
    }

    /**
     * Whether an MCP client is currently connected (Get started step 3).
     *
     * LIVE check on REFRESH tokens (user decision 2026-07-18): ticked while
     * any client could still silently reconnect — i.e. a non-revoked,
     * non-expired refresh token exists. Hourly access-token expiry does NOT
     * untick it; revoking all clients or 30 days of total silence does.
     */
    private static function has_client_ever_connected(): bool {
        global $wpdb;
        $table = $wpdb->prefix . 'awfah_oauth_tokens';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery -- admin-screen-only read of a plugin-owned table.
        $exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
        if ( $exists !== $table ) {
            return false;
        }

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $live = (int) $wpdb->get_var(
            "SELECT COUNT(*) FROM {$table} WHERE type = 'refresh' AND revoked = 0 AND expires > UTC_TIMESTAMP()"
        );

        return $live > 0;
    }
}
