<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class CourierService {
    private string $apiKey;
    private string $apiSecret;
    private string $base = 'https://portal.steadfast.com.bd/api/v1';
    public function __construct(string $apiKey, string $apiSecret) {
        $this->apiKey    = $apiKey;
        $this->apiSecret = $apiSecret;
    }
    public function createOrder(array $data): array {
        $response = Http::withHeaders([
            'Api-Key'    => $this->apiKey,
            'Secret-Key' => $this->apiSecret,
            'Content-Type' => 'application/json',
        ])->post("{$this->base}/create_order", [
            'invoice'          => $data['invoice'],
            'recipient_name'   => $data['name'],
            'recipient_phone'  => $data['phone'],
            'recipient_address'=> $data['address'],
            'cod_amount'       => $data['cod'] ?? 0,
            'note'             => $data['note'] ?? '',
        ]);
        return $response->json();
    }
    public function trackOrder(string $consignmentId): array {
        $response = Http::withHeaders([
            'Api-Key' => $this->apiKey, 'Secret-Key' => $this->apiSecret,
        ])->get("{$this->base}/status_by_consignment_id/{$consignmentId}");
        return $response->json();
    }
    public function checkBalance(): array {
        $response = Http::withHeaders([
            'Api-Key' => $this->apiKey, 'Secret-Key' => $this->apiSecret,
        ])->get("{$this->base}/get_balance");
        return $response->json();
    }

    public function checkCustomerStatus(string $phone): array {
        // Steadfast API usually doesn't document this clearly, but we can query it
        // If the endpoint doesn't exist, we will mock the response for demonstration.
        $response = Http::withHeaders([
            'Api-Key' => $this->apiKey, 'Secret-Key' => $this->apiSecret,
        ])->get("{$this->base}/customer_status/{$phone}");

        if ($response->successful() && !empty($response->json())) {
            return $response->json();
        }

        // If API fails or is not documented properly, return empty safe data instead of random numbers
        return [
            'success' => false,
            'data' => [
                'total_parcel' => 0,
                'delivered'    => 0,
                'returned'     => 0,
                'success_rate' => 0
            ]
        ];
    }
}
