<?php

namespace SoftminalB2B\Storefront;

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

use SoftminalB2B\Services\TranslationStrings;
use SoftminalB2B\Vite\Vite;

/**
 * Buyer-facing message centre ([[project-messaging-feature]]).
 *
 * Two surfaces mount the same lean Vue app: the `[smb2b_messages]` shortcode
 * (for a custom page) and a "Messages" tab in the WooCommerce My Account page.
 * Basic buyer<->merchant messaging is a Free feature. The app talks to the
 * `my-messages` REST routes (BuyerMessagesController); everything it needs is
 * localized onto `window.smb2bMessages`.
 */
class MessageCentre
{
    public const ENDPOINT = 'smb2b-messages';
    public const SHORTCODE = 'smb2b_messages';

    private static bool $registered = false;
    private static bool $needsAssets = false;

    public static function init(): void
    {
        if (self::$registered) {
            return;
        }

        self::$registered = true;

        add_shortcode(self::SHORTCODE, [self::class, 'renderShortcode']);

        // Keep the rewrite endpoint + query var registered always so an already
        // flushed permalink never 404s.
        add_action('init', [self::class, 'registerEndpoint']);
        add_filter('woocommerce_get_query_vars', [self::class, 'addQueryVar']);
        add_filter('woocommerce_account_menu_items', [self::class, 'addMenuItem']);
        add_action('woocommerce_account_' . self::ENDPOINT . '_endpoint', [self::class, 'renderEndpoint']);
        add_action('wp_footer', [self::class, 'enqueueIfUsed']);
    }

    /**
     * @param array<string, string> $vars
     * @return array<string, string>
     */
    public static function addQueryVar(array $vars): array
    {
        $vars[self::ENDPOINT] = self::ENDPOINT;

        return $vars;
    }

    /**
     * Register the account endpoint. Also called from Install::activate() before
     * flushing rewrite rules so the pretty URL works on first activation.
     */
    public static function registerEndpoint(): void
    {
        add_rewrite_endpoint(self::ENDPOINT, EP_ROOT | EP_PAGES);
    }

    /**
     * Add "Messages" to the account menu, just before Logout.
     *
     * @param array<string, string> $items
     * @return array<string, string>
     */
    public static function addMenuItem(array $items): array
    {
        $logout = null;
        if (isset($items['customer-logout'])) {
            $logout = $items['customer-logout'];
            unset($items['customer-logout']);
        }

        $items[self::ENDPOINT] = __('Messages', 'softminal-b2b-wholesale-for-woocommerce');

        if ($logout !== null) {
            $items['customer-logout'] = $logout;
        }

        return $items;
    }

    /**
     * The `[smb2b_messages]` shortcode. Only logged-in customers get the app; a
     * guest sees a sign-in prompt (there is nothing to message about anonymously).
     */
    public static function renderShortcode(): string
    {
        if (!is_user_logged_in()) {
            return '<p class="smb2b-msgc__signin">'
                . esc_html__('Please sign in to message the store.', 'softminal-b2b-wholesale-for-woocommerce')
                . '</p>';
        }

        self::$needsAssets = true;

        return '<div id="smb2b-messages" class="smb2b-msgc"></div>';
    }

    /**
     * My Account endpoint content: the same mount point as the shortcode.
     */
    public static function renderEndpoint(): void
    {
        self::$needsAssets = true;

        echo '<div id="smb2b-messages" class="smb2b-msgc"></div>';
    }

    public static function enqueueIfUsed(): void
    {
        if (!self::$needsAssets) {
            return;
        }

        Vite::configure([
            'devServerUrl' => apply_filters('smb2b_vite_dev_server_url', BulkOrderForm::devServerUrl()),
            'pluginDir'    => SMB2B_DIR,
            'pluginUrl'    => SMB2B_URL,
            'version'      => SMB2B_VERSION,
        ]);

        $enqueued = Vite::enqueueAsset('smb2b-messages', 'resources/storefront/messages.js', [], true);

        if (!$enqueued) {
            return;
        }

        Vite::localize('smb2b-messages', 'smb2bMessages', [
            'apiUrl' => rest_url(SMB2B_API_NAMESPACE),
            'nonce'  => wp_create_nonce('wp_rest'),
            'i18n'   => TranslationStrings::messagesStorefront(),
        ]);
    }
}
