<?php

namespace App\Services\ShipmentTracking;

use App\Services\Integrations\ShipmentTracking\FedexTracking;
use App\Services\Integrations\ShipmentTracking\UpsTracking;
use App\Models\AssetTracking;
use Carbon\Carbon;

class ShiShipmentService
{
	public function __construct(FedexTracking $fedexService, UpsTracking $upsService)
	{
		$this->fedexService = $fedexService;
		$this->upsService   = $upsService;
	}
	/**
	 * Update the Asset Tracking status by API response
	 */
	public function updateTrackingNumberStatus()
	{
		$trackingNos = AssetTracking::active()->get();
		foreach ($trackingNos as $key => $tackingNo) {

			if ($tackingNo->carrier == 'FedEx') {
				$trackingDetails = $this->fedexService->getTrackingDetails($tackingNo->tracking_number);
				$dataToUpdate 	 = $this->getDataToUpdate($trackingDetails);
				if ($dataToUpdate) {
					$tackingNo->update($dataToUpdate);
				}
			}

			if ($tackingNo->carrier == 'UPS') {
				$trackingDetails = $this->upsService->getTrackingDetails($tackingNo->tracking_number);
				$dataToUpdate 	 = $this->getDataToUpdate($trackingDetails);
				if ($dataToUpdate) {
					$tackingNo->update($dataToUpdate);
				}
			}
		}
	}

	/**
	 * Creating array for save the tracking details
	 * 
	 * @param $trackingStatus
	 */
	public function getDataToUpdate($trackingDetails)
	{
		if (empty($trackingDetails) || !isset($trackingDetails['status'])) {
			return null;
		}
		if (in_array($trackingDetails['status'], ['ERROR', 'No tracking information available', 'Invalid tracking number', 'No information found', 'Delivered'])) {
			$dateToUpdate['active']	= 0;

			return $dateToUpdate;
		}

		$dateToUpdate['shipment_status'] 	= $trackingDetails['status'];
		$dateToUpdate['status_updated_on'] 	= $trackingDetails['updated_on'];

		return $dateToUpdate;
	}
}
