<?php

namespace SoftminalB2B\Storefront;

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

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

/**
 * "Purchase Lists" tab in the WooCommerce My Account page (FEATURES F1 reorder).
 *
 * Buyers save order templates in the bulk order form; this gives them a home in
 * My Account to reorder, rename or delete them. The tab mounts a small Vue app
 * (`resources/storefront/purchase-lists.js`) that shares the REST endpoints and
 * stylesheet with the bulk order form. The rewrite endpoint is registered here
 * and flushed on activation (see Install::activate()).
 */
class PurchaseListsAccount
{
    public const ENDPOINT = 'purchase-lists';

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

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

        self::$registered = true;

        // Keep the rewrite endpoint + query var registered always (so an already
        // flushed permalink never 404s), but only surface the menu tab and its
        // content when saved lists are enabled in the admin.
        add_action('init', [self::class, 'registerEndpoint']);
        add_filter('woocommerce_get_query_vars', [self::class, 'addQueryVar']);

        if (Settings::get('bulk_order_enable_lists', 'yes') === 'no') {
            return;
        }

        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 "Purchase Lists" 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] = __('Purchase Lists', 'softminal-b2b-wholesale-for-woocommerce');

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

        return $items;
    }

    /**
     * Render the endpoint content: a mount point for the Vue app. The `.smb2b-bulk`
     * class pulls in the shared stylesheet.
     */
    public static function renderEndpoint(): void
    {
        self::$needsAssets = true;

        echo '<div id="smb2b-purchase-lists" class="smb2b-bulk"></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-purchase-lists', 'resources/storefront/purchase-lists.js', [], true);

        if (!$enqueued) {
            return;
        }

        // Shared base stylesheet (same file the bulk order form loads).
        Vite::enqueueStyle('smb2b-bulk-order-base', 'resources/storefront/bulk-order/table.css');

        Vite::localize('smb2b-purchase-lists', 'smb2bPurchaseLists', [
            'apiUrl' => rest_url(SMB2B_API_NAMESPACE),
            'nonce'  => wp_create_nonce('wp_rest'),
            'i18n'   => TranslationStrings::purchaseLists(),
        ]);

        // Reuse the bulk order form's stylesheet + store accent (scoped to
        // .smb2b-bulk). Inline styles ride on the base handle enqueued above.
        BulkOrderForm::attachInlineStyles();
    }
}
