<?php

declare(strict_types=1);

namespace FleekDash\Admin\Menu;

// Load debug helpers
if (!function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

/**
 * Menu Helpers
 *
 * Utility methods for menu operations
 *
 * @package FleekDash\Admin\Menu
 */
class MenuHelpers
{
    /**
     * Extract update count from menu text HTML
     *
     * @param string $text Menu text with HTML
     * @return int Update count
     */
    public static function getUpdateCount(string $text): int
    {
        // Static cache to prevent duplicate logs for the same text
        static $logged_texts = [];
        static $cache = [];

        // Use cache to avoid reprocessing same text
        $text_hash = md5($text);
        if (isset($cache[$text_hash])) {
            return $cache[$text_hash];
        }

        $patterns = [
            '/<span[^>]*class="update-plugins[^"]*"[^>]*>(\d+)<\/span>/',
            '/<span[^>]*class="awaiting-mod[^"]*"[^>]*>(\d+)<\/span>/',
            '/<span[^>]*class="update-count[^"]*"[^>]*>(\d+)<\/span>/',
            '/<span[^>]*class="[^"]*count[^"]*"[^>]*>(\d+)<\/span>/',
        ];

        foreach ($patterns as $pattern) {
            if (preg_match($pattern, $text, $matches)) {
                $count = intval($matches[1]);
                $cache[$text_hash] = $count;
                return $count;
            }
        }

        // Only log if text contains numbers AND it's not clearly a false positive
        // False positives: version numbers (v2, v1.0), codes (EA4V), etc.
        if (preg_match('/\d+/', $text)) {
            // Check if it's a false positive (version numbers, codes, etc.)
            $is_false_positive = preg_match('/\b(v|version|ver\.?)\s*\d+/i', $text) || // v2, version 1.0
                                 preg_match('/\b[A-Z]{2,}\d+/', $text) || // EA4V, ABC123
                                 preg_match('/\d+[A-Z]{2,}/', $text) || // 4V, 123ABC
                                 preg_match('/\b\d+\.\d+/', $text); // 1.0, 2.5 (version numbers)

            // Only log if it's NOT a false positive and we haven't logged this text before
            if (!$is_false_positive && !isset($logged_texts[$text_hash])) {
                $logged_texts[$text_hash] = true;
                fleekdash_log_debug('[AdminMenu] No update count pattern matched, but text contains numbers: ' . substr($text, 0, 100));
            }
        }

        $cache[$text_hash] = 0;
        return 0;
    }

    /**
     * Get new content items for toolbar
     *
     * @return array New content items
     */
    public static function getNewContentItems(): array
    {
        $items = array();
        $admin_url = \admin_url();

        $default_items = array(
            array(
                'text' => 'Post',
                'url' => $admin_url . 'post-new.php',
                'icon' => 'post',
            ),
            array(
                'text' => 'Media',
                'url' => $admin_url . 'media-new.php',
                'icon' => 'media',
            ),
            array(
                'text' => 'Page',
                'url' => $admin_url . 'post-new.php?post_type=page',
                'icon' => 'page',
            ),
        );

        $post_types = \get_post_types(array(
            'show_in_menu' => true,
            'public' => true,
        ), 'objects');

        foreach ($post_types as $post_type) {
            if (in_array($post_type->name, array('post', 'page', 'attachment'))) {
                continue;
            }

            if (\current_user_can($post_type->cap->create_posts)) {
                $items[] = array(
                    'text' => $post_type->labels->singular_name,
                    'url' => $admin_url . 'post-new.php?post_type=' . $post_type->name,
                    'icon' => 'post-type',
                );
            }
        }

        if (\current_user_can('create_users')) {
            $items[] = array(
                'text' => 'User',
                'url' => $admin_url . 'user-new.php',
                'icon' => 'user',
            );
        }

        return array_merge($default_items, $items);
    }

    /**
     * Check permissions - always return true
     * Let WordPress capabilities handle access
     */
    public static function checkPermissions(): bool
    {
        return true;
    }

    /**
     * WordPress $submenu[ $parent ] array key as id / unique_id suffix (legacy "{slug}_{key}" behavior).
     *
     * @param mixed $key Array key from global $submenu
     */
    public static function submenuArrayKeyToUniqueIdSuffix(mixed $key): string
    {
        $suffix = '0';
        if (\is_int($key)) {
            $suffix = (string) $key;
        } elseif (\is_float($key) || (\is_string($key) && $key !== '' && \is_numeric($key))) {
            $value = \is_float($key) ? $key : (float) $key;
            $suffix = self::formatNumericMenuKeySuffix($value);
        } elseif (\is_string($key) && $key !== '') {
            $clean = \preg_replace('/[^a-zA-Z0-9._-]+/', '_', $key);
            $suffix = ($clean !== '' && $clean !== null) ? $clean : 'x';
        }

        return $suffix;
    }

    private static function formatNumericMenuKeySuffix(float $value): string
    {
        $suffix = '0';
        $isWhole = \floor($value) === $value && \abs($value) <= PHP_INT_MAX;
        if ($isWhole) {
            $suffix = (string) (int) $value;
        } else {
            $trim = \trim(\trim(\sprintf('%.6F', $value), '0'), '.');
            $suffix = $trim !== '' ? $trim : '0';
        }

        return $suffix;
    }
}
