<?php
namespace Modules\Orders\Details\OrderCompanies;

class Model extends \Engine\Mvc\ModelAbstract
{
    /**
     * Current order ID
     * @var integer
     */
    protected $idOrder;

    /**
     * @param $idOrder
     */
    public function __construct($idOrder)
    {
        $this->idOrder = $idOrder;
    }

    /**
     * Get list of current order companies
     * @return array
     * @throws \Exception
     */
    public function getCompaniesList(): array
    {
        $idCorporatesList = \Entity\Order::select($this->idOrder)->idCorporatesList;

        // get the corporates list
        if ($idCorporatesList) {
            $listObj = new \App\EntityList\Corporates();
            $listObj->setColumns(['alias' => 'name', 'type', 'company', 'companyPrefix', 'companySuffix', 'fiscalCode', 'status']);
            $listObj->setFilter('id', 'IN', $idCorporatesList);

			// get companies by key
			$companiesByKey = [];
			foreach ($listObj->exportRecords() as $company) {
				$companiesByKey[$company['id']] = $company;
			}

			// return ordered by $idCorporatesList
			$companiesList = [];
			foreach ($idCorporatesList as $id) {
				if (isset($companiesByKey[$id])) {
					$companiesList[] = $companiesByKey[$id];
				}
			}
			return $companiesList;
        }

        return [];
    }

}
