<?php

namespace Licenzo\Modules\WooCommerce;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Framework\Asset\Vite;

/**
 * WooCommerce My Account Integration
 *
 * Registers Licenzo tabs (Subscriptions, Licenses) in the WooCommerce
 * "My Account" page and renders Vue micro-app mount points for each tab.
 */
class Account
{
    /** @var string WooCommerce endpoint slug for subscriptions tab */
    const ENDPOINT_SUBSCRIPTIONS = 'licenzo-subscriptions';

    /** @var string WooCommerce endpoint slug for licenses tab */
    const ENDPOINT_LICENSES = 'licenzo-licenses';

    public function __construct()
    {
        // Register rewrite endpoints so WooCommerce creates /my-account/licenzo-subscriptions/ etc.
        add_action('init', [$this, 'registerEndpoints']);

        // Add menu items to WooCommerce My Account navigation
        add_filter('woocommerce_account_menu_items', [$this, 'addMenuItems'], 200);

        // Register content callbacks for each endpoint
        add_action('woocommerce_account_' . static::ENDPOINT_SUBSCRIPTIONS . '_endpoint', [$this, 'renderSubscriptionsTab']);
        add_action('woocommerce_account_' . static::ENDPOINT_LICENSES . '_endpoint', [$this, 'renderLicensesTab']);
    }

    /**
     * Register WooCommerce rewrite endpoints.
     *
     * These create the URL structure: /my-account/licenzo-subscriptions/
     * EP_ROOT | EP_PAGES ensures they work with both permalink structures.
     */
    public function registerEndpoints(): void
    {
        add_rewrite_endpoint(static::ENDPOINT_SUBSCRIPTIONS, EP_ROOT | EP_PAGES);
        add_rewrite_endpoint(static::ENDPOINT_LICENSES, EP_ROOT | EP_PAGES);
    }

    /**
     * Add Licenzo tabs to WooCommerce My Account menu.
     *
     * Inserts "Subscriptions" and "Licenses" before the logout item.
     *
     * @param array $items Existing menu items
     * @return array Modified menu items
     */
    public function addMenuItems(array $items): array
    {
        $logout = $items['customer-logout'] ?? null;
        unset($items['customer-logout']);

        $items[static::ENDPOINT_SUBSCRIPTIONS] = __('Subscriptions', 'licenzo');
        $items[static::ENDPOINT_LICENSES] = __('Licenses', 'licenzo');

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

        return $items;
    }

    /**
     * Render the Subscriptions tab content.
     *
     * Enqueues Vue assets and outputs the mount point div.
     */
    public function renderSubscriptionsTab(): void
    {
        $this->enqueueWooAssets();
        echo '<div id="licenzo-woo-subscriptions" data-tab="subscriptions">Loading...</div>';
    }

    /**
     * Render the Licenses tab content.
     *
     * Enqueues Vue assets and outputs the mount point div.
     */
    public function renderLicensesTab(): void
    {
        $this->enqueueWooAssets();
        echo '<div id="licenzo-woo-licenses" data-tab="licenses">Loading...</div>';
    }

    /**
     * Enqueue Vue micro-app assets for WooCommerce tabs.
     *
     * Uses the Vite integration to load the woo entry point and
     * passes API configuration to the frontend. Idempotent — safe
     * to call multiple times per request.
     */
    private function enqueueWooAssets(): void
    {
        // Prevent double-enqueue within the same request
        static $enqueued = false;
        if ($enqueued) {
            return;
        }
        $enqueued = true;

        Vite::enqueue(
            'licenzo-woo-app',
            'resources/Customers/woo.js',
            [],
            true
        );

        wp_localize_script('licenzo-woo-app', 'licenzo_woo_app_', [
            'api_url'  => rest_url('licenzo/v1/'),
            'nonce'    => wp_create_nonce('wp_rest'),
            'currency' => function_exists('get_woocommerce_currency') ? get_woocommerce_currency() : 'USD',
            'locale'   => str_replace('_', '-', get_locale()),
        ]);
    }

    /**
     * Flush rewrite rules.
     *
     * Must be called on plugin activation so that the custom endpoints
     * registered in registerEndpoints() become available.
     */
    public static function flushRewriteRules(): void
    {
        // Register endpoints before flushing so the rules include them
        add_rewrite_endpoint(static::ENDPOINT_SUBSCRIPTIONS, EP_ROOT | EP_PAGES);
        add_rewrite_endpoint(static::ENDPOINT_LICENSES, EP_ROOT | EP_PAGES);
        flush_rewrite_rules();
    }

    /**
     * Static factory — registers hooks.
     */
    public static function register(): void
    {
        new static();
    }
}
