<?php

namespace Core\App\Integrations\Shipping;

class EcotrackClient
{
    protected string $baseUrl;
    protected string $apiToken;

    public function __construct(string $apiToken, string $baseUrl)
    {
        $this->apiToken = trim($apiToken);
        $this->baseUrl  = rtrim($baseUrl, '/');
    }

    /* =====================================================
       AUTH / META
    ===================================================== */

    public function validateToken(): array
    {
        $url = $this->baseUrl . '/api/v1/validate/token?api_token=' . urlencode($this->apiToken);
        return $this->request('GET', $url);
    }

    /* =====================================================
       ORDERS
    ===================================================== */

    public function createOrderSingle(array $params): array
    {
        $url = $this->baseUrl . '/api/v1/create/order?' . http_build_query($params);
        return $this->request('POST', $url);
    }

    public function createOrdersBulk(array $orders): array
    {
        $url = $this->baseUrl . '/api/v1/create/orders';
        return $this->request('POST', $url, ['orders' => $orders]);
    }

    public function updateOrder(string $tracking, array $params): array
    {
        $params['tracking'] = $tracking;
        $url = $this->baseUrl . '/api/v1/update/order?' . http_build_query($params);
        return $this->request('POST', $url);
    }

    public function deleteOrder(string $tracking): array
    {
        $url = $this->baseUrl . '/api/v1/delete/order?tracking=' . urlencode($tracking);
        return $this->request('DELETE', $url);
    }

    public function validateOrder(string $tracking, bool $askCollection): array
    {
        $url = $this->baseUrl . '/api/v1/valid/order?tracking='
             . urlencode($tracking)
             . '&ask_collection=' . ($askCollection ? 1 : 0);

        return $this->request('POST', $url);
    }

    public function getOrderLabel(string $tracking): array
    {
        $url = $this->baseUrl . '/api/v1/get/order/label?tracking=' . urlencode($tracking);
        return $this->request('GET', $url);
    }

    /* =====================================================
       TRACKING / STATUS
    ===================================================== */

    public function getTrackingInfo(string $tracking): array
    {
        $url = $this->baseUrl . '/api/v1/get/tracking/info?tracking=' . urlencode($tracking);
        return $this->request('GET', $url);
    }

    public function addUpdate(string $tracking, string $content): array
    {
        $url = $this->baseUrl . '/api/v1/add/maj?tracking='
             . urlencode($tracking)
             . '&content=' . urlencode($content);

        return $this->request('POST', $url);
    }

    public function getUpdates(string $tracking): array
    {
        $url = $this->baseUrl . '/api/v1/get/maj?tracking=' . urlencode($tracking);
        return $this->request('GET', $url);
    }

    public function askForReturn(string $tracking): array
    {
        $url = $this->baseUrl . '/api/v1/ask/for/order/return?tracking=' . urlencode($tracking);
        return $this->request('POST', $url);
    }

    /* =====================================================
       LISTS / REFERENCES
    ===================================================== */

    public function getOrders(int $page, ?string $startDate = null, ?string $endDate = null): array
    {
        $params = ['page' => $page];

        if ($startDate !== null) {
            $params['start_date'] = $startDate;
        }

        if ($endDate !== null) {
            $params['end_date'] = $endDate;
        }

        $url = $this->baseUrl . '/api/v1/get/orders?' . http_build_query($params);
        return $this->request('GET', $url);
    }

    public function getOrdersByStatus(array $trackings, string $status): array
    {
        $params = [
            'api_token' => $this->apiToken,
            'trackings' => implode(',', $trackings),
            'status'    => $status,
        ];

        $url = $this->baseUrl . '/api/v1/get/orders/status?' . http_build_query($params);
        return $this->request('GET', $url);
    }

        public function getOrderStatusSingle(string $tracking): array
    {
        $res = $this->getOrdersByStatus([$tracking], 'all');

        if (empty($res['success']) || empty($res['data']) || !is_array($res['data'])) {
            return [
                'success' => false,
                'error'   => $res['error'] ?? 'invalid_ecotrack_response',
                'data'    => null,
            ];
        }

        // Ecotrack returns: { "data": { "TRACKING": { ... } } }
        $body = $res['data'];

        if (!isset($body['data']) || !is_array($body['data']) || !isset($body['data'][$tracking])) {
            return [
                'success' => false,
                'error'   => 'ecotrack_not_ready',
                'data'    => null,
                'raw'     => $body,
            ];
        }

        return [
            'success' => true,
            'data'    => $body['data'][$tracking],
            'raw'     => $body,
        ];
    }
    
    public function getWilayas(): array
    {
        $url = $this->baseUrl . '/api/v1/get/wilayas';
        return $this->request('GET', $url);
    }

    public function getCommunes(?int $wilayaId = null): array
    {
        $url = $this->baseUrl . '/api/v1/get/communes';

        if ($wilayaId !== null) {
            $url .= '?wilaya_id=' . intval($wilayaId);
        }

        return $this->request('GET', $url);
    }

    public function getFees(): array
    {
        $url = $this->baseUrl . '/api/v1/get/fees';
        return $this->request('GET', $url);
    }

    public function getProductsList(): array
    {
        $url = $this->baseUrl . '/api/v1/get/products/list';
        return $this->request('GET', $url);
    }

    /* =====================================================
       LEGACY METHODS (KEPT BUT NOT USED)
    ===================================================== */

    public function createOrder(array $data): array
    {
        return $this->createOrderSingle($data);
    }

    public function track(string $tracking): array
    {
        return $this->getTrackingInfo($tracking);
    }

    /* =====================================================
       INTERNAL HTTP CLIENT
    ===================================================== */

    protected function request(string $method, string $url, array $payload = []): array
    {
        $ch = curl_init($url);

        $headers = [
            'Accept: application/json',
            'Authorization: Bearer ' . $this->apiToken,
        ];

        $options = [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_CUSTOMREQUEST  => $method,
            CURLOPT_HTTPHEADER     => $headers,
        ];

        if (!empty($payload)) {
            $headers[] = 'Content-Type: application/json';
            $options[CURLOPT_POSTFIELDS] = json_encode($payload);
        }

        curl_setopt_array($ch, $options);

        $response = curl_exec($ch);
        $status   = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        $decoded = json_decode($response, true);

        if ($status >= 200 && $status < 300) {
            return [
                'success' => true,
                'status'  => $status,
                'data'    => $decoded,
                'error'   => null,
                'raw'     => $response,
            ];
        }

        return [
            'success' => false,
            'status'  => $status,
            'error'   => $decoded['message'] ?? 'ECOTRACK API error',
            'raw'     => $decoded ?? $response,
        ];
    }
    
    /* =====================================================
   TRACKING LIFECYCLE (OFFICIAL – SINGLE SOURCE OF TRUTH)
===================================================== */

public function getTrackingLifecycle(string $tracking): array
{
    $response = $this->getTrackingInfo($tracking);

    if (
        empty($response['success']) ||
        empty($response['data'])
    ) {
        return [
            'success' => false,
            'error'   => $response['error'] ?? 'tracking_failed',
            'raw'     => $response,
        ];
    }

    $data = $response['data'];

    /**
     * حسب وثيقة Ecotrack:
     * lifecycle يوجد عادة داخل:
     * - events
     * - history
     * - activity
     */
    $events = [];

    if (!empty($data['events']) && is_array($data['events'])) {
        $events = $data['events'];
    } elseif (!empty($data['history']) && is_array($data['history'])) {
        $events = $data['history'];
    } elseif (!empty($data['activity']) && is_array($data['activity'])) {
        $events = $data['activity'];
    }

    // ترتيب زمني إن أمكن
    usort($events, function ($a, $b) {
        $ta = strtotime(($a['date'] ?? '') . ' ' . ($a['time'] ?? ''));
        $tb = strtotime(($b['date'] ?? '') . ' ' . ($b['time'] ?? ''));
        return $ta <=> $tb;
    });

    // آخر حالة = الحقيقة الحالية
    $current = end($events) ?: null;

    return [
        'success'  => true,
        'tracking' => $tracking,
        'current'  => $current,
        'events'   => array_values($events),
        'raw'      => $data,
    ];
}

}
