<?php

namespace SoftminalB2B\Storefront;

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

use SoftminalB2B\Pricing\Context;
use SoftminalB2B\Services\Settings;

/**
 * A shopper-facing "prices ex/inc VAT" switch (FEATURES A — pricing display).
 *
 * Trade buyers quote and think ex-VAT, but often need to see the VAT-inclusive
 * figure before they order. This puts that choice in their hands: a toggle on
 * the shop and product pages that flips every price on the page between the two,
 * remembered in a cookie. It defaults to the store's `tax_display_b2b` setting
 * (which nothing wired up before this) and is shown only to B2B customers on a
 * tax-enabled store — a retail shopper never sees it.
 */
class TaxToggle
{
    private const COOKIE = 'smb2b_tax_display';
    private const ACTION = 'smb2b_tax';

    private static bool $registered = false;

    public static function init(): void
    {
        if (self::$registered || !function_exists('wc_tax_enabled') || !wc_tax_enabled()) {
            return;
        }

        self::$registered = true;

        // Default ON lives in Settings::$defaults (not seeded here — init is
        // skipped entirely on tax-disabled stores, which would leave the
        // settings screen contradicting the documented default).

        // A click on the toggle lands as a query arg; store it and redirect clean.
        add_action('template_redirect', [self::class, 'handleClick']);

        // Drive Woo's own display mode from the buyer's choice.
        add_filter('option_woocommerce_tax_display_shop', [self::class, 'displayMode']);
        add_filter('option_woocommerce_tax_display_cart', [self::class, 'displayMode']);

        // Render the switch above the shop grid and on the product page.
        add_action('woocommerce_before_shop_loop', [self::class, 'render'], 25);
        add_action('woocommerce_single_product_summary', [self::class, 'render'], 25);

        add_action('wp_enqueue_scripts', [self::class, 'enqueueStyles']);
    }

    /**
     * The tax display mode for this request: the buyer's cookie choice if set,
     * otherwise the configured B2B default. Only ever overrides for a B2B
     * customer — retail keeps whatever the store is set to.
     *
     * @param mixed $value
     * @return mixed
     */
    public static function displayMode($value)
    {
        if (is_admin() || !self::enabled() || Context::forUser()->isRetail()) {
            return $value;
        }

        $choice = self::choice();

        return $choice !== '' ? $choice : $value;
    }

    /**
     * Merchant kill-switch (1.2.0): some stores want one fixed display.
     * Stored yes/no; anything unset counts as ON so upgrades change nothing.
     */
    private static function enabled(): bool
    {
        return \SoftminalB2B\Services\Settings::get('tax_toggle_enabled', 'yes') !== 'no';
    }

    /**
     * Persist a click, then reload without the query arg so a refresh is stable.
     */
    public static function handleClick(): void
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- a display preference, not a state change.
        if (empty($_GET[self::ACTION])) {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $mode = $_GET[self::ACTION] === 'incl' ? 'incl' : 'excl';

        setcookie(self::COOKIE, $mode, time() + YEAR_IN_SECONDS, defined('COOKIEPATH') ? COOKIEPATH : '/', defined('COOKIE_DOMAIN') ? COOKIE_DOMAIN : '');
        $_COOKIE[self::COOKIE] = $mode;

        wp_safe_redirect(remove_query_arg(self::ACTION));
        exit;
    }

    public static function render(): void
    {
        if (!self::enabled() || Context::forUser()->isRetail()) {
            return;
        }

        $current = self::current();

        // button() returns markup escaped piece by piece (esc_url + esc_attr +
        // esc_html), so the assembled toggle is safe to print.
        printf(
            '<div class="smb2b-tax-toggle" role="group" aria-label="%s">%s%s</div>',
            esc_attr__('Show prices with or without VAT', 'softminal-b2b-wholesale-for-woocommerce'),
            self::button('excl', __('Ex. VAT', 'softminal-b2b-wholesale-for-woocommerce'), $current), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
            self::button('incl', __('Inc. VAT', 'softminal-b2b-wholesale-for-woocommerce'), $current) // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        );
    }

    private static function button(string $mode, string $label, string $current): string
    {
        $url = esc_url(add_query_arg(self::ACTION, $mode));
        $cls = 'smb2b-tax-toggle__btn' . ($current === $mode ? ' is-active' : '');

        return sprintf(
            '<a href="%s" class="%s"%s>%s</a>',
            $url,
            esc_attr($cls),
            $current === $mode ? ' aria-current="true"' : '',
            esc_html($label)
        );
    }

    /**
     * The mode in effect now (choice, or the configured default), for the toggle
     * to highlight.
     */
    private static function current(): string
    {
        $choice = self::choice();

        return $choice !== '' ? $choice : (Settings::get('tax_display_b2b') === 'incl' ? 'incl' : 'excl');
    }

    /**
     * The buyer's explicit cookie choice, or '' when they have not chosen.
     */
    private static function choice(): string
    {
        $pref = isset($_COOKIE[self::COOKIE]) ? sanitize_key((string) $_COOKIE[self::COOKIE]) : '';

        return in_array($pref, ['incl', 'excl'], true) ? $pref : '';
    }

    public static function enqueueStyles(): void
    {
        if (!function_exists('is_woocommerce') || !(is_woocommerce() || is_shop())) {
            return;
        }

        $css = ''
            . '.smb2b-tax-toggle{display:inline-flex;gap:2px;padding:3px;margin:0 0 16px;border-radius:999px;'
            . 'background:rgba(0,0,0,.05);font-size:12.5px}'
            . '.smb2b-tax-toggle__btn{padding:4px 12px;border-radius:999px;text-decoration:none;color:inherit;'
            . 'opacity:.7;font-weight:600;line-height:1.6}'
            . '.smb2b-tax-toggle__btn.is-active{background:#fff;opacity:1;box-shadow:0 1px 2px rgba(0,0,0,.12)}';

        wp_register_style('smb2b-tax-toggle', false, [], SMB2B_VERSION);
        wp_enqueue_style('smb2b-tax-toggle');
        wp_add_inline_style('smb2b-tax-toggle', $css);
    }
}
