<?php


namespace BWDK\Woo\Order;

use BWDK\Admin\BWDK_Admin_DX_Meta_Box;
use BWDK\Support\Constant;
use BWDK\Woo\Order\ReferenceCodeHelper;
use WC_Order;

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

class OrderListColumns
{
    const COLUMN_KEY       = 'bwdk';
    const COLUMN_LABEL     = 'روش پرداخت';
    const COLUMN_REF_KEY   = 'bwdk_reference_code';
    const COLUMN_REF_LABEL = 'کد پیگیری دیجی‌کالایی';
    const PLACEHOLDER_HTML = '<span class="na">—</span>';

    public function register(): void
    {

        add_filter('manage_edit-shop_order_columns', [$this, 'addColumnLegacy'], 20);
        add_action('manage_shop_order_posts_custom_column', [$this, 'renderColumnLegacy'], 20, 2);


        add_filter('woocommerce_shop_order_list_table_columns', [$this, 'addColumnHpos'], 20);
        add_action('woocommerce_shop_order_list_table_custom_column', [$this, 'renderColumnHpos'], 20, 2);


        add_filter('manage_edit-shop_order_sortable_columns', [$this, 'makeSortableLegacy']);
        add_filter('woocommerce_shop_order_list_table_sortable_columns', [$this, 'makeSortableHpos']);

        add_action('pre_get_posts', [$this, 'applyLegacySorting']);

        // DigiKala tracking search: use WooCommerce filters only (no main query override).
        add_filter('woocommerce_shop_order_search_fields', [$this, 'extendSearchableOrderMeta']);
        add_filter('woocommerce_order_table_search_query_meta_keys', [$this, 'extendSearchableOrderMeta']);

        // Admin styles for reference/id display.
        add_action('admin_head', [$this, 'printAdminStyles']);
    }

    /** ---------------- Legacy (manage_edit-shop_order) ---------------- */

    public function addColumnLegacy(array $columns): array
    {
        return $this->injectColumns($columns);
    }

    public function renderColumnLegacy(string $column, int $post_id): void
    {
        if (!in_array($column, [self::COLUMN_KEY, self::COLUMN_REF_KEY], true)) return;

        $order = wc_get_order($post_id);
        if ($column === self::COLUMN_KEY) {
            echo wp_kses_post($this->getCellHtml($order));
            return;
        }

        echo wp_kses_post($this->getReferenceCodeHtml($order));
    }

    public function makeSortableLegacy(array $columns): array
    {
        $columns[self::COLUMN_KEY] = self::COLUMN_KEY;
        return $columns;
    }


    public function applyLegacySorting(\WP_Query $q): void
    {
        if (!is_admin() || !$q->is_main_query()) return;

        $orderby = $q->get('orderby');
        if ($orderby !== self::COLUMN_KEY) return;

        $q->set('meta_key', '_bwdk_payment_status');
        $q->set('orderby', 'meta_value');
    }

    /** ---------------- HPOS (wc-orders screen) ---------------- */

    public function addColumnHpos(array $columns): array
    {
        return $this->injectColumns($columns);
    }

    /**
     * @param string $column Column key
     * @param \WC_Order $order Order object
     */
    public function renderColumnHpos(string $column, $order): void
    {
        if (!in_array($column, [self::COLUMN_KEY, self::COLUMN_REF_KEY], true)) return;

        if (!$order instanceof WC_Order) {

            $order = wc_get_order(is_numeric($order) ? (int)$order : 0);
        }
        if ($column === self::COLUMN_KEY) {
            echo wp_kses_post($this->getCellHtml($order));
            return;
        }

        echo wp_kses_post($this->getReferenceCodeHtml($order));
    }

    public function makeSortableHpos(array $columns): array
    {
        $columns[self::COLUMN_KEY] = self::COLUMN_KEY;
        return $columns;
    }

    /** ---------------- Helper ---------------- */

    protected function getCellHtml(?WC_Order $order): string
    {
        if (!$order) return self::PLACEHOLDER_HTML;

        $data = $order->get_meta(Constant::META_BWDK_JSON_CB);
        if (!is_array($data)) {
            $data = [];
        }

        $raw_gateway = strtolower((string) ($data['payment']['gateway_name'] ?? ''));
        $payment_title = (string) $order->get_payment_method_title();
        $payment_method = (string) $order->get_payment_method();

        $display = $this->buildPaymentMethodDisplayHtml($raw_gateway, $payment_title, $payment_method);
        if ($display === '') {
            return self::PLACEHOLDER_HTML;
        }

        // Check if this is a BWDK payment (Digikala/Digipay)
        $is_bwdk_payment = strpos(strtolower($payment_title), 'دیجی') !== false
                          || strtolower($payment_method) === 'digikala'
                          || strtolower($payment_method) === 'digipay'
                          || $raw_gateway !== '';

        // Only apply badge classes for BWDK payments
        if (!$is_bwdk_payment) {
            return $this->maybe_append_digiexpress_list_icon(esc_html($display), $order);
        }

        $badgeClass = 'bwdk-badge bwdk-badge--muted';
        switch (strtolower($display)) {
            case 'paid':
            case 'success':
            case 'ok':
                $badgeClass = 'bwdk-badge bwdk-badge--success';
                break;
            case 'failed':
            case 'error':
                $badgeClass = 'bwdk-badge bwdk-badge--danger';
                break;
            case 'pending':
            default:
                $badgeClass = 'bwdk-badge bwdk-badge--warning';
                break;
        }

        $html = sprintf('<span class="%s">%s</span>', esc_attr($badgeClass), $display);

        return $this->maybe_append_digiexpress_list_icon($html, $order);
    }

    /**
     * Build logo-based payment method markup for the order list column.
     */
    protected function buildPaymentMethodDisplayHtml(string $raw_gateway, string $payment_title, string $payment_method = ''): string
    {
        if ($raw_gateway === 'digipay') {
            $bwdk_logo    = $this->paymentLogoImg('BWDKLogo.svg', 'Buy With Digikala');
            $digipay_logo = $this->paymentLogoImg('Digi pay.svg', 'DigiPay');

            if ($bwdk_logo === '' || $digipay_logo === '') {
                return $payment_title !== '' ? $payment_title . ' / دیجی پی' : 'دیجی پی';
            }

            return $this->wrapPaymentMethodHtml($bwdk_logo, $digipay_logo);
        }

        if ($raw_gateway !== '') {
            $bwdk_logo = $this->paymentLogoImg('BWDKLogo.svg', 'Buy With Digikala');
            if ($bwdk_logo === '') {
                return 'نقدی';
            }

            return $this->wrapPaymentMethodHtml(
                $bwdk_logo,
                '<span class="bwdk-payment-label">' . esc_html('نقدی') . '</span>'
            );
        }

        if ($this->isBwdkLabelOnlyPayment($payment_title, $payment_method)) {
            $bwdk_logo = $this->paymentLogoImg('BWDKLogo.svg', 'Buy With Digikala');
            if ($bwdk_logo === '') {
                return $payment_title;
            }

            return $this->wrapPaymentMethodStandaloneHtml($bwdk_logo);
        }

        return $payment_title;
    }

    protected function isBwdkLabelOnlyPayment(string $payment_title, string $payment_method = ''): bool
    {
        if (strpos(strtolower($payment_title), 'دیجی') !== false) {
            return true;
        }

        $method = strtolower($payment_method);

        return $method === 'digikala' || $method === 'digipay';
    }

    protected function wrapPaymentMethodStandaloneHtml(string $content): string
    {
        return sprintf('<div class="bwdk-payment-method">%s</div>', $content);
    }

    protected function wrapPaymentMethodHtml(string $left, string $right): string
    {
        return sprintf(
            '<div class="bwdk-payment-method">%s<span class="bwdk-payment-separator">/</span>%s</div>',
            $left,
            $right
        );
    }

    protected function paymentLogoImg(string $filename, string $alt): string
    {
        if (!defined('BWDK_PUBLIC_IMG')) {
            return '';
        }

        return sprintf(
            '<img src="%s" alt="%s" class="bwdk-payment-logo" />',
            esc_url(BWDK_PUBLIC_IMG . $filename),
            esc_attr($alt)
        );
    }

    /**
     * Append DigiExpress list icon next to payment method cell when feature flag and order detection match.
     */
    protected function maybe_append_digiexpress_list_icon(string $html, WC_Order $order): string
    {
        if (!function_exists('bwdk_is_digiexpress_enabled') || !bwdk_is_digiexpress_enabled()) {
            return $html;
        }
        if (!class_exists(BWDK_Admin_DX_Meta_Box::class) || !BWDK_Admin_DX_Meta_Box::order_is_digiexpress_for_list($order)) {
            return $html;
        }
        if (!defined('BWDK_ADMIN_IMG')) {
            return $html;
        }

        $img = sprintf(
            '<img src="%s" alt="%s" width="16" height="16" style="width:13px;height:15px;vertical-align:middle;margin-inline-start:6px;" />',
            esc_url(BWDK_ADMIN_IMG . 'DXlist.svg'),
            esc_attr('DigiExpress')
        );

        return $html . wp_kses_post($img);
    }

    protected function getReferenceCodeHtml(?WC_Order $order): string
    {
        if (!$order instanceof WC_Order) {
            return self::PLACEHOLDER_HTML;
        }

        $code = ReferenceCodeHelper::extractFromOrder($order);
        if ($code === '') {
            return self::PLACEHOLDER_HTML;
        }

        // Digify order id from stored callback JSON meta.
        $digify_id = '';
        $raw       = $order->get_meta(Constant::META_BWDK_JSON_CB);

        // Normalise meta value similar to ReferenceCodeHelper::normaliseMetaValue
        if ($raw instanceof \stdClass) {
            $raw = (array) $raw;
        }

        if (is_string($raw)) {
            $trimmed = trim($raw);
            if ($trimmed !== '') {
                $json = json_decode($trimmed, true);
                if (json_last_error() === JSON_ERROR_NONE) {
                    $raw = $json;
                } else {
                    $maybe = maybe_unserialize($trimmed);
                    if ($maybe !== $raw) {
                        $raw = $maybe;
                    }
                }
            }
        }

        if (is_array($raw)) {
            $id_value = $raw['id'] ?? null;
            if ($id_value !== null && !is_array($id_value) && !is_object($id_value)) {
                $digify_id = (string) $id_value;
            }
        }

        $html = '<span class="ltr bwdk-refcode" style="display:block;">' . esc_html($code) . '</span>';
        if ($digify_id !== '') {
            $html .= '<span class="ltr bwdk-refid">' . 'id: ' . esc_html($digify_id) . '</span>';
        }

        return $html;
    }

    /**
     * Print minimal admin CSS for reference/id styling.
     */
    public function printAdminStyles(): void
    {
        echo '<style>
        .column-bwdk_reference_code span.ltr.bwdk-refid {
            display: inline-flex;
            color: #454545;
            background: #e5e5e5;
            border-radius: 4px;
            border-bottom: 1px solid rgba(0, 0, 0, .05);
            cursor: inherit !important;
            white-space: nowrap;
            padding: 0 5px;
            font-weight: bold;
            text-transform: uppercase;
            margin-right: 5px;
            font-size: 10px;
        }
        </style>';
    }

    protected function injectColumns(array $columns): array
    {
        $new = [];
        foreach ($columns as $key => $label) {
            $new[$key] = $label;
            if ($key === 'order_total') {
                $new[self::COLUMN_KEY]     = self::COLUMN_LABEL;
                $new[self::COLUMN_REF_KEY] = self::COLUMN_REF_LABEL;
            }
        }

        if (!isset($new[self::COLUMN_KEY])) {
            $new[self::COLUMN_KEY] = self::COLUMN_LABEL;
        }

        if (!isset($new[self::COLUMN_REF_KEY])) {
            $new[self::COLUMN_REF_KEY] = self::COLUMN_REF_LABEL;
        }

        return $new;
    }

    /**
     * Add BWDK meta keys to WooCommerce order search (legacy + HPOS).
     * Does not modify main query; WooCommerce merges these into its search.
     */
    public function extendSearchableOrderMeta(array $meta_keys): array
    {
        $meta_keys[] = Constant::META_BWDK_JSON_CB;
        $meta_keys[] = '_bwdk_reference_code';
        $meta_keys[] = '_bwdk_digify_order_id';
        $meta_keys[] = '_bwdk_search_tokens';

        return array_values(array_unique($meta_keys));
    }
}
