<?php
namespace App\Services;

use Illuminate\Support\Facades\Http;
use App\Models\CourierApi as ModelsCourierApi;


class CourierOrderInfoService
{
    public static function getCustomerOrderStats(string $phone): array
    {
        $courier_api = ModelsCourierApi::first();

        if (!$courier_api) {
            return [
                'total_delivery' => 0,
                'total_return' => 0,
            ];
        }

        // Safe fallback helper
        $safe = fn($val) => $val ? (int) $val : 0;

        try {
            $responses = Http::pool(fn($pool) => [
                $pool->withHeaders([
                    'Api-Key' => $courier_api->steadfast_api_key,
                    'Secret-Key' => $courier_api->steadfast_secret_key,
                    'Content-Type' => 'application/json',
                ])->get('https://portal.packzy.com/api/v1/fraud_check/' . $phone),

                $pool->withHeaders([
                    'API-ACCESS-TOKEN' => 'Bearer ' . $courier_api->redx_access_token,
                    'Accept' => 'application/json',
                ])->get('https://openapi.redx.com.bd/v1.0.0-beta/customer/success_rate/' . $phone),

                $pool->withHeaders([
                    'Content-Type' => 'application/json',
                    'accept' => 'application/json',
                    'Authorization' => 'Bearer ' . $courier_api->pathao_access_token,
                ])->post("https://merchant.pathao.com/api/v1/user/success", [
                    'phone' => $phone,
                ]),
            ]);

            $steadfast = json_decode($responses[0]->body());
            $redx = json_decode($responses[1]->body());
            $pathao = json_decode($responses[2]->body());

            // Steadfast
            $steadfast_delivered = $safe($steadfast->total_delivered ?? 0);
            $steadfast_cancelled = $safe($steadfast->total_cancelled ?? 0);

            // RedX
            $redx_delivered = $safe($redx->deliveredParcels ?? 0);
            $redx_total = $safe($redx->totalParcels ?? 0);
            $redx_cancelled = max($redx_total - $redx_delivered, 0);

            // Pathao
            $pathao_data = $pathao->data ?? null;
            $pathao_delivered = $safe($pathao_data->customer->successful_delivery ?? 0);
            $pathao_total = $safe($pathao_data->customer->total_delivery ?? 0);
            $pathao_cancelled = max($pathao_total - $pathao_delivered, 0);

            return [
                'total_delivery' => $steadfast_delivered + $redx_delivered + $pathao_delivered,
                'total_return' => $steadfast_cancelled + $redx_cancelled + $pathao_cancelled,
            ];
        } catch (\Throwable $e) {
            return [
                'total_delivery' => 0,
                'total_return' => 0,
            ];
        }
    }
}
