<?php
if (!defined('ABSPATH')) exit;

class Fusion_WooDoo_Returns {

    public function __construct() {
        add_action('wp_ajax_fusion_woodoo_submit_return', [$this, 'ajax_submit_return']);
    }

    /**
     * Get the last N orders for the current customer.
     *
     * @param  int $limit
     * @return WC_Order[]
     */
    public function get_customer_orders(int $limit = 20): array {
        if (!is_user_logged_in()) {
            return [];
        }
        return wc_get_orders([
            'customer' => get_current_user_id(),
            'limit'    => $limit,
            'status'   => ['completed', 'processing', 'on-hold'],
            'orderby'  => 'date',
            'order'    => 'DESC',
        ]);
    }

    /**
     * Fetch existing returns for the current customer from Odoo.
     *
     * @return array
     */
    public function get_existing_returns(): array {
        if (!is_user_logged_in()) {
            return [];
        }
        $client = new Fusion_WooDoo_API_Client();
        $result = $client->get_returns(get_current_user_id());
        return $result['success'] ? ($result['data']['returns'] ?? []) : [];
    }

    /**
     * AJAX handler for return form submission.
     */
    public function ajax_submit_return(): void {
        check_ajax_referer('fusion_woodoo_nonce', 'nonce');

        if (!is_user_logged_in()) {
            wp_send_json_error(['message' => __('You must be logged in to submit a return.', 'fusion-woodoo')]);
        }

        $order_id = (int) ($_POST['order_id'] ?? 0);
        $reason   = sanitize_textarea_field($_POST['reason'] ?? '');
        $items    = $_POST['items'] ?? [];

        if (!$order_id) {
            wp_send_json_error(['message' => __('Please select an order.', 'fusion-woodoo')]);
        }

        if (empty($items) || !is_array($items)) {
            wp_send_json_error(['message' => __('Please select at least one item to return.', 'fusion-woodoo')]);
        }

        if (empty($reason)) {
            wp_send_json_error(['message' => __('Please provide a reason for the return.', 'fusion-woodoo')]);
        }

        // Verify the order belongs to the current user
        $order = wc_get_order($order_id);
        if (!$order || $order->get_customer_id() !== get_current_user_id()) {
            wp_send_json_error(['message' => __('Order not found or access denied.', 'fusion-woodoo')]);
        }

        // Sanitize and validate items
        $sanitized_items = [];
        foreach ($items as $item) {
            $product_id = (int) ($item['product_id'] ?? 0);
            $qty        = max(1, (int) ($item['qty'] ?? 1));
            if ($product_id > 0) {
                $sanitized_items[] = ['product_id' => $product_id, 'qty' => $qty];
            }
        }

        if (empty($sanitized_items)) {
            wp_send_json_error(['message' => __('No valid items selected for return.', 'fusion-woodoo')]);
        }

        $client = new Fusion_WooDoo_API_Client();
        $result = $client->submit_return($order_id, $sanitized_items, $reason);

        if ($result['success']) {
            wp_send_json_success([
                'message'   => __('Return request submitted successfully. Our team will review it shortly.', 'fusion-woodoo'),
                'return_id' => $result['data']['return_id'] ?? null,
            ]);
        } else {
            wp_send_json_error([
                'message' => $result['error'] ?: __('Failed to submit return. Please try again or contact support.', 'fusion-woodoo'),
            ]);
        }
    }
}
