<?php


namespace BWDK\Woo\Order;

use BWDK\Support\Constant;
use WC_Order;

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

class OrderListColumns
{
    const COLUMN_KEY   = 'bwdk';
    const COLUMN_LABEL = 'روش پرداخت';

    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']);


    }

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

    public function addColumnLegacy(array $columns): array
    {

        $new = [];
        foreach ($columns as $key => $label) {
            $new[$key] = $label;
            if ($key === 'order_total') {
                $new[self::COLUMN_KEY] = self::COLUMN_LABEL;
            }
        }

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

    public function renderColumnLegacy(string $column, int $post_id): void
    {
        if ($column !== self::COLUMN_KEY) return;

        $order = wc_get_order($post_id);
        echo wp_kses_post($this->getCellHtml($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
    {

        $new = [];
        foreach ($columns as $key => $label) {
            $new[$key] = $label;
            if ($key === 'order_total') {
                $new[self::COLUMN_KEY] = self::COLUMN_LABEL;
            }
        }
        if (!isset($new[self::COLUMN_KEY])) {
            $new[self::COLUMN_KEY] = self::COLUMN_LABEL;
        }
        return $new;
    }

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

        if (!$order instanceof WC_Order) {

            $order = wc_get_order(is_numeric($order) ? (int)$order : 0);
        }
        echo wp_kses_post($this->getCellHtml($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 '<span class="na">—</span>';


        $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 '<span class="na">—</span>';
        }


        $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;
        }

        return sprintf('<span class="%s">%s</span>', esc_attr($badgeClass), esc_html($status));
    }
}
