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

        
        
        
        
        
        
        
        
        
        add_action('manage_woocommerce_page_wc-orders_custom_column', array($this, 'maybe_seed_attribution'), 1, 2);
        add_action('manage_shop_order_posts_custom_column',          array($this, 'maybe_seed_attribution'), 1, 2);

        
        
        
        add_action('admin_post_aieo_moi_print_voucher', array($this, 'handle_print_voucher'));
    }

    
    private function complete_on_print_enabled($order = null) {
        return (bool) apply_filters('aieo_moi_complete_on_print', get_option('aieo_moi_complete_on_print', 'yes') === 'yes', $order);
    }

    
    private function voucher_print_href($order_id, $voucher_url) {
        if ($voucher_url === '') { return ''; }
        if (!$this->complete_on_print_enabled($order_id)) { return $voucher_url; }
        return wp_nonce_url(
            admin_url('admin-post.php?action=aieo_moi_print_voucher&order=' . (int) $order_id),
            'aieo_moi_print_voucher_' . (int) $order_id
        );
    }

    
    public function handle_print_voucher() {
        $order_id = isset($_GET['order']) ? absint($_GET['order']) : 0; 
        if (!$order_id || (!current_user_can('manage_woocommerce') && !current_user_can('edit_shop_order', $order_id))) {
            wp_die(esc_html__('You are not allowed to do this.', 'marketplace-order-importer'), '', array('response' => 403));
        }
        check_admin_referer('aieo_moi_print_voucher_' . $order_id);

        $order = wc_get_order($order_id);
        if (!$order) {
            wp_die(esc_html__('Order not found.', 'marketplace-order-importer'), '', array('response' => 404));
        }
        $is_marketplace = ((int) $order->get_meta('_aieo_moi_vendor_id') > 0) || ((string) $order->get_meta('_aieo_moi_remote_order_id') !== '');
        $voucher_url    = (string) $order->get_meta('_aieo_moi_voucher_url');

        if ($is_marketplace
            && $this->complete_on_print_enabled($order)
            && in_array($order->get_status(), array('pending', 'processing', 'on-hold'), true)) {
            $order->update_status('completed', __('Marked completed on marketplace voucher print.', 'marketplace-order-importer'));
        }

        if ($voucher_url !== '') {
            wp_redirect($voucher_url); 
            exit;
        }
        wp_safe_redirect($order->get_edit_order_url());
        exit;
    }

    public function register_meta_box() {
        
        add_meta_box(
            'aieo_moi_order',
            __('Marketplace Order', 'marketplace-order-importer'),
            array($this, 'render_meta_box'),
            wc_get_page_screen_id('shop-order'),
            'side',
            'high'
        );
        
        add_meta_box(
            'aieo_moi_order',
            __('Marketplace Order', 'marketplace-order-importer'),
            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.', 'marketplace-order-importer') . '</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.', 'marketplace-order-importer') . '</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:', 'marketplace-order-importer') . '</strong> ' . esc_html($vendor_label) . '</p>';
        echo '<p><strong>' . esc_html__('Remote ID:', 'marketplace-order-importer') . '</strong> <code>' . esc_html($remote_id) . '</code>';
        if ($code !== '') { echo ' &nbsp;<small>(' . esc_html($code) . ')</small>'; }
        echo '</p>';

        
        
        $imported_via = (string) $order->get_meta('_aieo_moi_imported_via');
        if ($imported_via !== '') {
            $imported_at = (string) $order->get_meta('_aieo_moi_imported_at');
            $is_reconcile = ($imported_via === 'reconcile');
            $bg = $is_reconcile ? '#fef3c7' : '#e5e7eb';
            $fg = $is_reconcile ? '#92400e' : '#374151';
            $label_text = $is_reconcile
                ? __('Reconciled (caught by manual backfill — was missed by webhook/poll)', 'marketplace-order-importer')
                : sprintf( __('Imported via %s', 'marketplace-order-importer'), $imported_via);
            echo '<p><span style="display:inline-block;padding:3px 10px;border-radius:4px;background:' . esc_attr($bg) . ';color:' . esc_attr($fg) . ';font-size:11px;font-weight:600;">' . esc_html($label_text) . '</span>';
            if ($imported_at !== '') {
                echo ' <small style="color:#6b7280;">' . esc_html($imported_at) . ' UTC</small>';
            }
            echo '</p>';
        }
        if ($state !== '') {
            echo '<p><strong>' . esc_html__('State:', 'marketplace-order-importer') . '</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:', 'marketplace-order-importer') . '</strong> ' . esc_html($courier) . '</p>';
        }
        if (!empty($tracking)) {
            echo '<p><strong>' . esc_html__('Tracking:', 'marketplace-order-importer') . '</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($this->voucher_print_href($order->get_id(), $voucher_url)) . '" target="_blank" rel="noopener">' . esc_html__('Print voucher', 'marketplace-order-importer') . '</a></p>';
        } else {
            echo '<p><em style="color:#646970;font-size:12px;">' . esc_html__('No voucher yet.', 'marketplace-order-importer') . '</em></p>';
        }

        
        
        
        
        $accept_options_raw = (string) $order->get_meta('_aieo_moi_accept_options');
        $accept_options     = $accept_options_raw !== '' ? json_decode($accept_options_raw, true) : null;
        $needs_accept_form  = ($state === 'open' || $state === '')
            && is_array($accept_options)
            && (!empty($accept_options['pickup_location']) || !empty($accept_options['pickup_window']));

        echo '<div class="aieo-moi-actions" style="display:flex;flex-direction:column;gap:6px;margin-top:10px;">';

        if ($needs_accept_form) {
            $locs = is_array($accept_options['pickup_location']) ? $accept_options['pickup_location'] : array();
            $wins = is_array($accept_options['pickup_window'])   ? $accept_options['pickup_window']   : array();

            echo '<div class="aieo-moi-accept-form" style="border:1px solid #e5e7eb;border-radius:4px;padding:8px;margin-bottom:4px;background:#fafafa;">';
            echo '<p style="margin:0 0 6px;font-size:12px;color:#374151;"><strong>' . esc_html__('Accept details', 'marketplace-order-importer') . '</strong></p>';

            echo '<label style="display:block;font-size:11px;color:#6b7280;margin-bottom:2px;">' . esc_html__('Pickup location', 'marketplace-order-importer') . '</label>';
            echo '<select class="aieo-moi-pickup-location" style="width:100%;margin-bottom:6px;">';
            foreach ($locs as $loc) {
                $id = isset($loc['id']) ? (string) $loc['id'] : '';
                if ($id === '') { continue; }
                $lbl = isset($loc['label']) ? (string) $loc['label'] : $id;
                echo '<option value="' . esc_attr($id) . '">' . esc_html($lbl) . '</option>';
            }
            echo '</select>';

            echo '<label style="display:block;font-size:11px;color:#6b7280;margin-bottom:2px;">' . esc_html__('Pickup window', 'marketplace-order-importer') . '</label>';
            echo '<select class="aieo-moi-pickup-window" style="width:100%;margin-bottom:6px;">';
            foreach ($wins as $win) {
                $id = isset($win['id']) ? (string) $win['id'] : '';
                if ($id === '') { continue; }
                $lbl = isset($win['label']) ? (string) $win['label'] : $id;
                echo '<option value="' . esc_attr($id) . '">' . esc_html($lbl) . '</option>';
            }
            echo '</select>';

            echo '<label style="display:block;font-size:11px;color:#6b7280;margin-bottom:2px;">' . esc_html__('Number of parcels', 'marketplace-order-importer') . '</label>';
            echo '<input type="number" class="aieo-moi-parcels" value="1" min="1" max="20" style="width:80px;">';
            echo '</div>';
        }

        
        
        
        
        
        
        
        
        
        
        $mb_state_lower      = strtolower((string) $state);
        $mb_pending_states   = array('', 'open', 'pending', 'registered');
        $mb_rejected_states  = array('rejected', 'cancelled', 'canceled');
        $mb_is_pending = in_array($mb_state_lower, $mb_pending_states, true);
        $mb_is_rejected = in_array($mb_state_lower, $mb_rejected_states, true);

        if ($mb_is_pending) {
            echo '<button type="button" class="button button-secondary" data-aieo-moi-action="accept">' . esc_html__('Accept on marketplace', 'marketplace-order-importer') . '</button>';
            echo '<button type="button" class="button button-link-delete" data-aieo-moi-action="reject">' . esc_html__('Reject', 'marketplace-order-importer') . '</button>';
        }
        
        
        
        if (!$mb_is_pending && !$mb_is_rejected) {
            echo '<button type="button" class="button button-secondary" data-aieo-moi-action="voucher">' . esc_html__('Refresh voucher', 'marketplace-order-importer') . '</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):', 'marketplace-order-importer')) . '") || "";
                        body.reason = reason;
                    }
                    // Skroutz accept requires pickup_location, pickup_window,
                    // number_of_parcels. Read whatever dropdowns the render
                    // step emitted; empty payload means there were no accept
                    // options (other vendors, or already-accepted state).
                    if (action === "accept") {
                        var loc  = root.querySelector(".aieo-moi-pickup-location");
                        var win  = root.querySelector(".aieo-moi-pickup-window");
                        var parc = root.querySelector(".aieo-moi-parcels");
                        if (loc && loc.value)  { body.pickup_location  = loc.value; }
                        if (win && win.value)  { body.pickup_window    = parseInt(win.value, 10); }
                        if (parc && parc.value) { body.number_of_parcels = parseInt(parc.value, 10) || 1; }
                    }
                    btn.disabled = true;
                    status.style.color = "#646970";
                    status.textContent = "' . esc_js(__('Working…', 'marketplace-order-importer')) . '";
                    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.', 'marketplace-order-importer')) . '";
                            setTimeout(function(){ window.location.reload(); }, 800);
                        } else {
                            status.style.color = "#b91c1c";
                            status.textContent = (j && j.message) || "' . esc_js(__('Failed.', 'marketplace-order-importer')) . '";
                        }
                    }).catch(function(){
                        btn.disabled = false;
                        status.style.color = "#b91c1c";
                        status.textContent = "' . esc_js(__('Network error.', 'marketplace-order-importer')) . '";
                    });
                });
            });
        })();</script>';
    }

    public function add_column($columns) {
        $columns['aieo_moi_marketplace'] = __('Marketplace', 'marketplace-order-importer');
        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();
        $imported_via = (string) $order->get_meta('_aieo_moi_imported_via');
        $vendor       = AIEO_MOI_Vendor_Manager::get($vendor_id);
        $label        = $vendor ? $vendor['label'] : '?';
        $wc_id        = (int) $order->get_id();

        
        
        
        
        
        
        
        
        
        
        $state_lower = strtolower((string) $state);
        $pending_states  = array('', 'open', 'pending', 'registered');
        $rejected_states = array('rejected', 'cancelled', 'canceled');
        $is_pending = in_array($state_lower, $pending_states, true);
        $rejected   = in_array($state_lower, $rejected_states, true);
        $accepted   = !$is_pending && !$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:', 'marketplace-order-importer') . '</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', 'marketplace-order-importer') . '</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', 'marketplace-order-importer') . '</button>';
        }
        if ($accepted) {
            if ($voucher_url !== '') {
                echo '<a class="button button-small" href="' . esc_url($this->voucher_print_href($order->get_id(), $voucher_url)) . '" target="_blank" rel="noopener">' . esc_html__('Print Voucher', 'marketplace-order-importer') . '</a>';
            } else {
                echo '<button type="button" class="button button-small" data-aieo-moi-row-action="voucher">' . esc_html__('Fetch Voucher', 'marketplace-order-importer') . '</button>';
            }
        }
        echo '</div>';
        echo '<span class="aieo-moi-row-status" style="font-size:11px;color:#6b7280;display:none;"></span>';
        
        if ($imported_via === 'reconcile') {
            echo '<span title="' . esc_attr__('This order was missed by the normal webhook/poll flow and was caught by a manual reconcile.', 'marketplace-order-importer') . '" style="display:inline-block;margin-top:2px;padding:1px 6px;border-radius:3px;background:#fef3c7;color:#92400e;font-size:10px;font-weight:600;">' . esc_html__('RECONCILED', 'marketplace-order-importer') . '</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):', 'marketplace-order-importer');
        $msg_working = __('Working…', 'marketplace-order-importer');
        $msg_done    = __('Done.', 'marketplace-order-importer');
        $msg_failed  = __('Failed.', 'marketplace-order-importer');

        ?>
        <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); ?>) || '';
                }
                // Accept body is intentionally empty here — the REST handler
                // server-side defaults pickup_location/pickup_window to the
                // first entry from the order's accept_options meta. Operators
                // wanting a SPECIFIC pickup window must open the order edit
                // page, where dropdowns are wired to send explicit values.
                // Keeping the orders-list per-row payload empty avoids
                // emitting per-row inline JSON that would balloon HTML at
                // 100+ orders / page.
                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;
    }

    
    public function maybe_seed_attribution($column, $order_id) {
        if ($column !== 'origin') { 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 || !is_a($order, 'WC_Order')) { return; }

        $provider_slug = (string) $order->get_meta('_aieo_moi_provider');
        if ($provider_slug === '') { return; } 

        
        
        $existing_type   = (string) $order->get_meta('_wc_order_attribution_source_type');
        $existing_source = (string) $order->get_meta('_wc_order_attribution_utm_source');
        if ($existing_type !== '' || $existing_source !== '') { return; }

        self::seed_attribution_meta($order, $provider_slug);
    }

    
    public static function seed_attribution_meta(WC_Order $order, $provider_slug) {
        $provider_slug = (string) $provider_slug;
        if ($provider_slug === '') { return; }

        $label = '';
        if (class_exists('AIEO_MOI_Provider_Registry')) {
            $provider_obj = AIEO_MOI_Provider_Registry::get($provider_slug);
            if ($provider_obj && method_exists($provider_obj, 'label')) {
                $label = (string) $provider_obj->label();
            }
        }
        if ($label === '') { $label = ucfirst($provider_slug); }

        $order->update_meta_data('_wc_order_attribution_source_type', 'utm');
        $order->update_meta_data('_wc_order_attribution_utm_source',  $label);
        $order->update_meta_data('_wc_order_attribution_utm_medium',  'aieo_marketplace');
        $order->save_meta_data();
    }
}
