<?php
/**
 * Bizmart Core — Orders AJAX Handlers.
 *
 * @package Bizmart
 * @license GPL-2.0-or-later
 */
if (!defined('ABSPATH')) exit;

// phpcs:disable WordPress.Security.NonceVerification.Missing, WordPress.PHP.DevelopmentFunctions.error_log_error_log

// ORDERS MODULE — AJAX Endpoints (reads WooCommerce orders)
// ============================================================

/**
 * AJAX: Get paginated orders list with filters + stats
 */
function bizmart_normalize_orders_query_results($results, int $page, int $per_page): array {
    $normalized = [
        'orders' => [],
        'total' => 0,
        'total_pages' => 1,
    ];

    if (is_object($results) && isset($results->orders)) {
        $normalized['orders'] = is_array($results->orders) ? $results->orders : [];
        $normalized['total'] = isset($results->total) ? (int) $results->total : count($normalized['orders']);
        $normalized['total_pages'] = isset($results->max_num_pages) ? (int) $results->max_num_pages : 1;
        return $normalized;
    }

    if (is_array($results) && isset($results['orders'])) {
        $normalized['orders'] = is_array($results['orders']) ? $results['orders'] : [];
        $normalized['total'] = isset($results['total']) ? (int) $results['total'] : count($normalized['orders']);
        $normalized['total_pages'] = isset($results['max_num_pages']) ? (int) $results['max_num_pages'] : 1;
        return $normalized;
    }

    if (is_array($results)) {
        $normalized['orders'] = $results;
        $normalized['total'] = count($results);
        $normalized['total_pages'] = max(1, (int) ceil(max(1, $normalized['total']) / max(1, $per_page)));
    }

    return $normalized;
}

/**
 * Safely get payment gateways for admin filters without checkout-only availability checks.
 */
function bizmart_get_order_gateway_options(): array {
    if (!function_exists('WC')) {
        return [];
    }

    $woocommerce = WC();
    if (!$woocommerce || !method_exists($woocommerce, 'payment_gateways')) {
        return [];
    }

    $gateway_manager = $woocommerce->payment_gateways();
    if (!$gateway_manager || !method_exists($gateway_manager, 'payment_gateways')) {
        return [];
    }

    $gateways = [];
    foreach ((array) $gateway_manager->payment_gateways() as $gateway) {
        if (!is_object($gateway) || empty($gateway->id)) {
            continue;
        }

        $title = method_exists($gateway, 'get_title') ? (string) $gateway->get_title() : (string) ($gateway->title ?? $gateway->id);
        $gateways[] = [
            'id' => (string) $gateway->id,
            'title' => $title !== '' ? $title : (string) $gateway->id,
        ];
    }

    return $gateways;
}

add_action('wp_ajax_bizmart_get_orders', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);
    if (!function_exists('wc_get_orders')) wp_send_json_error('WooCommerce not active');

    try {
        $page     = max(1, min(10000, intval(wp_unslash($_POST['page'] ?? 1))));
        $per_page = max(1, min(100, intval(wp_unslash($_POST['per_page'] ?? 25))));
        $status   = sanitize_text_field(wp_unslash($_POST['status'] ?? ''));
        $search   = sanitize_text_field(wp_unslash($_POST['search'] ?? ''));
        $payment  = sanitize_text_field(wp_unslash($_POST['payment_method'] ?? ''));
        $start    = sanitize_text_field(wp_unslash($_POST['start_date'] ?? ''));
        $end      = sanitize_text_field(wp_unslash($_POST['end_date'] ?? ''));
        $orderby  = sanitize_text_field(wp_unslash($_POST['orderby'] ?? 'date'));
        $order    = strtoupper(sanitize_text_field(wp_unslash($_POST['order'] ?? 'DESC')));
        if (!in_array($order, ['ASC', 'DESC'], true)) $order = 'DESC';

        $args = [
            'limit'    => $per_page,
            'page'     => $page,
            'orderby'  => $orderby,
            'order'    => $order,
            'paginate' => true,
        ];

        if ($status) {
            $args['status'] = ltrim($status, 'wc-');
        } else {
            $args['status'] = ['pending', 'processing', 'on-hold', 'completed', 'cancelled', 'refunded', 'failed'];
        }

        if ($search) {
            $args['s'] = $search;
        }

        if ($payment) {
            $args['payment_method'] = $payment;
        }

        if ($start) {
            $args['date_created'] = '>=' . $start;
        }
        if ($end) {
            $date_query = isset($args['date_created']) ? $args['date_created'] . '...' . $end : '<=' . $end;
            $args['date_created'] = $date_query;
        }

        $results = bizmart_normalize_orders_query_results(wc_get_orders($args), $page, $per_page);

        $orders = [];
        foreach ($results['orders'] as $wc_order) {
            if ($wc_order instanceof WC_Order) {
                $orders[] = bizmart_format_order_row($wc_order);
            }
        }

        wp_send_json_success([
            'orders'          => $orders,
            'total'           => $results['total'],
            'total_pages'     => $results['total_pages'],
            'page'            => $page,
            'stats'           => bizmart_get_order_stats(),
            'status_counts'   => bizmart_get_order_status_counts(),
            'daily_trend'     => bizmart_get_daily_trend(),
            'payment_methods' => bizmart_get_payment_method_stats(),
            'gateways'        => bizmart_get_order_gateway_options(),
        ]);
    } catch (Throwable $exception) {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Bizmart orders AJAX failed: ' . $exception->getMessage());
        }

        wp_send_json_error([
            'message' => bizmart_text(
                'Unable to load the orders dashboard right now. Please refresh the page.',
                'Impossible de charger le tableau des commandes pour le moment. Veuillez actualiser la page.',
                'تعذر تحميل لوحة الطلبات الآن. يرجى تحديث الصفحة.'
            ),
        ]);
    }
});

/**
 * Format a WC_Order into a summary row array.
 */
function bizmart_format_order_row($wc_order) {
    $billing_name = trim($wc_order->get_billing_first_name() . ' ' . $wc_order->get_billing_last_name());
    $items = $wc_order->get_items();
    $item_count = 0;
    $preview_parts = [];
    foreach ($items as $item) {
        $item_count += $item->get_quantity();
        if (count($preview_parts) < 3) {
            $preview_parts[] = $item->get_name() . ' ×' . $item->get_quantity();
        }
    }
    $item_preview = implode(', ', $preview_parts);
    if (count($items) > 3) {
        $item_preview .= '…';
    }

    // Calculate gains (total minus cost of goods)
    $gains = bizmart_calculate_order_gains($wc_order);

    return [
        'id'             => $wc_order->get_id(),
        'number'         => $wc_order->get_order_number(),
        'status'         => $wc_order->get_status(),
        'date_created'   => $wc_order->get_date_created() ? $wc_order->get_date_created()->format('Y-m-d H:i:s') : '',
        'total'          => $wc_order->get_total(),
        'billing_name'   => $billing_name,
        'billing_email'  => $wc_order->get_billing_email(),
        'item_count'     => $item_count,
        'item_preview'   => $item_preview,
        'payment_method' => $wc_order->get_payment_method(),
        'payment_title'  => $wc_order->get_payment_method_title(),
        'gains'          => $gains,
    ];
}

/**
 * Calculate gains for an order (total - cost of goods).
 */
function bizmart_calculate_order_gains($wc_order) {
    static $purchase_price_cache = [];

    if (function_exists('bizmart_analytics_get_order_line_metrics')) {
        $metrics = bizmart_analytics_get_order_line_metrics($wc_order, $purchase_price_cache);
        return round((float) ($metrics['profit'] ?? 0), 2);
    }

    $total_cost = 0;
    foreach ($wc_order->get_items() as $item) {
        $product_id = $item->get_product_id();
        $qty = $item->get_quantity();
        $cost = 0;

        // Try purchase price meta
        $purchase_price = get_post_meta($product_id, '_purchase_price', true);
        if (!$purchase_price) {
            $purchase_price = get_post_meta($product_id, '_alg_wc_cog_cost', true);
        }
        if ($purchase_price && is_numeric($purchase_price)) {
            $cost = floatval($purchase_price);
        } elseif (function_exists('bizmart_get_wac')) {
            $cost = bizmart_get_wac($product_id);
        }

        $total_cost += $cost * $qty;
    }

    return round(floatval($wc_order->get_total()) - $total_cost, 2);
}

/**
 * Get overall order stats.
 */
function bizmart_get_order_stats() {
    $reporting_statuses = function_exists('bizmart_analytics_reporting_statuses')
        ? bizmart_analytics_reporting_statuses()
        : ['completed', 'processing', 'on-hold'];

    $month_windows = function_exists('bizmart_analytics_get_month_windows')
        ? bizmart_analytics_get_month_windows()
        : [
            'today' => wp_date('Y-m-d'),
            'this_month_start' => wp_date('Y-m-01'),
            'last_month_start' => wp_date('Y-m-01'),
            'last_month_end' => wp_date('Y-m-d'),
        ];

    $today = $month_windows['today'];
    $this_month_start = $month_windows['this_month_start'];
    $last_month_start = $month_windows['last_month_start'];
    $last_month_end = $month_windows['last_month_end'];

    $orders = function_exists('bizmart_analytics_get_orders_range')
        ? bizmart_analytics_get_orders_range('2000-01-01', $today, $reporting_statuses)
        : wc_get_orders([
            'status' => $reporting_statuses,
            'limit' => -1,
            'type' => 'shop_order',
            'date_created' => '2000-01-01 00:00:00...' . $today . ' 23:59:59',
        ]);

    $purchase_price_cache = [];
    $total_sales = 0.0;
    $total_gains = 0.0;
    $this_month = 0.0;
    $this_month_gains = 0.0;
    $last_month = 0.0;
    $total_orders = 0;
    $today_count = 0;
    $today_sales = 0.0;

    foreach ($orders as $order) {
        if ($order instanceof WC_Order_Refund) {
            continue;
        }

        $date_created = $order->get_date_created();
        $order_day = $date_created ? $date_created->date('Y-m-d') : $today;
        $metrics = function_exists('bizmart_analytics_get_order_line_metrics')
            ? bizmart_analytics_get_order_line_metrics($order, $purchase_price_cache)
            : ['sales' => (float) $order->get_total(), 'profit' => bizmart_calculate_order_gains($order)];

        $sales = (float) ($metrics['sales'] ?? 0);
        $profit = (float) ($metrics['profit'] ?? 0);

        $total_sales += $sales;
        $total_gains += $profit;
        $total_orders++;

        if ($order_day >= $this_month_start) {
            $this_month += $sales;
            $this_month_gains += $profit;
        }

        if ($order_day >= $last_month_start && $order_day <= $last_month_end) {
            $last_month += $sales;
        }

        if ($order_day === $today) {
            $today_count++;
            $today_sales += $sales;
        }
    }

    $pending_count = 0;
    if (function_exists('wc_get_orders')) {
        foreach (['pending', 'on-hold', 'failed'] as $st) {
            $pending_count += count(wc_get_orders(['status' => $st, 'limit' => -1, 'return' => 'ids', 'type' => 'shop_order']));
        }
    }

    $avg_order = $total_orders > 0 ? round($total_sales / $total_orders, 2) : 0.0;

    return [
        'total_sales' => round($total_sales, 2),
        'total_gains' => round($total_gains, 2),
        'this_month' => round($this_month, 2),
        'this_month_gains' => round($this_month_gains, 2),
        'last_month' => round($last_month, 2),
        'avg_order' => $avg_order,
        'total_orders' => $total_orders,
        'pending_count' => $pending_count,
        'today_count' => $today_count,
        'today_sales' => round($today_sales, 2),
    ];
}

/**
 * Get order counts per status.
 */
function bizmart_get_order_status_counts() {
    $statuses = ['pending', 'processing', 'on-hold', 'completed', 'cancelled', 'refunded', 'failed'];
    $counts = [];
    // Use wc_orders_count() or direct SQL for efficiency
    if (function_exists('wc_orders_count')) {
        foreach ($statuses as $s) {
            $counts[] = ['status' => $s, 'count' => (int) wc_orders_count($s, 'shop_order')];
        }
    } else {
        foreach ($statuses as $s) {
            $result = wc_get_orders([
                'status' => 'wc-' . $s,
                'limit'  => -1,
                'return' => 'ids',
            ]);
            $counts[] = ['status' => $s, 'count' => count($result)];
        }
    }
    return $counts;
}

/**
 * Get daily order trend for the last 30 days.
 */
function bizmart_get_daily_trend() {
    $days_ago = wp_date('Y-m-d', strtotime('-30 days'));
    $today = wp_date('Y-m-d');
    $reporting_statuses = function_exists('bizmart_analytics_reporting_statuses')
        ? bizmart_analytics_reporting_statuses()
        : ['completed', 'processing', 'on-hold'];
    $orders = function_exists('bizmart_analytics_get_orders_range')
        ? bizmart_analytics_get_orders_range($days_ago, $today, $reporting_statuses)
        : [];

    $purchase_price_cache = [];
    $buckets = [];
    foreach ($orders as $order) {
        if ($order instanceof WC_Order_Refund) {
            continue;
        }

        $date_created = $order->get_date_created();
        $day = $date_created ? $date_created->date('Y-m-d') : $today;
        if (!isset($buckets[$day])) {
            $buckets[$day] = ['day' => $day, 'count' => 0, 'total' => 0.0];
        }

        $metrics = function_exists('bizmart_analytics_get_order_line_metrics')
            ? bizmart_analytics_get_order_line_metrics($order, $purchase_price_cache)
            : ['sales' => (float) $order->get_total()];

        $buckets[$day]['count']++;
        $buckets[$day]['total'] += (float) ($metrics['sales'] ?? 0);
    }

    ksort($buckets);

    return array_values(array_map(static function($row) {
        return (object) [
            'day' => $row['day'],
            'count' => (int) $row['count'],
            'total' => round((float) $row['total'], 2),
        ];
    }, $buckets));
}

/**
 * Get payment method statistics.
 */
function bizmart_get_payment_method_stats() {
    $reporting_statuses = function_exists('bizmart_analytics_reporting_statuses')
        ? bizmart_analytics_reporting_statuses()
        : ['completed', 'processing', 'on-hold'];
    $orders = function_exists('bizmart_analytics_get_orders_range')
        ? bizmart_analytics_get_orders_range('2000-01-01', wp_date('Y-m-d'), $reporting_statuses)
        : [];

    $purchase_price_cache = [];
    $grouped = [];
    foreach ($orders as $order) {
        if ($order instanceof WC_Order_Refund) {
            continue;
        }

        $method = (string) $order->get_payment_method();
        if ($method === '') {
            continue;
        }

        $label = (string) $order->get_payment_method_title();
        $key = $method . '|' . $label;
        if (!isset($grouped[$key])) {
            $grouped[$key] = [
                'method' => $method,
                'label' => $label,
                'count' => 0,
                'total' => 0.0,
            ];
        }

        $metrics = function_exists('bizmart_analytics_get_order_line_metrics')
            ? bizmart_analytics_get_order_line_metrics($order, $purchase_price_cache)
            : ['sales' => (float) $order->get_total()];

        $grouped[$key]['count']++;
        $grouped[$key]['total'] += (float) ($metrics['sales'] ?? 0);
    }

    $results = array_values(array_map(static function($row) {
        return (object) [
            'method' => $row['method'],
            'label' => $row['label'],
            'count' => (int) $row['count'],
            'total' => round((float) $row['total'], 2),
        ];
    }, $grouped));

    usort($results, static function($left, $right) {
        return $right->total <=> $left->total;
    });

    return $results;
}

// ============================================================
// UPDATE ORDER STATUS
// ============================================================
add_action('wp_ajax_bizmart_update_order_status', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $order_id  = absint(wp_unslash($_POST['order_id'] ?? 0));
    $status    = sanitize_text_field(wp_unslash($_POST['status'] ?? ''));
    if (!$order_id || !$status) wp_send_json_error('Missing parameters');

    $order = wc_get_order($order_id);
    if (!$order) wp_send_json_error('Order not found');

    $order->update_status($status, 'Status updated via Bizmart.');
    wp_send_json_success(['status' => $order->get_status()]);
});

// ============================================================
// BULK UPDATE ORDER STATUS
// ============================================================
add_action('wp_ajax_bizmart_bulk_update_orders', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $order_ids = isset($_POST['order_ids']) ? array_map('absint', (array) wp_unslash($_POST['order_ids'])) : [];
    $status    = sanitize_text_field(wp_unslash($_POST['status'] ?? ''));
    if (empty($order_ids) || !$status) wp_send_json_error('Missing parameters');

    $updated = 0;
    foreach ($order_ids as $oid) {
        $order = wc_get_order($oid);
        if ($order) {
            $order->update_status($status, 'Bulk status update via Bizmart.');
            $updated++;
        }
    }
    wp_send_json_success(['updated' => $updated]);
});

// ============================================================
// GET ORDER DETAILS (for side panel)
// ============================================================
add_action('wp_ajax_bizmart_get_order_details', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $order_id = absint(wp_unslash($_POST['order_id'] ?? 0));
    if (!$order_id) wp_send_json_error('Missing order ID');

    $order = wc_get_order($order_id);
    if (!$order) wp_send_json_error('Order not found');

    // Line items
    $line_items = [];
    foreach ($order->get_items() as $item_id => $item) {
        $product = $item->get_product();
        $image = '';
        if ($product) {
            $thumb_id = $product->get_image_id();
            if ($thumb_id) {
                $img_src = wp_get_attachment_image_url($thumb_id, 'thumbnail');
                $image = $img_src ? $img_src : '';
            }
        }

        $line_items[] = [
            'id'       => $item_id,
            'name'     => $item->get_name(),
            'sku'      => $product ? $product->get_sku() : '',
            'quantity' => $item->get_quantity(),
            'subtotal' => floatval($item->get_subtotal()),
            'total'    => floatval($item->get_total()),
            'image'    => $image,
        ];
    }

    // Notes
    $notes_raw = wc_get_order_notes(['order_id' => $order_id, 'orderby' => 'date_created', 'order' => 'DESC']);
    $notes = [];
    foreach ($notes_raw as $note) {
        $notes[] = [
            'id'            => $note->id,
            'content'       => $note->content,
            'date'          => $note->date_created ? $note->date_created->format('Y-m-d H:i:s') : '',
            'added_by'      => $note->added_by,
            'customer_note' => $note->customer_note,
        ];
    }

    // Refunds
    $refunds = [];
    foreach ($order->get_refunds() as $refund) {
        $refunds[] = [
            'id'     => $refund->get_id(),
            'amount' => abs(floatval($refund->get_amount())),
            'reason' => $refund->get_reason(),
            'date'   => $refund->get_date_created() ? $refund->get_date_created()->format('Y-m-d H:i:s') : '',
        ];
    }

    // Coupon lines
    $coupon_lines = [];
    foreach ($order->get_coupon_codes() as $code) {
        foreach ($order->get_items('coupon') as $coupon_item) {
            if ($coupon_item->get_code() === $code) {
                $coupon_lines[] = [
                    'code'     => $code,
                    'discount' => floatval($coupon_item->get_discount()),
                ];
            }
        }
    }

    // Gains
    $gains = bizmart_calculate_order_gains($order);

    $data = [
        'id'              => $order->get_id(),
        'number'          => $order->get_order_number(),
        'status'          => $order->get_status(),
        'date_created'    => $order->get_date_created() ? $order->get_date_created()->format('Y-m-d H:i:s') : '',
        'date_paid'       => $order->get_date_paid() ? $order->get_date_paid()->format('Y-m-d H:i:s') : '',
        'total'           => floatval($order->get_total()),
        'subtotal'        => floatval($order->get_subtotal()),
        'discount_total'  => floatval($order->get_discount_total()),
        'shipping_total'  => floatval($order->get_shipping_total()),
        'tax_total'       => floatval($order->get_total_tax()),
        'total_refunded'  => floatval($order->get_total_refunded()),
        'net_total'       => floatval($order->get_total()) - floatval($order->get_total_refunded()),
        'gains'           => $gains,
        'payment_method'  => $order->get_payment_method(),
        'payment_title'   => $order->get_payment_method_title(),
        'transaction_id'  => $order->get_transaction_id(),
        'created_via'     => $order->get_created_via(),
        'customer_note'   => $order->get_customer_note(),
        'billing'         => $order->get_address('billing'),
        'shipping'        => $order->get_address('shipping'),
        'line_items'      => $line_items,
        'notes'           => $notes,
        'refunds'         => $refunds,
        'coupon_lines'    => $coupon_lines,
    ];

    wp_send_json_success($data);
});

// ============================================================
// ADD ORDER NOTE
// ============================================================
add_action('wp_ajax_bizmart_add_order_note', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $order_id    = absint(wp_unslash($_POST['order_id'] ?? 0));
    $note        = sanitize_textarea_field(wp_unslash($_POST['note'] ?? ''));
    $is_customer = sanitize_text_field(wp_unslash($_POST['is_customer'] ?? '0'));
    if (!$order_id || !$note) wp_send_json_error('Missing parameters');

    $order = wc_get_order($order_id);
    if (!$order) wp_send_json_error('Order not found');

    $note_id = $order->add_order_note($note, $is_customer === '1');
    wp_send_json_success(['note_id' => $note_id]);
});

// ============================================================
// DELETE ORDER NOTE
// ============================================================
add_action('wp_ajax_bizmart_delete_order_note', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $note_id = absint(wp_unslash($_POST['note_id'] ?? 0));
    if (!$note_id) wp_send_json_error('Missing note ID');

    $result = wc_delete_order_note($note_id);
    if ($result) {
        wp_send_json_success();
    } else {
        wp_send_json_error('Could not delete note');
    }
});

// ============================================================
// REFUND ORDER
// ============================================================
add_action('wp_ajax_bizmart_refund_order', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $order_id = absint(wp_unslash($_POST['order_id'] ?? 0));
    $amount   = floatval(wp_unslash($_POST['amount'] ?? 0));
    $reason   = sanitize_text_field(wp_unslash($_POST['reason'] ?? ''));
    $restock  = sanitize_text_field(wp_unslash($_POST['restock'] ?? '0'));
    if (!$order_id || $amount <= 0) wp_send_json_error('Invalid parameters');

    $order = wc_get_order($order_id);
    if (!$order) wp_send_json_error('Order not found');

    $refund = wc_create_refund([
        'amount'         => $amount,
        'reason'         => $reason,
        'order_id'       => $order_id,
        'refund_payment' => false,
        'restock_items'  => ($restock === '1'),
    ]);

    if (is_wp_error($refund)) {
        wp_send_json_error($refund->get_error_message());
    }

    wp_send_json_success(['refund_id' => $refund->get_id()]);
});

// ============================================================
// RESEND ORDER EMAIL
// ============================================================
add_action('wp_ajax_bizmart_resend_order_email', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $order_id   = absint(wp_unslash($_POST['order_id'] ?? 0));
    $email_type = sanitize_text_field(wp_unslash($_POST['email_type'] ?? 'new_order'));
    if (!$order_id) wp_send_json_error('Missing order ID');

    $order = wc_get_order($order_id);
    if (!$order) wp_send_json_error('Order not found');

    // Trigger the WooCommerce email
    $emails = WC()->mailer()->get_emails();
    $email_map = [
        'new_order'                 => 'WC_Email_New_Order',
        'customer_processing_order' => 'WC_Email_Customer_Processing_Order',
        'customer_completed_order'  => 'WC_Email_Customer_Completed_Order',
        'customer_invoice'          => 'WC_Email_Customer_Invoice',
    ];

    $class_name = isset($email_map[$email_type]) ? $email_map[$email_type] : 'WC_Email_New_Order';
    foreach ($emails as $email) {
        if (get_class($email) === $class_name) {
            $email->trigger($order_id, $order);
            wp_send_json_success();
            return;
        }
    }

    wp_send_json_error('Email class not found');
});

// ============================================================
// TRASH ORDER
// ============================================================
add_action('wp_ajax_bizmart_trash_order', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $order_id = absint(wp_unslash($_POST['order_id'] ?? 0));
    if (!$order_id) wp_send_json_error('Missing order ID');

    $order = wc_get_order($order_id);
    if (!$order) wp_send_json_error('Order not found');

    $order->update_status('trash');
    wp_send_json_success();
});

// ============================================================
// SEARCH CUSTOMERS
// ============================================================
add_action('wp_ajax_bizmart_search_customers', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $term = sanitize_text_field(wp_unslash($_POST['term'] ?? ''));
    if (strlen($term) < 2) wp_send_json_error('Term too short');

    $users = new WP_User_Query([
        'search'         => '*' . $term . '*',
        'search_columns' => ['user_login', 'user_email', 'user_nicename', 'display_name'],
        'number'         => 20,
        'orderby'        => 'display_name',
        'order'          => 'ASC',
    ]);

    $customers = [];
    foreach ($users->get_results() as $user) {
        $billing = [
            'first_name' => get_user_meta($user->ID, 'billing_first_name', true),
            'last_name'  => get_user_meta($user->ID, 'billing_last_name', true),
            'company'    => get_user_meta($user->ID, 'billing_company', true),
            'address_1'  => get_user_meta($user->ID, 'billing_address_1', true),
            'address_2'  => get_user_meta($user->ID, 'billing_address_2', true),
            'city'       => get_user_meta($user->ID, 'billing_city', true),
            'postcode'   => get_user_meta($user->ID, 'billing_postcode', true),
            'country'    => get_user_meta($user->ID, 'billing_country', true),
            'email'      => get_user_meta($user->ID, 'billing_email', true) ?: $user->user_email,
            'phone'      => get_user_meta($user->ID, 'billing_phone', true),
        ];

        $name = trim(get_user_meta($user->ID, 'billing_first_name', true) . ' ' . get_user_meta($user->ID, 'billing_last_name', true));
        if (!$name) $name = $user->display_name;

        $customers[] = [
            'id'      => $user->ID,
            'name'    => $name,
            'email'   => $user->user_email,
            'phone'   => get_user_meta($user->ID, 'billing_phone', true),
            'billing' => $billing,
        ];
    }

    wp_send_json_success($customers);
});

// ============================================================
// SEARCH PRODUCTS (for new/edit order)
// ============================================================
add_action('wp_ajax_bizmart_search_products_for_order', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $term = sanitize_text_field(wp_unslash($_POST['term'] ?? ''));
    if (strlen($term) < 1) wp_send_json_error('Term too short');

    $args = [
        'status'  => 'publish',
        'limit'   => 20,
        'orderby' => 'title',
        'order'   => 'ASC',
    ];

    // Search by SKU or name
    if (is_numeric($term)) {
        $args['include'] = [absint($term)];
    } else {
        $args['s'] = $term;
    }

    $products = wc_get_products($args);

    $results = [];
    foreach ($products as $product) {
        $image = '';
        $thumb_id = $product->get_image_id();
        if ($thumb_id) {
            $img_src = wp_get_attachment_image_url($thumb_id, 'thumbnail');
            $image = $img_src ? $img_src : '';
        }

        $results[] = [
            'id'             => $product->get_id(),
            'name'           => $product->get_name(),
            'sku'            => $product->get_sku(),
            'price'          => floatval($product->get_price()),
            'image'          => $image,
            'managing_stock' => $product->managing_stock(),
            'stock'          => $product->get_stock_quantity(),
        ];
    }

    wp_send_json_success($results);
});

// ============================================================
// CREATE ORDER
// ============================================================
add_action('wp_ajax_bizmart_create_order', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $customer_id    = absint(wp_unslash($_POST['customer_id'] ?? 0));
    $status         = sanitize_text_field(wp_unslash($_POST['status'] ?? 'pending'));
    $payment_method = sanitize_text_field(wp_unslash($_POST['payment_method'] ?? ''));
    $customer_note  = sanitize_textarea_field(wp_unslash($_POST['customer_note'] ?? ''));
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- items is an array, sanitized per-field below
    $items          = isset($_POST['items']) ? wp_unslash($_POST['items']) : [];
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $billing_data   = isset($_POST['billing']) ? wp_unslash($_POST['billing']) : [];
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $shipping_data  = isset($_POST['shipping']) ? wp_unslash($_POST['shipping']) : [];

    if (empty($items)) wp_send_json_error('No items provided');

    try {
        $order = wc_create_order(['customer_id' => $customer_id]);

        // Add items
        foreach ($items as $item_data) {
            $product_id = absint($item_data['product_id'] ?? 0);
            $quantity   = max(1, intval($item_data['quantity'] ?? 1));
            $price      = floatval($item_data['price'] ?? 0);
            $product    = wc_get_product($product_id);
            if (!$product) continue;

            $order->add_product($product, $quantity, ['subtotal' => $price * $quantity, 'total' => $price * $quantity]);
        }

        // Set billing address
        $billing_fields = ['first_name', 'last_name', 'company', 'address_1', 'address_2', 'city', 'postcode', 'country', 'email', 'phone'];
        foreach ($billing_fields as $f) {
            if (isset($billing_data[$f])) {
                $setter = 'set_billing_' . $f;
                if (method_exists($order, $setter)) {
                    $order->$setter(sanitize_text_field($billing_data[$f]));
                }
            }
        }

        // Set shipping address
        $shipping_fields = ['first_name', 'last_name', 'company', 'address_1', 'address_2', 'city', 'postcode', 'country', 'phone'];
        foreach ($shipping_fields as $f) {
            if (isset($shipping_data[$f])) {
                $setter = 'set_shipping_' . $f;
                if (method_exists($order, $setter)) {
                    $order->$setter(sanitize_text_field($shipping_data[$f]));
                }
            }
        }

        // Payment method
        if ($payment_method) {
            $order->set_payment_method($payment_method);
            $gateways = WC()->payment_gateways()->payment_gateways();
            if (isset($gateways[$payment_method])) {
                $order->set_payment_method_title($gateways[$payment_method]->get_title());
            }
        }

        // Customer note
        if ($customer_note) {
            $order->set_customer_note($customer_note);
        }

        $order->calculate_totals();
        $order->update_status($status, 'Created via Bizmart.');
        $order->save();

        wp_send_json_success([
            'order_id' => $order->get_id(),
            'number'   => $order->get_order_number(),
        ]);

    } catch (Exception $e) {
        wp_send_json_error($e->getMessage());
    }
});

// ============================================================
// DUPLICATE ORDER
// ============================================================
add_action('wp_ajax_bizmart_duplicate_order', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $order_id = absint(wp_unslash($_POST['order_id'] ?? 0));
    if (!$order_id) wp_send_json_error('Missing order ID');

    $original = wc_get_order($order_id);
    if (!$original) wp_send_json_error('Order not found');

    try {
        $new_order = wc_create_order([
            'customer_id' => $original->get_customer_id(),
        ]);

        // Copy items
        foreach ($original->get_items() as $item) {
            $product = $item->get_product();
            if ($product) {
                $new_order->add_product($product, $item->get_quantity(), [
                    'subtotal' => $item->get_subtotal(),
                    'total'    => $item->get_total(),
                ]);
            }
        }

        // Copy addresses
        $new_order->set_address($original->get_address('billing'), 'billing');
        $new_order->set_address($original->get_address('shipping'), 'shipping');

        // Copy payment method
        $new_order->set_payment_method($original->get_payment_method());
        $new_order->set_payment_method_title($original->get_payment_method_title());

        $new_order->calculate_totals();
        $new_order->update_status('pending', 'Duplicated from order #' . $original->get_order_number() . ' via Bizmart.');
        $new_order->save();

        wp_send_json_success([
            'order_id' => $new_order->get_id(),
            'number'   => $new_order->get_order_number(),
        ]);
    } catch (Exception $e) {
        wp_send_json_error($e->getMessage());
    }
});

// ============================================================
// UPDATE ORDER (addresses)
// ============================================================
add_action('wp_ajax_bizmart_update_order', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $order_id = absint(wp_unslash($_POST['order_id'] ?? 0));
    if (!$order_id) wp_send_json_error('Missing order ID');

    $order = wc_get_order($order_id);
    if (!$order) wp_send_json_error('Order not found');

    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $billing  = isset($_POST['billing']) ? wp_unslash($_POST['billing']) : null;
    // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
    $shipping = isset($_POST['shipping']) ? wp_unslash($_POST['shipping']) : null;

    if ($billing && is_array($billing)) {
        $fields = ['first_name', 'last_name', 'company', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country', 'email', 'phone'];
        foreach ($fields as $f) {
            if (isset($billing[$f])) {
                $setter = 'set_billing_' . $f;
                if (method_exists($order, $setter)) {
                    $order->$setter(sanitize_text_field($billing[$f]));
                }
            }
        }
    }

    if ($shipping && is_array($shipping)) {
        $fields = ['first_name', 'last_name', 'company', 'address_1', 'address_2', 'city', 'state', 'postcode', 'country', 'phone'];
        foreach ($fields as $f) {
            if (isset($shipping[$f])) {
                $setter = 'set_shipping_' . $f;
                if (method_exists($order, $setter)) {
                    $order->$setter(sanitize_text_field($shipping[$f]));
                }
            }
        }
    }

    $order->save();
    wp_send_json_success();
});

// ============================================================
// ADD ITEM TO EXISTING ORDER
// ============================================================
add_action('wp_ajax_bizmart_add_order_item', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $order_id   = absint(wp_unslash($_POST['order_id'] ?? 0));
    $product_id = absint(wp_unslash($_POST['product_id'] ?? 0));
    $quantity   = max(1, intval(wp_unslash($_POST['quantity'] ?? 1)));
    if (!$order_id || !$product_id) wp_send_json_error('Missing parameters');

    $order = wc_get_order($order_id);
    if (!$order) wp_send_json_error('Order not found');

    $product = wc_get_product($product_id);
    if (!$product) wp_send_json_error('Product not found');

    $order->add_product($product, $quantity);
    $order->calculate_totals();
    $order->save();

    wp_send_json_success();
});

// ============================================================
// REMOVE ITEM FROM ORDER
// ============================================================
add_action('wp_ajax_bizmart_remove_order_item', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $order_id = absint(wp_unslash($_POST['order_id'] ?? 0));
    $item_id  = absint(wp_unslash($_POST['item_id'] ?? 0));
    if (!$order_id || !$item_id) wp_send_json_error('Missing parameters');

    $order = wc_get_order($order_id);
    if (!$order) wp_send_json_error('Order not found');

    $order->remove_item($item_id);
    $order->calculate_totals();
    $order->save();

    wp_send_json_success();
});

// ============================================================
// UPDATE ORDER ITEM (quantity or price)
// ============================================================
add_action('wp_ajax_bizmart_update_order_item', function() {
    bizmart_check_ajax_nonce('nonce');
    if (!current_user_can('manage_woocommerce')) wp_send_json_error('Unauthorized', 403);

    $order_id = absint(wp_unslash($_POST['order_id'] ?? 0));
    $item_id  = absint(wp_unslash($_POST['item_id'] ?? 0));
    if (!$order_id || !$item_id) wp_send_json_error('Missing parameters');

    $order = wc_get_order($order_id);
    if (!$order) wp_send_json_error('Order not found');

    $item = $order->get_item($item_id);
    if (!$item) wp_send_json_error('Item not found');

    // Update quantity
    if (isset($_POST['quantity'])) {
        $qty = max(1, intval(wp_unslash($_POST['quantity'])));
        $item->set_quantity($qty);

        // Recalculate line totals based on new quantity
        $product = $item->get_product();
        if ($product) {
            $price = floatval($product->get_price());
            $item->set_subtotal($price * $qty);
            $item->set_total($price * $qty);
        }
    }

    // Update price
    if (isset($_POST['price'])) {
        $price = floatval(wp_unslash($_POST['price']));
        $qty = $item->get_quantity();
        $item->set_subtotal($price * $qty);
        $item->set_total($price * $qty);
    }

    $item->save();
    $order->calculate_totals();
    $order->save();

    wp_send_json_success();
});
