<?php

namespace Fitsmart\ParcelPanel;

class ApiClient
{
    private string $apiKey;

    public function __construct(private Logger $logger)
    {
        $this->apiKey = ParcelPanelHelper::getParcelKey();
    }

    public function get_tracking_by_order_id(int $order_id): mixed
    {
        $url = 'https://wp-api.parcelpanel.com/api/v1/tracking/list';
        $payload = [
            'orders' => [
                [
                    'order_id' => $order_id,
                ],
            ],
        ];
        return $this->post($url, $payload);
    }

    public function create_tracking(int $order_id, array $tracking_data): mixed
    {
        $url = 'https://wp-api.parcelpanel.com/api/v1/tracking/create';
        $shipment = [
            'order_id' => $order_id,
            'tracking_number' => $tracking_data['tracking_number'] ?? '',
        ];

        if (!empty($tracking_data['courier_code'])) {
            $shipment['courier_code'] = $tracking_data['courier_code'];
        }
        $payload = ['shipments' => [$shipment]];
        return $this->post($url, $payload);
    }

    private function post(string $url, array $payload): mixed
    {
        $headers = [
            'Content-Type: application/json',
            'PP-Api-Key: ' . $this->apiKey,
        ];

        $curl = curl_init();
        curl_setopt_array($curl, [
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_POSTFIELDS => json_encode($payload),
            CURLOPT_HTTPHEADER => $headers,
        ]);

        $response = curl_exec($curl);
        $http_status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if (!$response) {
            $this->logger->log(curl_error($curl));
        }

//        $this->logger->log(json_decode($response));

        curl_close($curl);

        if ($http_status >= 200 && $http_status < 300) {
            return json_decode($response);
        }
        $this->logger->log($response);
        return false;
    }
}