<?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']);
        add_action('admin_notices', [$this, 'displaySyncNotice']);
    }

    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();
        $reference_code = ReferenceCodeHelper::extractFromOrder($order);

        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>
            <?php if ($reference_code !== ''): ?>
                <div class="row"><span class="key"><?php esc_html_e('کد پیگیری دیجی‌کالایی', 'bwdk'); ?></span>
                    <span class="val ltr"><?= esc_html($reference_code); ?></span></div>
            <?php endif; ?>
            <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 
            // Show sync/verify button for all BWDK orders
            $is_bwdk_order = !empty($order_uuid);
            if ($is_bwdk_order): 
            ?>
                <p class="block-title">به‌روزرسانی</p>
                <div class="row">
                    <span class="key">به‌روزرسانی سفارش</span>
                    <span class="val">
                        <div class="actions">
                            <button type="button" class="button button-primary bwdk-sync-order"
                                    data-order-id="<?php echo esc_attr($order->get_id()) ?>"
                                    data-order-uuid="<?php echo esc_attr($order_uuid) ?>">
                                به‌روزرسانی سفارش
                            </button>
                        </div>
                    </span>
                </div>
            <?php endif; ?>

            <?php 
            // Show refund button ONLY if Digipay is detected (from meta data)
            // Check gateway_name == "Digipay" OR gateway_type == 2
            $is_digipay = false;
            if (!empty($raw_json) && isset($raw_json["payment"])) {
                $payment = $raw_json["payment"];
                $gateway_name_check = isset($payment["gateway_name"]) && strtolower($payment["gateway_name"]) === 'digipay';
                $gateway_type_check = isset($payment["gateway_type"]) && (int)$payment["gateway_type"] === 2;
                $is_digipay = $gateway_name_check || $gateway_type_check;
            }
            
            if ($is_bwdk_order && $is_digipay): 
            ?>
                <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 esc_attr($order_uuid) ?>"
                               data-order-id="<?php echo esc_attr($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;
    }

    /**
     * Display admin notice after sync operation
     */
    public function displaySyncNotice(): void
    {
        $screen = get_current_screen();
        if (!$screen || (strpos($screen->id, 'shop_order') === false && strpos($screen->id, 'woocommerce_page_wc-orders') === false)) {
            return;
        }

        $order_id = 0;
        if (isset($_GET['post'])) {
            $order_id = absint($_GET['post']);
        } elseif (isset($_GET['id'])) {
            $order_id = absint($_GET['id']);
        }

        if (!$order_id) {
            return;
        }

        $notice_key = 'bwdk_sync_notice_' . $order_id;
        $notice = get_transient($notice_key);
        
        if ($notice && is_array($notice)) {
            delete_transient($notice_key);
            
            $type = $notice['type'] ?? 'info';
            $message = $notice['message'] ?? '';
            
            if (!empty($message)) {
                $class = 'notice notice-' . esc_attr($type) . ' is-dismissible';
                printf(
                    '<div class="%1$s"><p>%2$s</p></div>',
                    esc_attr($class),
                    esc_html($message)
                );
            }
        }
    }
}
