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

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

/**
 * AJAX: Get paginated orders list with filters + stats
 */
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');

    $page     = max(1, 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'] = 'wc-' . ltrim($status, 'wc-');
    } else {
        $args['status'] = ['wc-pending', 'wc-processing', 'wc-on-hold', 'wc-completed', 'wc-cancelled', 'wc-refunded', 'wc-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 = wc_get_orders($args);

    $orders = [];
    foreach ($results->orders as $wc_order) {
        $orders[] = bizmart_format_order_row($wc_order);
    }

    // Stats
    $stats = bizmart_get_order_stats();

    // Status counts
    $status_counts = bizmart_get_order_status_counts();

    // Daily trend (last 30 days)
    $daily_trend = bizmart_get_daily_trend();

    // Payment methods breakdown
    $payment_methods = bizmart_get_payment_method_stats();

    // Available gateways
    $gateways = [];
    if (function_exists('WC')) {
        $available = WC()->payment_gateways()->get_available_payment_gateways();
        foreach ($available as $gw) {
            $gateways[] = ['id' => $gw->id, 'title' => $gw->get_title()];
        }
    }

    wp_send_json_success([
        'orders'          => $orders,
        'total'           => $results->total,
        'total_pages'     => $results->max_num_pages,
        'page'            => $page,
        'stats'           => $stats,
        'status_counts'   => $status_counts,
        'daily_trend'     => $daily_trend,
        'payment_methods' => $payment_methods,
        'gateways'        => $gateways,
    ]);
});

/**
 * 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) {
    $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() {
    $completed = wc_get_orders([
        'status' => ['wc-completed'],
        'limit'  => -1,
        'return' => 'ids',
    ]);

    $total_sales = 0;
    $total_gains = 0;
    foreach ($completed as $order_id) {
        $order = wc_get_order($order_id);
        if (!$order) continue;
        $total_sales += floatval($order->get_total());
        $total_gains += bizmart_calculate_order_gains($order);
    }

    // This month
    $this_month_start = gmdate('Y-m-01');
    $this_month_orders = wc_get_orders([
        'status'       => ['wc-completed', 'wc-processing'],
        'date_created' => '>=' . $this_month_start,
        'limit'        => -1,
        'return'       => 'ids',
    ]);
    $this_month = 0;
    $this_month_gains = 0;
    foreach ($this_month_orders as $oid) {
        $o = wc_get_order($oid);
        if (!$o) continue;
        $this_month += floatval($o->get_total());
        $this_month_gains += bizmart_calculate_order_gains($o);
    }

    // Last month
    $last_month_start = gmdate('Y-m-01', strtotime('-1 month'));
    $last_month_end   = gmdate('Y-m-t', strtotime('-1 month'));
    $last_month_orders = wc_get_orders([
        'status'       => ['wc-completed', 'wc-processing'],
        'date_created' => $last_month_start . '...' . $last_month_end,
        'limit'        => -1,
        'return'       => 'ids',
    ]);
    $last_month = 0;
    foreach ($last_month_orders as $oid) {
        $o = wc_get_order($oid);
        if (!$o) continue;
        $last_month += floatval($o->get_total());
    }

    // Averages
    $all_orders = wc_get_orders([
        'status' => ['wc-completed', 'wc-processing'],
        'limit'  => -1,
        'return' => 'ids',
    ]);
    $total_orders = count($all_orders);
    $total_sum = 0;
    foreach ($all_orders as $oid) {
        $o = wc_get_order($oid);
        if (!$o) continue;
        $total_sum += floatval($o->get_total());
    }
    $avg_order = $total_orders > 0 ? round($total_sum / $total_orders, 2) : 0;

    // Pending count
    $pending = wc_get_orders([
        'status' => ['wc-pending', 'wc-on-hold'],
        'limit'  => -1,
        'return' => 'ids',
    ]);

    // Today
    $today_start = gmdate('Y-m-d');
    $today_orders = wc_get_orders([
        'status'       => ['wc-completed', 'wc-processing', 'wc-pending', 'wc-on-hold'],
        'date_created' => '>=' . $today_start,
        'limit'        => -1,
        'return'       => 'ids',
    ]);
    $today_sales = 0;
    foreach ($today_orders as $oid) {
        $o = wc_get_order($oid);
        if (!$o) continue;
        $today_sales += floatval($o->get_total());
    }

    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'     => count($completed),
        'pending_count'    => count($pending),
        'today_count'      => count($today_orders),
        '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 = [];
    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() {
    global $wpdb;

    $days_ago = gmdate('Y-m-d', strtotime('-30 days'));

    if (class_exists('\Automattic\WooCommerce\Utilities\OrderUtil') &&
        \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled()) {
        // HPOS enabled
        $table = $wpdb->prefix . 'wc_orders';
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table name is safe (prefix + literal)
        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT DATE(date_created_gmt) AS day, COUNT(*) AS `count`, SUM(total_amount) AS total
             FROM {$table}
             WHERE status IN ('wc-completed','wc-processing')
             AND date_created_gmt >= %s
             GROUP BY DATE(date_created_gmt)
             ORDER BY day ASC",
            $days_ago
        ));
    } else {
        // Legacy post meta
        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT DATE(p.post_date) AS day, COUNT(*) AS `count`, SUM(pm.meta_value) AS total
             FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = '_order_total'
             WHERE p.post_type = 'shop_order'
             AND p.post_status IN ('wc-completed','wc-processing')
             AND p.post_date >= %s
             GROUP BY DATE(p.post_date)
             ORDER BY day ASC",
            $days_ago
        ));
    }

    return $results ? $results : [];
}

/**
 * Get payment method statistics.
 */
function bizmart_get_payment_method_stats() {
    global $wpdb;

    if (class_exists('\Automattic\WooCommerce\Utilities\OrderUtil') &&
        \Automattic\WooCommerce\Utilities\OrderUtil::custom_orders_table_usage_is_enabled()) {
        $table = $wpdb->prefix . 'wc_orders';
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $results = $wpdb->get_results(
            "SELECT payment_method AS method, payment_method_title AS label, COUNT(*) AS `count`, SUM(total_amount) AS total
             FROM {$table}
             WHERE status IN ('wc-completed','wc-processing')
             AND payment_method != ''
             GROUP BY payment_method, payment_method_title
             ORDER BY total DESC"
        );
    } else {
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared -- table names only, no user input
        $results = $wpdb->get_results(
            "SELECT pm1.meta_value AS method, pm2.meta_value AS label, COUNT(*) AS `count`, SUM(pm3.meta_value) AS total
             FROM {$wpdb->posts} p
             INNER JOIN {$wpdb->postmeta} pm1 ON p.ID = pm1.post_id AND pm1.meta_key = '_payment_method'
             INNER JOIN {$wpdb->postmeta} pm2 ON p.ID = pm2.post_id AND pm2.meta_key = '_payment_method_title'
             INNER JOIN {$wpdb->postmeta} pm3 ON p.ID = pm3.post_id AND pm3.meta_key = '_order_total'
             WHERE p.post_type = 'shop_order'
             AND p.post_status IN ('wc-completed','wc-processing')
             AND pm1.meta_value != ''
             GROUP BY pm1.meta_value, pm2.meta_value
             ORDER BY total DESC"
        );
    }

    return $results ? $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();
});
