<?php


namespace BWDK\Woo\Order;


use Automattic\WooCommerce\Internal\Utilities\COTMigrationUtil;
use BWDK\Enums\BWDK_OrderStatus;
use WC_Order;

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

class OrderMetabox
{
    const ID = 'bwdk_meta';
    const TITLE = 'اطلاعات پرداخت امن دیجیکالا';

    public function register(): void
    {
        add_action('add_meta_boxes', [$this, 'addMetaboxLegacy']);
        add_action('admin_enqueue_scripts', [$this, 'enqueueStyle']);
    }

    public function enqueueStyle()
    {

        wp_enqueue_style(
            'bwdk-sweetalert-style',
            BWDK_ADMIN_CSS . 'sweetalert2.min.css',
            [],
            '1.0.0'
        );
        wp_enqueue_script(
            'bwdk-sweetalert-script',
            BWDK_ADMIN_JS . 'sweetalert2.all.min.js',
            ['jquery', 'bwdk-admin-script'],
            '1.0.0',
            true
        );
    }

    public function addMetaboxLegacy(): void
    {
        add_meta_box(
            self::ID,
            self::TITLE,
            [$this, 'renderLegacyMetabox'],
            wc_get_container()->get(COTMigrationUtil::class)->get_order_admin_screen(),
            'side',
            'high'
        );
    }

    public function renderLegacyMetabox(): void
    {
        $order_id = 0;
        if (isset($_REQUEST['id'])) {
            $order_id = $_REQUEST['id'];
        } elseif (isset($_REQUEST['post'])) {
            $order_id = $_REQUEST['post'];
        }

        $order = wc_get_order($order_id);

        if ($order) {
            echo $this->renderHtml($order);
        }
    }

    public function renderBoxInWooPanels($order): void
    {
        if (!$order instanceof WC_Order) {

            $order_id = isset($_GET['id']) ? absint($_GET['id']) : (isset($_GET['post']) ? absint($_GET['post']) : 0);
            $order = $order_id ? wc_get_order($order_id) : null;
        }
        echo $this->wrapAsPanel($this->renderHtml($order));
    }

    protected function renderHtml(?WC_Order $order): string
    {
        if (!$order) {
            return '<p>سفارشی یافت نشد.</p>';
        }


        $raw_json = $order->get_meta(\BWDK\Support\Constant::META_BWDK_JSON_CB);


        $order_uuid = (string)$order->get_meta(\BWDK\Support\Constant::META_BWDK_UUID);
        $order_url = (string)$order->get_meta(\BWDK\Support\Constant::META_BWDK_ASSIGN_URL);
        $status = BWDK_OrderStatus::label($raw_json["status"] ?? 2);
        $txn_id = (string)"";
        $trace_id = (string)"";
        $gateway_name = $raw_json["payment"]["gateway_name"] ?? "_";
        $gateway_type_display = $raw_json["payment"]["gateway_type_display"] ?? "_";
        $gateway_type = $raw_json["payment"]["gateway_type"] ?? 0;
        $updated = (string)$order->get_payment_method_title();

        if ($updated) {
            $updated = $order->get_date_modified() ? $order->get_date_modified()->date_i18n('Y-m-d H:i') : '—';
        }

        ob_start();
        ?>
        <div class="bwdk-meta">
            <div class="row"><span class="key">وضعیت</span><span class="val"><?= esc_html($status ?: '—'); ?></span>
            </div>
            <div class="row"><span class="key">شماره تراکنش</span><span
                        class="val ltr"><?= esc_html($txn_id ?: '—'); ?></span></div>
            <div class="row"><span class="key">Trace ID</span><span
                        class="val ltr"><?= esc_html($trace_id ?: '—'); ?></span></div>
            <div class="row"><span class="key">درگاه پرداخت</span><span
                        class="val"><?= esc_html($gateway_name ?: '—'); ?></span></div>
            <div class="row"><span class="key">نوع پرداخت</span><span
                        class="val"><?= esc_html($gateway_type_display ?: '—'); ?></span></div>
            <div class="row"><span class="key">آخرین بروزرسانی</span><span
                        class="val"><?= esc_html($updated ?: '—'); ?></span></div>

            <?php if (!empty($raw_json)): ?>
                <p class="block-title">داده خام</p>
                <code class="bwdk-code"><?= esc_html($this->prettyJson($raw_json)); ?></code>
                <div class="actions">
                    <a href="#" class="button button-small bwdk-copy-json">کپی JSON</a>
                </div>
            <?php endif; ?>

            <?php if (!empty($order_url)): ?>
                <p class="block-title">آدرس سفارش</p>
                <code class="bwdk-order-url"><?= esc_html($this->prettyJson($order_url)); ?></code>
                <div class="actions">
                    <a href="#" class="button button-small bwdk-copy-order-url">کپی آدرس</a>
                </div>
            <?php endif; ?>

            <?php if (!empty($gateway_type == 2) || $raw_json["status"] == 9): ?>
                <div class="row">

                </div>
                <p class="block-title">استرداد</p>
                <div class="row">
                    <span class="key">استرداد دیجی پی</span>
                    <span class="val">
                        <div class="actions">
                            <a href="" class="button button-small bwdk-refund-digipay"
                               data-order-uuid="<?php echo $order_uuid ?>"
                               data-order-id="<?php echo $order->get_id() ?>"
                            >استرداد سفارش</a>
                        </div>
                    </span>
                </div>

            <?php endif; ?>

            <div class="row"><span class="key">آخرین بروزرسانی</span><span
                        class="val"><?= esc_html($updated ?: '—'); ?></span></div>
        </div>
        <?php
        return (string)ob_get_clean();
    }

    protected function wrapAsPanel(string $inner): string
    {
        return '<div class="bwdk-woo-panel">' .
            '<h3 class="bwdk-woo-panel__title">' . esc_html(self::TITLE) . '</h3>' .
            '<div class="bwdk-woo-panel__body">' . $inner . '</div>' .
            '</div>';
    }

    protected function prettyJson($raw)
    {
        $encoded = json_encode($raw);
        $decoded = json_decode($encoded, true);
        if (json_last_error() === JSON_ERROR_NONE) {
            return json_encode($decoded, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);
        }
        return $raw;
    }
}
