<?php

namespace BWDK\Admin;

use BWDK\Support\Constant;
use BWDK\Support\WooCompatibility;
use WC_Order;

class AdminOrderHooks
{
    public function register(): void
    {
        // Shipping item meta (admin order edit screen): show shipping promotion under the shipping row.
        add_action('woocommerce_after_order_itemmeta', [$this, 'renderShippingPromotionUnderShippingItem'], 10, 3);

        // Admin totals table: add a separate "shipping discount" row (display-only).
        add_action('woocommerce_admin_order_totals_after_shipping', [$this, 'renderShippingPromotionTotalsRow'], 10, 1);

        // Optional helper row (display-only): "Final shipping: Free" when final == 0.
        add_action('woocommerce_admin_order_totals_after_total', [$this, 'renderFinalShippingHelperRow'], 10, 1);
    }

    /**
     * UI-only: prints extra meta under shipping item row in admin order edit.
     *
     * @param int $item_id
     * @param \WC_Order_Item $item
     * @param mixed $product
     */
    public function renderShippingPromotionUnderShippingItem($item_id, $item, $product = null): void
    {
        if (!is_admin()) {
            return;
        }
        if (!$item instanceof \WC_Order_Item_Shipping) {
            return;
        }

        $order_id = (int) $item->get_order_id();
        $order = $order_id ? wc_get_order($order_id) : null;
        if (!$order instanceof WC_Order) {
            return;
        }

        $data = $this->get_shipping_promotion_snapshot($order);
        if (!$data['has_shipping_promotion']) {
            return;
        }

        $code_label = ($data['discount_type'] === 1) ? 'کد ارسال رایگان' : 'کد تخفیف ارسال';
        $code_line = sprintf('%s: %s (%s)', $code_label, $data['code'], $data['discount_label']);

        $discount_money = $this->format_money($order, (float) $data['shipping_discount_amount']);
        $discount_line = sprintf('تخفیف ارسال: %s', $discount_money);

        echo '<div class="bwdk-admin-shipping-promotion" style="margin-top:6px; padding-top:6px; border-top:1px dashed #ddd;">';
        echo '<div><strong>' . esc_html($code_label) . ':</strong> ' . esc_html($data['code']) . ' (' . esc_html($data['discount_label']) . ')</div>';
        echo '<div><strong>' . esc_html__('تخفیف ارسال', 'bwdk') . ':</strong> ' . esc_html($discount_money) . '</div>';
        echo '</div>';
    }

    /**
     * UI-only: adds a "Shipping discount" row in admin totals.
     *
     * @param int|\WC_Order $order_id
     */
    public function renderShippingPromotionTotalsRow($order_id): void
    {
        if (!is_admin()) {
            return;
        }

        $order = $order_id instanceof WC_Order ? $order_id : wc_get_order((int) $order_id);
        if (!$order instanceof WC_Order) {
            return;
        }

        $data = $this->get_shipping_promotion_snapshot($order);
        if (!$data['has_shipping_promotion']) {
            return;
        }

        $discount_amount = (float) $data['shipping_discount_amount'];
        if ($discount_amount <= 0) {
            return;
        }

        $discount_display = $this->format_money($order, $discount_amount);
        // Show as negative (display-only).
        $discount_display = '-' . $discount_display;

        echo '<tr class="bwdk-admin-totals-shipping-discount">';
        echo '  <td class="label">' . esc_html__('تخفیف ارسال', 'bwdk') . ':</td>';
        echo '  <td width="1%"></td>';
        echo '  <td class="total">' . esc_html($discount_display) . '</td>';
        echo '</tr>';
    }

    /**
     * UI-only: adds a helper row when shipping becomes free after promotion.
     *
     * @param int|\WC_Order $order_id
     */
    public function renderFinalShippingHelperRow($order_id): void
    {
        if (!is_admin()) {
            return;
        }

        $order = $order_id instanceof WC_Order ? $order_id : wc_get_order((int) $order_id);
        if (!$order instanceof WC_Order) {
            return;
        }

        $data = $this->get_shipping_promotion_snapshot($order);
        if (!$data['has_shipping_promotion']) {
            return;
        }

        if ((float) $data['final_shipping_amount'] > 0) {
            return;
        }

        echo '<tr class="bwdk-admin-totals-final-shipping">';
        echo '  <td class="label">' . esc_html__('ارسال نهایی', 'bwdk') . ':</td>';
        echo '  <td width="1%"></td>';
        echo '  <td class="total">' . esc_html__('رایگان', 'bwdk') . '</td>';
        echo '</tr>';
    }

    /**
     * Source of truth for admin display.
     * Reads from order meta first, then falls back to raw BWDK JSON (Constant::META_BWDK_JSON_CB).
     *
     * Returns:
     * - has_shipping_promotion (bool)
     * - code (string)
     * - discount_type (int 1/2)
     * - discount_label (string "100%" | "20,000 تومان")
     * - shipping_discount_amount (float, store currency)
     * - original_shipping_amount (float, store currency)
     * - final_shipping_amount (float, store currency)
     */
    private function get_shipping_promotion_snapshot(WC_Order $order): array
    {
        $out = [
            'has_shipping_promotion' => false,
            'code' => '',
            'discount_type' => 0,
            'discount_label' => '',
            'shipping_discount_amount' => 0.0,
            'original_shipping_amount' => 0.0,
            'final_shipping_amount' => 0.0,
        ];

        $discount_bwdk = (float) $order->get_meta('_bwdk_shipping_promotion_discount_amount', true);
        $promo = $order->get_meta('_bwdk_shipping_promotion_data', true);

        if (is_string($promo)) {
            $decoded = json_decode($promo, true);
            $promo = is_array($decoded) ? $decoded : [];
        }
        if (!is_array($promo)) {
            $promo = [];
        }

        // Fallback to raw JSON if needed.
        if ($discount_bwdk <= 0 || empty($promo)) {
            $raw = $order->get_meta(Constant::META_BWDK_JSON_CB);
            if (is_string($raw)) {
                $raw = json_decode($raw, true);
            }
            if (is_array($raw)) {
                if ($discount_bwdk <= 0 && isset($raw['shipping_promotion_discount_amount'])) {
                    $discount_bwdk = (float) $raw['shipping_promotion_discount_amount'];
                }
                if (empty($promo) && isset($raw['shipping_promotion_data']) && is_array($raw['shipping_promotion_data'])) {
                    $promo = $raw['shipping_promotion_data'];
                }
            }
        }

        if ($discount_bwdk <= 0 || empty($promo) || !is_array($promo)) {
            return $out;
        }

        $code = isset($promo['code']) ? trim((string) $promo['code']) : '';
        $discount_type = isset($promo['discount_type']) ? (int) $promo['discount_type'] : 0;
        $discount_value = isset($promo['discount_value']) ? (float) $promo['discount_value'] : 0.0;

        if ($code === '' || ($discount_type !== 1 && $discount_type !== 2)) {
            return $out;
        }

        // originalShipping from raw JSON: shipping_amount or selected_shipping_method.cost (BWDK unit = Toman)
        $raw = $order->get_meta(Constant::META_BWDK_JSON_CB);
        if (is_string($raw)) {
            $raw = json_decode($raw, true);
        }
        $original_bwdk = null;
        if (is_array($raw)) {
            if (isset($raw['shipping_amount'])) {
                $original_bwdk = (float) $raw['shipping_amount'];
            } elseif (isset($raw['selected_shipping_method']['cost'])) {
                $original_bwdk = (float) $raw['selected_shipping_method']['cost'];
            }
        }

        $original_store = is_numeric($original_bwdk)
            ? WooCompatibility::convert_to_store_currency((float) $original_bwdk)
            : (float) $order->get_shipping_total();

        $discount_store = WooCompatibility::convert_to_store_currency((float) $discount_bwdk);
        $final_store = max(0.0, (float) $original_store - (float) $discount_store);

        $discount_label = '';
        if ($discount_type === 1) {
            $discount_label = rtrim(rtrim(number_format($discount_value, 2, '.', ''), '0'), '.') . '%';
        } elseif ($discount_type === 2) {
            $discount_label = number_format($discount_value, 0, '.', ',') . ' تومان';
        }

        $out['has_shipping_promotion'] = true;
        $out['code'] = $code;
        $out['discount_type'] = $discount_type;
        $out['discount_label'] = $discount_label;
        $out['shipping_discount_amount'] = $discount_store;
        $out['original_shipping_amount'] = (float) $original_store;
        $out['final_shipping_amount'] = (float) $final_store;

        return $out;
    }

    private function format_money(WC_Order $order, float $amount): string
    {
        if (function_exists('wc_price')) {
            return wp_strip_all_tags(wc_price($amount, ['currency' => $order->get_currency()]));
        }
        return number_format($amount, 0, '.', ',') . ' تومان';
    }
}

