<?php

namespace App\Http\Controllers\Assets;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Asset;
use App\Models\AssetTracking;
use App\Services\Integrations\ShipmentTracking\FedexTracking;
use App\Services\Integrations\ShipmentTracking\UpsTracking;
use App\User;

class AssetTrackingController extends Controller
{

	public function __construct(FedexTracking $fedexService, UpsTracking $upsService)
	{
		$this->fedexService = $fedexService;
		$this->upsService   = $upsService;
	}

	public function updateTrackingNumber(Request $request)
	{

		$userAssets = User::with('assets')->where('id', $request->user_id)->first();
		if (empty($request->tracking_number)) {
			foreach ($userAssets->assets as $asset) {
				$asset->update(['asset_tracking_id' => ""]);
			}

			return redirect()->back()->with('message', __('message.updated'));
		}


		$assetTracking = AssetTracking::firstOrCreate(['tracking_number' => $request->tracking_number]);


		foreach ($userAssets->assets as $asset) {
			$asset->update(['asset_tracking_id' => $assetTracking->id]);
		}

		$this->updateTrackingStatus($assetTracking);

		return redirect()->back()->with('message', __('message.updated'));
	}

	public function updateTrackingStatus($assetTracking)
	{
		if (isUpsTrackingNo($assetTracking->tracking_number)) {
			$trackingDetails = $this->upsService->getTrackingDetails($assetTracking->tracking_number);
		} else {
			$trackingDetails = $this->fedexService->getTrackingDetails($assetTracking->tracking_number);
		}

		if ($trackingDetails) {
			$dataToUpdate 	 = $this->getDataToUpdate($trackingDetails);
			if ($dataToUpdate) {
				$assetTracking->update($dataToUpdate);
			}
		}
	}

	/**
	 * Creating array for save the tracking details
	 * 
	 * @param $trackingStatus
	 */
	public function getDataToUpdate($trackingDetails)
	{
		if (in_array($trackingDetails['status'], ['ERROR', 'No tracking information available'])) {
			$dataToUpdate['active']	= 0;

			return $dataToUpdate;
		}

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

		if ($trackingDetails['status'] == 'Delivered') {
			$dataToUpdate['active']	 	    = 0;
		}

		return $dataToUpdate;
	}

	/**
	 * processing Jamf Sync 
	 */
	public function manualSync()
	{
		$assetTrackings = AssetTracking::where('active', 1)->get();

		foreach ($assetTrackings as $assetTracking) {
			$this->updateTrackingStatus($assetTracking);
		}

		return response()->json(array('status' => 'success', 'message' => "Sync completed"));
	}
}
