<?php namespace App\Libs\Composers;

use JobOffer;

class VacanciesComposer
{
    use SidebarComposerTrait;

    public function compose($view)
    {
        $data = $view->getData();
        $page = $data['object'];

        $vacancies = JobOffer::full()
            ->with(array('document', 'office'))
            ->where("status", "published")
            ->orderBy('position', 'asc')->get();

        $units = JobOffer::full()
            ->select(\DB::raw('DISTINCT(business_unit)'))
            ->where("status", "published")
            ->orderBy('business_unit', 'asc')
            ->get();
        $currentLang = \Localization::getActiveLocale();

        $countries = JobOffer::full()
            ->select(\DB::raw('DISTINCT(countries_lang.title)'))
            ->leftJoin('offices', 'job_offers.office_id', '=', 'offices.id')
            ->leftJoin('countries_lang', 'offices.country_id', '=', 'countries_lang.country_id')
            ->where('countries_lang.language_id', $currentLang)
            ->where("status", "published")
            ->get();

        $countriesFlex = JobOffer::full()
            ->select(\DB::raw('DISTINCT(countries_lang.title)'))
            ->leftJoin('job_offer_office', 'job_offers.id', '=', 'job_offer_office.job_offer_id')
            ->leftJoin('offices', 'job_offer_office.office_id', '=', 'offices.id')
            ->leftJoin('countries_lang', 'offices.country_id', '=', 'countries_lang.country_id')
            ->where('countries_lang.language_id', $currentLang)
            ->where("status", "published")
            ->get();

        $filterCountries = [];
        foreach ($countries as $country) {
            if (!in_array($country->title, $filterCountries)) {
                $filterCountries[] = $country->title;
            }
        }
        foreach ($countriesFlex as $country) {
            if (!in_array($country->title, $filterCountries)) {
                $filterCountries[] = $country->title;
            }
        }
        sort($filterCountries);

        $this->composeSidebar($view, \DefaultTemplateConfiguration::query());
        $templateData = \DefaultTemplateConfiguration
            ::full()->where('entry_id', $page->id)->first();

        $view->with(array(
            'vacancies' => $vacancies,
            'filterUnits' => $units,
            'filterCountries' => $filterCountries
        ));
    }
}
