<?php
declare(strict_types=1);

namespace Help4BuilderSuite\Modules\MegaMenu;

use Help4BuilderSuite\Contracts\ModuleContract;
use WP_Post;

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

final class Module implements ModuleContract
{
    public function key(): string
    {
        return 'mega_menu';
    }

    public function boot(): void
    {
        add_action('wp_nav_menu_item_custom_fields', [$this, 'renderItemFields'], 10, 4);
        add_action('wp_update_nav_menu_item', [$this, 'saveItemFields'], 10, 3);
        add_filter('nav_menu_css_class', [$this, 'addMenuClasses'], 10, 4);
        add_filter('walker_nav_menu_start_el', [$this, 'decorateMenuOutput'], 10, 4);
    }

    /**
     * @param object|string $args
     */
    public function renderItemFields(int $itemId, WP_Post $menuItem, int $depth, $args): void
    {
        $enabled = (string) get_post_meta($itemId, '_h4_mega_enabled', true);
        $columns = (int) get_post_meta($itemId, '_h4_mega_columns', true);
        $badge = (string) get_post_meta($itemId, '_h4_mega_badge', true);

        if (! $columns) {
            $columns = 4;
        }
        ?>
        <p class="field-h4-mega-enabled description description-wide">
            <label>
                <input type="checkbox" name="h4_mega_enabled[<?php echo esc_attr((string) $itemId); ?>]" value="1" <?php checked($enabled === '1'); ?>>
                <?php esc_html_e('Enable Mega Menu Container', 'help4-builder-suite'); ?>
            </label>
        </p>
        <p class="field-h4-mega-columns description description-thin">
            <label>
                <?php esc_html_e('Mega Columns (2-6)', 'help4-builder-suite'); ?><br>
                <input type="number" min="2" max="6" class="widefat code edit-menu-item-custom" name="h4_mega_columns[<?php echo esc_attr((string) $itemId); ?>]" value="<?php echo esc_attr((string) $columns); ?>">
            </label>
        </p>
        <p class="field-h4-mega-badge description description-thin">
            <label>
                <?php esc_html_e('Badge Text (optional)', 'help4-builder-suite'); ?><br>
                <input type="text" class="widefat code edit-menu-item-custom" name="h4_mega_badge[<?php echo esc_attr((string) $itemId); ?>]" value="<?php echo esc_attr($badge); ?>">
            </label>
        </p>
        <?php
    }

    /**
     * @param array<string, mixed> $args
     */
    public function saveItemFields(int $menuId, int $menuItemDbId, array $args): void
    {
        if (
            ! isset($_POST['update-nav-menu-nonce'])
            || ! wp_verify_nonce(sanitize_text_field((string) wp_unslash($_POST['update-nav-menu-nonce'])), 'update-nav_menu')
        ) {
            return;
        }

        $megaEnabled = isset($_POST['h4_mega_enabled']) && is_array($_POST['h4_mega_enabled'])
            ? map_deep(wp_unslash($_POST['h4_mega_enabled']), 'sanitize_text_field')
            : [];
        $enabled = isset($megaEnabled[$menuItemDbId]) ? '1' : '0';
        update_post_meta($menuItemDbId, '_h4_mega_enabled', $enabled);

        $megaColumns = isset($_POST['h4_mega_columns']) && is_array($_POST['h4_mega_columns'])
            ? map_deep(wp_unslash($_POST['h4_mega_columns']), 'sanitize_text_field')
            : [];
        $columns = isset($megaColumns[$menuItemDbId]) ? (int) $megaColumns[$menuItemDbId] : 4;
        $columns = max(2, min(6, $columns));
        update_post_meta($menuItemDbId, '_h4_mega_columns', $columns);

        $badge = isset($_POST['h4_mega_badge'][$menuItemDbId]) ? sanitize_text_field(wp_unslash($_POST['h4_mega_badge'][$menuItemDbId])) : '';
        update_post_meta($menuItemDbId, '_h4_mega_badge', $badge);
    }

    /**
     * @param string[] $classes
     * @param object|string $args
     * @return string[]
     */
    public function addMenuClasses(array $classes, WP_Post $item, $args, int $depth): array
    {
        $enabled = (string) get_post_meta($item->ID, '_h4_mega_enabled', true);
        $columns = (int) get_post_meta($item->ID, '_h4_mega_columns', true);

        if ($enabled === '1') {
            $classes[] = 'h4bs-mega-parent';
            if ($columns > 0) {
                $classes[] = 'h4bs-mega-cols-' . $columns;
            }
        }

        return array_unique($classes);
    }

    /**
     * @param object|string $args
     */
    public function decorateMenuOutput(string $itemOutput, WP_Post $item, int $depth, $args): string
    {
        $badge = (string) get_post_meta($item->ID, '_h4_mega_badge', true);
        if ($badge === '') {
            return $itemOutput;
        }

        $badgeHtml = '<span class="h4bs-menu-badge">' . esc_html($badge) . '</span>';
        return str_replace('</a>', ' ' . $badgeHtml . '</a>', $itemOutput);
    }
}
