<?php

namespace App\Utils;

/**
 * this class is used to store method for sorting services on an order
 *
 */
class SortServicesSegments
{

	/**
	 * The order id
	 * @var int
	 */
	protected $idOrder = null;

	/**
	 * The list of service (and segment index - for itinerary services).
	 * Contains a numerically indexed array, with the value set as an associative array of two
	 * elements: idService and segmentIndex.
	 * @var array
	 */
	protected $serviceSegments = [];

	/**
	 * Sets the order id also.
	 * @param Int $idOrder
	 */
	public function __construct($serviceSegments = [])
	{
		if ($serviceSegments) {
			$this->setServiceSegments($serviceSegments);
		}
	}

	public function setServiceSegments(Array $serviceSegments)
	{
		$this->serviceSegments = $serviceSegments;
	}

	public function importFromOrder($idOrder)
	{
		$this->serviceSegments = \Entity\Order::select($idOrder)->servicesSegmentsList;
	}

	/**
	 * this method will sort the services from an order
	 * the sort will be made after the startDate of the offer
	 * if the service has not chosen offer, the start date will be filled from the service itself
	 * @return Array
	 */
	public function getSortedServicesSegments()
	{

		foreach ($this->serviceSegments as $servSegmDet) {

			$idService = $servSegmDet['idService'];
			if ($servSegmDet['segmentIndex']!==null) {
				$segmentIndex = $servSegmDet['segmentIndex'];
			} else {
				$segmentIndex = null;
			}

			$servEnt = \Entity\Service::select($idService);
			$offEnt = $servEnt->chosenOffer;

			// determine start date from offer or from service (for non-itinerary services) -------
			if ($segmentIndex===null) {
				if ($offEnt->recordExists()) {
					$startDate = $offEnt->startDatetime->formatDatetimeIso();
				} else {
					$startDate = $servEnt->startDate;
				}

				$services[$idService.'_'.$segmentIndex] = $startDate;

			}
			// determine the start date from itinerary segment ------------------------------------
			else {

				$itinSegments = [];
				if ($offEnt->itinerary) {
					$itinSegments = $offEnt->itinerary->getSegments(); // TODO: why no segments?
				}

				if ($itinSegments and $itinSegments[$segmentIndex]) {
					$currSegment = $itinSegments[$segmentIndex];
					$services[$idService.'_'.$segmentIndex] = $currSegment->getDepartureDateTime()->formatDatetimeIso();
				}

			}

		}


		// sort services and get their keys
		asort($services);
		$sortedServices = array_keys($services);

		// recompose the ordered services list
		$return = [];
		foreach($sortedServices as $servDet) {
			list($idService, $segmentIndex) = explode('_', $servDet);
			if (is_numeric($segmentIndex)) {
				$return[$idService.'_'.$segmentIndex] = ['idService'=>$idService, 'segmentIndex'=>$segmentIndex];
			} else {
				$return[$idService.'_'] = ['idService'=>$idService];
			}
		}

		return $return;

	}

}
