<?php

namespace App\Services;

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

class  CourierApi
{

    public function store($data, $courier = 'steadfast')
    {
        $courier_api = ModelsCourierApi::first();
        if ($courier == 'steadfast') {
            $response = Http::withHeaders([
                'Api-Key' => $courier_api->steadfast_api_key,
                'Secret-Key' => $courier_api->steadfast_secret_key,
                'Content-Type' => 'application/json'
            ])->post($courier_api->steadfast_base_url . '/create_order/bulk-order', ['data' => $data]);

            return json_decode($response, true);
        } elseif ($courier == 'pathao') {

            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $courier_api->pathao_access_token,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ])->post($courier_api->pathao_base_url . '/orders', $data);

            return $response;
        } elseif ($courier == 'redx') {

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $courier_api->redx_base_url . ($courier_api->redx_without_area_entry == 0 ? '/parcel' : '/no-area-parcels'),
                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($data),
                CURLOPT_HTTPHEADER => array(
                    'API-ACCESS-TOKEN: Bearer ' . $courier_api->redx_access_token . '',
                    'Content-Type: application/json'
                ),
            ));
            //execute 
            $response = curl_exec($curl);
            curl_close($curl);
            // Decode the JSON response
            return $data = json_decode($response, true);
        } elseif ($courier == 'paperfly') {
            return   Http::withHeaders([
                'paperflykey' => $courier_api->paperfly_api_key,
            ])->withBasicAuth(
                $courier_api->paperfly_username,
                $courier_api->paperfly_password
            )->post($courier_api->paperfly_base_url, $data);
        }
    }





    public function pathaoAccessToken()
    {
        $courier_api = ModelsCourierApi::first();
        $data = [
            'client_id' => $courier_api->pathao_client_id,
            'client_secret' => $courier_api->pathao_client_secret,
            'username' => $courier_api->pathao_client_email,
            'password' => $courier_api->pathao_client_password,
            'grant_type' => 'password',
        ];
        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ])->post($courier_api->pathao_base_url . '/issue-token',  $data);

        if ($response['access_token']) {
            return $response['access_token'];
        }
    }




    public function pathaoCityList()
    {
        $courier_api = ModelsCourierApi::first();

        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $courier_api->pathao_access_token,
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ])->get($courier_api->pathao_base_url . '/city-list');

        $cities = $response['data']['data'];
        //inserting to database table
        // foreach($cities as $item){
        //   $city =  new City();
        //   $city->name = $item['city_name'] ;
        //   $city->pathao_city_id = $item['city_id'] ;
        //   $city->save();                 

        // }

        return $cities;
    }



    public function pathaoZoneList($city_id)
    {

        $courier_api = ModelsCourierApi::first();
        $response = Http::withHeaders([
            'Authorization' => 'Bearer ' . $courier_api->pathao_access_token,
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ])->get($courier_api->pathao_base_url . '/cities/' . $city_id . '/zone-list');

        $zone_list = $response['data']['data'];
        //inserting to database table
        // foreach($zone_list as $item){
        //   $sub_city =  new SubCity();
        //   $sub_city->name = $item['zone_name'] ;
        //   $sub_city->city_id = $city_id ;
        //   $sub_city->pathao_zone_id = $item['zone_id'] ;
        //   $sub_city->save();                 
        // }
        return $zone_list;
    }



    public function redxAreaList()
    {

        $courier_api = ModelsCourierApi::first();
        $response = Http::withHeaders([
            'API-ACCESS-TOKEN' => 'Bearer ' . $courier_api->redx_access_token,
            'Content-Type' => 'application/json',
            'Accept' => 'application/json',
        ])->get($courier_api->redx_base_url . '/areas');

        $areas = $response['areas'];
        //inserting to database table
        // foreach($areas as $item){
        //   $city =  new RedxDeliveryArea();
        //   $city->district_name = $item['district_name'] ;
        //   $city->area_id = $item['id'] ;
        //   $city->area_name = $item['name'] ;
        //   $city->zone_id = $item['zone_id'] ;
        //   $city->save();                 

        // }

        return $areas;
    }



    public function tracking($tracking_id, $courier = 'steadfast')
    {

        $courier_api = ModelsCourierApi::first();
        if ($courier == 'steadfast') {

            $response = Http::withHeaders([
                'Api-Key' => $courier_api->steadfast_api_key,
                'Secret-Key' => $courier_api->steadfast_secret_key,
                'Content-Type' => 'application/json'
            ])->get($courier_api->steadfast_base_url . '/status_by_trackingcode/' . $tracking_id);

            return json_decode($response, true);
        } elseif ($courier == 'pathao') {

            $response = Http::withHeaders([
                'Authorization' => 'Bearer ' . $courier_api->pathao_access_token,
                'Content-Type' => 'application/json',
                'Accept' => 'application/json',
            ])->get($courier_api->pathao_base_url . '/orders/' . $tracking_id . '/info');

            return $response;
        } elseif ($courier == 'redx') {

            $curl = curl_init();
            curl_setopt_array($curl, array(
                CURLOPT_URL => $courier_api->redx_base_url . '/parcel/track/' . $tracking_id . '',
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => '',
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 0,
                CURLOPT_FOLLOWLOCATION => true,
                CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
                CURLOPT_CUSTOMREQUEST => 'GET',
                CURLOPT_HTTPHEADER => array(
                    'API-ACCESS-TOKEN: Bearer ' . $courier_api->redx_access_token . '',
                    'Content-Type: application/json'
                ),
            ));
            //execute 
            $response = curl_exec($curl);
            curl_close($curl);
            return $response;
        } elseif ($courier == 'paperfly') {

            $url = 'https://api.paperfly.com.bd/API-Order-Tracking';

            $headers = [
                'paperflykey' =>  $courier_api->paperfly_api_key,
                'Accept' => 'application/json',
            ];

            $response = Http::withBasicAuth(
                $courier_api->paperfly_username,
                $courier_api->paperfly_password
            )
                ->withHeaders($headers)
                ->post($url, [
                    'ReferenceNumber' => $tracking_id,
                ]);

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