<?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);

        $gateway_name=$data["payment"]["gateway_name"]??"";
        switch (strtolower($gateway_name)) {
            case 'digipay':
                $gateway_name = 'دیجی پی';
                break;
            case 'sep':
                $gateway_name = 'بانک سامان';
                break;

        }

        $status = (string) $order->get_payment_method_title()." / ".$gateway_name;


        if ($status === '') {
            return self::PLACEHOLDER_HTML;
        }


        // Check if this is a BWDK payment (Digikala/Digipay)
        $payment_method = $order->get_payment_method();
        $is_bwdk_payment = strpos(strtolower($order->get_payment_method_title()), 'دیجی') !== false 
                          || strtolower($payment_method) === 'digikala' 
                          || strtolower($payment_method) === 'digipay'
                          || !empty($gateway_name);
        
        // Only apply badge classes for BWDK payments
        if (!$is_bwdk_payment) {
            return $this->maybe_append_digiexpress_list_icon(esc_html($status), $order);
        }

        $badgeClass = 'bwdk-badge bwdk-badge--muted';
        switch (strtolower($status)) {
            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), esc_html($status));

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

    /**
     * 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:16px;height:16px;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));
    }
}
