<?php
namespace App\Service;

use Cake\Http\Client;
use Cake\Log\Log;

class CourierPleaseService
{
    protected $http;
    protected $account;
    protected $token;
    protected $sandbox;
    protected $urlSandbox;
    protected $urlProduction;
    protected $timeout;

    public function __construct()
    {
        $this->http = new Client();

        // READ FROM .env
        $this->account = env('COURIERPLEASE_ACCOUNT_NUMBER');
        $this->token = env('COURIERPLEASE_API_TOKEN');

        $this->sandbox = filter_var(env('COURIERPLEASE_USE_SANDBOX'), FILTER_VALIDATE_BOOLEAN);
        $this->urlSandbox = env('COURIERPLEASE_API_URL_SANDBOX');
        $this->urlProduction = env('COURIERPLEASE_API_URL_PRODUCTION');
        $this->timeout = (int) env('COURIERPLEASE_TIMEOUT', 30);
    }

    protected function getUrl()
    {
        return $this->sandbox ? $this->urlSandbox : $this->urlProduction;
    }

    public function track($trackingNumber)
    {
        $url = $this->getUrl();

        try {
            $response = $this->http->get($url, [
                'trackingCode' => $trackingNumber
            ], [
                'headers' => [
                    'Authorization' => 'Basic ' . base64_encode($this->account . ':' . $this->token),
                    'Accept' => 'application/json'
                ],
                'timeout' => $this->timeout
            ]);

            if (!$response->isOk()) {
                Log::error('CourierPlease API failed: ' . $response->getStringBody());
                return [
                    'success' => false,
                    'status_code' => $response->getStatusCode(),
                    'error_msg' => $response->getStringBody()
                ];
            }

            $data = $response->getJson();

            return [
                'success' => true,
                'data' => $data
            ];

        } catch (\Exception $e) {
            Log::error('CourierPlease Exception: ' . $e->getMessage());
            return [
                'success' => false,
                'error_msg' => 'Exception: ' . $e->getMessage()
            ];
        }
    }
}
