<?php

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

class AIEO_MOI_Order_Meta_Box {

    private static $instance = null;
    public static function instance() {
        if (self::$instance === null) { self::$instance = new self(); }
        return self::$instance;
    }

    private function __construct() {
        
        add_action('add_meta_boxes',                                 array($this, 'register_meta_box'));
        
        add_filter('manage_woocommerce_page_wc-orders_columns',      array($this, 'add_column'), 12);
        add_filter('manage_edit-shop_order_columns',                 array($this, 'add_column'), 12);
        add_action('manage_woocommerce_page_wc-orders_custom_column', array($this, 'render_column'), 99, 2);
        add_action('manage_shop_order_posts_custom_column',          array($this, 'render_column'), 99, 2);
        
        add_filter('woocommerce_shop_order_search_fields',           array($this, 'add_search_field'));
    }

    public function register_meta_box() {
        
        add_meta_box(
            'aieo_moi_order',
            __('Marketplace Order', 'ai-eshop-optimizer'),
            array($this, 'render_meta_box'),
            wc_get_page_screen_id('shop-order'),
            'side',
            'high'
        );
        
        add_meta_box(
            'aieo_moi_order',
            __('Marketplace Order', 'ai-eshop-optimizer'),
            array($this, 'render_meta_box'),
            'shop_order',
            'side',
            'high'
        );
    }

    public function render_meta_box($post_or_order) {
        $order = ($post_or_order instanceof WP_Post)
            ? wc_get_order($post_or_order->ID)
            : $post_or_order;
        if (!$order || !is_a($order, 'WC_Order')) {
            echo '<p>' . esc_html__('Not a Woo order.', 'ai-eshop-optimizer') . '</p>';
            return;
        }
        $vendor_id = (int) $order->get_meta('_aieo_moi_vendor_id');
        $remote_id = (string) $order->get_meta('_aieo_moi_remote_order_id');
        if ($vendor_id <= 0 || $remote_id === '') {
            echo '<p style="color:#646970;font-size:12px;">' . esc_html__('Not a marketplace order.', 'ai-eshop-optimizer') . '</p>';
            return;
        }
        $vendor = AIEO_MOI_Vendor_Manager::get($vendor_id);
        $vendor_label = $vendor ? $vendor['label'] : '—';
        $state        = (string) $order->get_meta('_aieo_moi_state');
        $voucher_url  = (string) $order->get_meta('_aieo_moi_voucher_url');
        $code         = (string) $order->get_meta('_aieo_moi_remote_code');
        $courier      = (string) $order->get_meta('_aieo_moi_courier');
        $tracking_raw = (string) $order->get_meta('_aieo_moi_tracking_codes');
        $tracking     = json_decode($tracking_raw, true);
        $tracking     = is_array($tracking) ? $tracking : array();

        $rest_root  = esc_url_raw(rest_url('moi/v1/orders/' . $order->get_id() . '/'));
        $rest_nonce = wp_create_nonce('wp_rest');

        echo '<p><strong>' . esc_html__('Vendor:', 'ai-eshop-optimizer') . '</strong> ' . esc_html($vendor_label) . '</p>';
        echo '<p><strong>' . esc_html__('Remote ID:', 'ai-eshop-optimizer') . '</strong> <code>' . esc_html($remote_id) . '</code>';
        if ($code !== '') { echo ' &nbsp;<small>(' . esc_html($code) . ')</small>'; }
        echo '</p>';
        if ($state !== '') {
            echo '<p><strong>' . esc_html__('State:', 'ai-eshop-optimizer') . '</strong> <span class="aieo-moi-state aieo-moi-state-' . esc_attr(sanitize_html_class($state)) . '">' . esc_html($state) . '</span></p>';
        }
        if ($courier !== '') {
            echo '<p><strong>' . esc_html__('Courier:', 'ai-eshop-optimizer') . '</strong> ' . esc_html($courier) . '</p>';
        }
        if (!empty($tracking)) {
            echo '<p><strong>' . esc_html__('Tracking:', 'ai-eshop-optimizer') . '</strong><br>';
            foreach ($tracking as $t) { echo '<code>' . esc_html((string) $t) . '</code> '; }
            echo '</p>';
        }
        if ($voucher_url !== '') {
            echo '<p><a class="button button-primary" href="' . esc_url($voucher_url) . '" target="_blank" rel="noopener">' . esc_html__('Print voucher', 'ai-eshop-optimizer') . '</a></p>';
        } else {
            echo '<p><em style="color:#646970;font-size:12px;">' . esc_html__('No voucher yet.', 'ai-eshop-optimizer') . '</em></p>';
        }

        echo '<div class="aieo-moi-actions" style="display:flex;flex-direction:column;gap:6px;margin-top:10px;">';
        echo '<button type="button" class="button button-secondary" data-aieo-moi-action="accept">' . esc_html__('Accept on marketplace', 'ai-eshop-optimizer') . '</button>';
        echo '<button type="button" class="button button-secondary" data-aieo-moi-action="voucher">' . esc_html__('Refresh voucher', 'ai-eshop-optimizer') . '</button>';
        echo '<button type="button" class="button button-link-delete" data-aieo-moi-action="reject">' . esc_html__('Reject', 'ai-eshop-optimizer') . '</button>';
        echo '<span class="aieo-moi-status" style="color:#646970;font-size:12px;"></span>';
        echo '</div>';

        echo '<style>
            .aieo-moi-state{display:inline-block;padding:2px 8px;border-radius:4px;background:#e5e7eb;font-size:11px;font-weight:600;}
            .aieo-moi-state-accepted{background:#dcfce7;color:#15803d;}
            .aieo-moi-state-rejected{background:#fee2e2;color:#b91c1c;}
            .aieo-moi-state-shipped{background:#dbeafe;color:#1d4ed8;}
        </style>';

        echo '<script>(function(){
            var root = document.getElementById("aieo_moi_order");
            if (!root) return;
            var status = root.querySelector(".aieo-moi-status");
            root.querySelectorAll("[data-aieo-moi-action]").forEach(function(btn){
                btn.addEventListener("click", function(){
                    var action = btn.getAttribute("data-aieo-moi-action");
                    var body = {};
                    if (action === "reject") {
                        var reason = prompt("' . esc_js(__('Reason for rejection (optional):', 'ai-eshop-optimizer')) . '") || "";
                        body.reason = reason;
                    }
                    btn.disabled = true;
                    status.style.color = "#646970";
                    status.textContent = "' . esc_js(__('Working…', 'ai-eshop-optimizer')) . '";
                    fetch("' . esc_js($rest_root) . '" + action, {
                        method: "POST",
                        credentials: "same-origin",
                        headers: { "Content-Type": "application/json", "X-WP-Nonce": "' . esc_js($rest_nonce) . '" },
                        body: JSON.stringify(body)
                    }).then(function(r){return r.json();}).then(function(j){
                        btn.disabled = false;
                        if (j && (j.ok || j.success)) {
                            status.style.color = "#15803d";
                            status.textContent = j.message || "' . esc_js(__('Done.', 'ai-eshop-optimizer')) . '";
                            setTimeout(function(){ window.location.reload(); }, 800);
                        } else {
                            status.style.color = "#b91c1c";
                            status.textContent = (j && j.message) || "' . esc_js(__('Failed.', 'ai-eshop-optimizer')) . '";
                        }
                    }).catch(function(){
                        btn.disabled = false;
                        status.style.color = "#b91c1c";
                        status.textContent = "' . esc_js(__('Network error.', 'ai-eshop-optimizer')) . '";
                    });
                });
            });
        })();</script>';
    }

    public function add_column($columns) {
        $columns['aieo_moi_marketplace'] = __('Marketplace', 'ai-eshop-optimizer');
        return $columns;
    }

    public function render_column($column, $order_id) {
        if ($column !== 'aieo_moi_marketplace') { return; }
        $order = ($order_id instanceof WP_Post) ? wc_get_order($order_id->ID) : (is_numeric($order_id) ? wc_get_order((int) $order_id) : $order_id);
        if (!$order) { return; }
        $vendor_id = (int) $order->get_meta('_aieo_moi_vendor_id');
        if ($vendor_id <= 0) { echo '—'; return; }

        $remote_id    = (string) $order->get_meta('_aieo_moi_remote_order_id');
        $remote_code  = (string) $order->get_meta('_aieo_moi_remote_code');
        $state        = (string) $order->get_meta('_aieo_moi_state');
        $courier      = (string) $order->get_meta('_aieo_moi_courier');
        $voucher_url  = (string) $order->get_meta('_aieo_moi_voucher_url');
        $tracking_raw = (string) $order->get_meta('_aieo_moi_tracking_codes');
        $tracking     = json_decode($tracking_raw, true);
        $tracking     = is_array($tracking) ? $tracking : array();
        $vendor       = AIEO_MOI_Vendor_Manager::get($vendor_id);
        $label        = $vendor ? $vendor['label'] : '?';
        $wc_id        = (int) $order->get_id();

        $accepted   = ($state === 'accepted' || $state === 'shipped');
        $rejected   = ($state === 'rejected' || $state === 'cancelled');
        $is_pending = !$accepted && !$rejected;

        echo '<div class="aieo-moi-cell" data-order="' . esc_attr($wc_id) . '" style="display:flex;flex-direction:column;gap:4px;font-size:12px;">';
        echo '<div><strong>' . esc_html__('Referral:', 'ai-eshop-optimizer') . '</strong> ' . esc_html($label) . '</div>';
        if ($remote_id !== '') {
            $shown = $remote_code !== '' ? $remote_code : $remote_id;
            echo '<div><small><code>' . esc_html($shown) . '</code></small></div>';
        }
        if ($state !== '') {
            echo '<div><span class="aieo-moi-state aieo-moi-state-' . esc_attr(sanitize_html_class($state)) . '">' . esc_html(ucfirst($state)) . '</span></div>';
        }
        if ($accepted && ($courier !== '' || !empty($tracking))) {
            echo '<div style="margin-top:2px;">';
            if ($courier !== '') { echo '<strong>' . esc_html($courier) . '</strong> '; }
            if (!empty($tracking)) {
                $first = (string) reset($tracking);
                echo '<code style="font-size:11px;">' . esc_html($first) . '</code>';
            }
            echo '</div>';
        }

        echo '<div class="aieo-moi-row-actions" style="margin-top:4px;display:flex;flex-wrap:wrap;gap:4px;">';
        if ($is_pending) {
            echo '<button type="button" class="button button-small" data-aieo-moi-row-action="accept" style="background:#15803d;border-color:#15803d;color:#fff;">' . esc_html__('Accept Order', 'ai-eshop-optimizer') . '</button>';
            echo '<button type="button" class="button button-small" data-aieo-moi-row-action="reject" style="background:#b91c1c;border-color:#b91c1c;color:#fff;">' . esc_html__('Reject Order', 'ai-eshop-optimizer') . '</button>';
        }
        if ($accepted) {
            if ($voucher_url !== '') {
                echo '<a class="button button-small" href="' . esc_url($voucher_url) . '" target="_blank" rel="noopener">' . esc_html__('Print Voucher', 'ai-eshop-optimizer') . '</a>';
            } else {
                echo '<button type="button" class="button button-small" data-aieo-moi-row-action="voucher">' . esc_html__('Fetch Voucher', 'ai-eshop-optimizer') . '</button>';
            }
        }
        echo '</div>';
        echo '<span class="aieo-moi-row-status" style="font-size:11px;color:#6b7280;display:none;"></span>';
        echo '</div>';

        $this->maybe_print_row_actions_js();
    }

    
    private function maybe_print_row_actions_js() {
        static $printed = false;
        if ($printed) { return; }
        $printed = true;

        $rest_base   = esc_url_raw(rest_url('moi/v1/orders/'));
        $rest_nonce  = wp_create_nonce('wp_rest');
        $msg_reason  = __('Reason for rejection (optional):', 'ai-eshop-optimizer');
        $msg_working = __('Working…', 'ai-eshop-optimizer');
        $msg_done    = __('Done.', 'ai-eshop-optimizer');
        $msg_failed  = __('Failed.', 'ai-eshop-optimizer');

        ?>
        <style>
            .aieo-moi-state { display:inline-block; padding:1px 6px; border-radius:3px; background:#e5e7eb; font-size:11px; font-weight:600; line-height:1.4; }
            .aieo-moi-state-accepted  { background:#dcfce7; color:#15803d; }
            .aieo-moi-state-rejected,
            .aieo-moi-state-cancelled { background:#fee2e2; color:#b91c1c; }
            .aieo-moi-state-shipped   { background:#dbeafe; color:#1d4ed8; }
        </style>
        <script>
        (function(){
            if (window.__aieoMoiRowActionsBound) return; window.__aieoMoiRowActionsBound = true;
            var REST  = <?php echo wp_json_encode($rest_base); ?>;
            var NONCE = <?php echo wp_json_encode($rest_nonce); ?>;
            document.addEventListener('click', function(e){
                var btn = e.target.closest('[data-aieo-moi-row-action]'); if (!btn) return;
                var cell = btn.closest('.aieo-moi-cell'); if (!cell) return;
                var orderId = cell.getAttribute('data-order'); if (!orderId) return;
                var action  = btn.getAttribute('data-aieo-moi-row-action');
                var body    = {};
                if (action === 'reject') {
                    body.reason = prompt(<?php echo wp_json_encode($msg_reason); ?>) || '';
                }
                var status = cell.querySelector('.aieo-moi-row-status');
                status.style.display = ''; status.style.color = '#6b7280';
                status.textContent = <?php echo wp_json_encode($msg_working); ?>;
                cell.querySelectorAll('[data-aieo-moi-row-action]').forEach(function(b){ b.disabled = true; });
                fetch(REST + orderId + '/' + action, {
                    method: 'POST',
                    credentials: 'same-origin',
                    headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': NONCE },
                    body: JSON.stringify(body)
                }).then(function(r){ return r.json(); }).then(function(j){
                    if (j && (j.ok || j.success)) {
                        status.style.color = '#15803d';
                        status.textContent = (j.message || <?php echo wp_json_encode($msg_done); ?>);
                        setTimeout(function(){ window.location.reload(); }, 700);
                    } else {
                        status.style.color = '#b91c1c';
                        status.textContent = (j && j.message) || <?php echo wp_json_encode($msg_failed); ?>;
                        cell.querySelectorAll('[data-aieo-moi-row-action]').forEach(function(b){ b.disabled = false; });
                    }
                }).catch(function(){
                    status.style.color = '#b91c1c';
                    status.textContent = <?php echo wp_json_encode($msg_failed); ?>;
                    cell.querySelectorAll('[data-aieo-moi-row-action]').forEach(function(b){ b.disabled = false; });
                });
            });
        })();
        </script>
        <?php
    }

    public function add_search_field($fields) {
        $fields[] = '_aieo_moi_remote_order_id';
        $fields[] = '_aieo_moi_remote_code';
        return $fields;
    }
}
