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

class Fusion_WooDoo_API_Client {

    private string $odoo_url;
    private string $api_key;

    public function __construct() {
        $this->odoo_url = rtrim(get_option('fusion_woodoo_odoo_url', ''), '/');
        $this->api_key  = get_option('fusion_woodoo_api_key', '');
    }

    /**
     * Make a POST request to an Odoo endpoint.
     *
     * @param string $endpoint  e.g. '/woo/api/order/status'
     * @param array  $data
     * @return array{success: bool, data: mixed, error: string}
     */
    public function request(string $endpoint, array $data = []): array {
        if (empty($this->odoo_url) || empty($this->api_key)) {
            return ['success' => false, 'data' => null, 'error' => 'Odoo URL or API key not configured.'];
        }

        $url      = $this->odoo_url . $endpoint;
        $response = wp_remote_post($url, [
            'timeout'     => 15,
            'headers'     => [
                'Content-Type'  => 'application/json',
                'Authorization' => 'Bearer ' . $this->api_key,
            ],
            'body'        => wp_json_encode($data),
            'data_format' => 'body',
        ]);

        if (is_wp_error($response)) {
            return ['success' => false, 'data' => null, 'error' => $response->get_error_message()];
        }

        $code = wp_remote_retrieve_response_code($response);
        $body = json_decode(wp_remote_retrieve_body($response), true);

        if ($code >= 200 && $code < 300) {
            return ['success' => true, 'data' => $body, 'error' => ''];
        }

        $error_msg = $body['message'] ?? $body['error'] ?? 'Unexpected response from Odoo (HTTP ' . $code . ').';
        return ['success' => false, 'data' => $body, 'error' => $error_msg];
    }

    /**
     * Test connectivity to Odoo.
     */
    public function test_connection(): array {
        return $this->request('/woo/api/order/status', ['ping' => true]);
    }

    /**
     * Get order status from Odoo.
     *
     * @param int|string $order_id  WooCommerce order ID
     */
    public function get_order_status(int|string $order_id): array {
        return $this->request('/woo/api/order/status', ['order_id' => $order_id]);
    }

    /**
     * Submit a return request to Odoo.
     *
     * @param int|string $order_id
     * @param array      $items    [['product_id' => ..., 'qty' => ...], ...]
     * @param string     $reason
     */
    public function submit_return(int|string $order_id, array $items, string $reason): array {
        return $this->request('/woo/api/return/create', [
            'order_id' => $order_id,
            'items'    => $items,
            'reason'   => $reason,
        ]);
    }

    /**
     * Fetch existing returns for a customer.
     *
     * @param int|string $customer_id  WooCommerce user ID
     */
    public function get_returns(int|string $customer_id): array {
        return $this->request('/woo/api/return/list', ['customer_id' => $customer_id]);
    }
}
