<?php

namespace App\Services;

use GuzzleHttp\Client;

class PathaoCourierService
{
    private $apiKey;            
    private $secretKey;
    private $clientEmail;
    private $clientPassword;
    private $isSandbox;
    private $client;
    private $accessToken;
    private $baseUrl;

    public function __construct($apiKey, $secretKey, $clientEmail, $clientPassword, $isSandbox = false)
    {
        $this->apiKey = $apiKey;
        $this->secretKey = $secretKey;
        $this->clientEmail = $clientEmail;
        $this->clientPassword = $clientPassword;
        $this->isSandbox = $isSandbox;
        $this->baseUrl = $isSandbox ? 'https://courier-api-sandbox.pathao.com' : 'https://api-hermes.pathao.com';
        $this->client = new Client(
            [
                'verify' => $isSandbox ? false : true,
            ]
        );
        $this->getAccessToken();
    }

    public function createOrder($orderData)
    {
 
    $response = $this->client->post($this->baseUrl . '/aladdin/api/v1/orders', [
        'headers' => [
            'Authorization' => 'Bearer ' . $this->accessToken,
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ],
        'json' => [
            'store_id' => $orderData['store'],
            'merchant_order_id' => $orderData['merchant_order_id'] ?? null,
            'recipient_name' => $orderData['recipient_name'],
            'recipient_phone' => $orderData['recipient_phone'],
            'recipient_address' => $orderData['recipient_address'],
            'recipient_city' => $orderData['city'],
            'recipient_zone' => $orderData['zone'],
            'recipient_area' => $orderData['area'],
            'delivery_type' => $orderData['delivery_type'],
            'item_type' => $orderData['product_type'],
            'special_instruction' => $orderData['special_instruction'] ?? null,
            'item_quantity' => $orderData['quantity'],
            'item_weight' => $orderData['total_weight'],
            'amount_to_collect' => floatval($orderData['cod_amount']),
            'item_description' => $orderData['item_description'] ?? null,
        ],
    ]);

    return json_decode($response->getBody(), true);
    }

    private function getAccessToken()
    {
        $response = $this->client->post($this->baseUrl . '/aladdin/api/v1/issue-token', [
            'headers' => [
                'Accept' => 'application/json',
                'Content-Type' => 'application/json',
            ],
            'json' => [
                'client_id' => $this->apiKey,
                'client_secret' => $this->secretKey,
                'username' => $this->clientEmail,
                'password' => $this->clientPassword,
                'grant_type' => 'password',
            ],
        ]);
        
        
        if ($response->getStatusCode() == 200) {
            $data = json_decode($response->getBody(), true);
            $this->accessToken = $data['access_token'];
        } else {
            \Log::error('API Error', ['status_code' => $response->getStatusCode(), 'body' => $response->getBody()]);
            throw new \Exception('Failed to obtain access token: ' . $response->getBody());
        }
        
    }

    public function getStoreList()
    {
       
        $response = $this->client->get($this->baseUrl . '/aladdin/api/v1/stores', [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->accessToken,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ],
        ]);
        $data = json_decode($response->getBody(), true);
        return $data;
    }
    public function getCityList()
    {
        $response = $this->client->get($this->baseUrl . '/aladdin/api/v1/city-list', [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->accessToken,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ],
        ]);
        $data = json_decode($response->getBody(), true);
        return $data;
    }
    public function getZoneListByCityId($cityId)
    {
        $response = $this->client->get($this->baseUrl . '/aladdin/api/v1/cities/' . $cityId . '/zone-list', [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->accessToken,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ],
        ]);
        $data = json_decode($response->getBody(), true);
        return $data;
    }
    public function getAreaListByZoneId($zoneId)
    {
        $response = $this->client->get($this->baseUrl . '/aladdin/api/v1/zones/' . $zoneId . '/area-list', [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->accessToken,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ],
        ]);
        $data = json_decode($response->getBody(), true);
        return $data;
    }
}
