<?php namespace App\Libs\Composers;

use App\Libs\Facades\RequestContext;
use App\Models\Office;

class OfficesMapComposer
{
    use RelatedComposerTrait;

    public function compose($view)
    {
        $offices = Office::full()
            ->with('country', 'contact', 'contact.image')
            ->where('status', 'published')
            ->orderBy('website_objects.position', 'asc')->get();

        $officeMarkers = array();
        foreach ($offices as $office) {
            $image = $office->overviewImage ? getMediaUrl($office->overviewImage->filename, '420x670') : '';
            $contact = null;
            if ($office->contact) {
                $contactImage = null;
                $contactEmailLink = null;
                if ($office->contact->image) {
                    $contactImage = getMediaUrl($office->contact->image->filename, '200x200');
                }
                if ($office->contact->email) {
                    $contactEmailLink = email_link_tag($office->contact->email);
                }
                $contact = array(
                    'name' => $office->contact->name,
                    'image' => $contactImage,
                    'emailLink' => $contactEmailLink
                );
            }

            $contactHash = $contact ? base64_encode(json_encode(["Contact_person" => $contact['name'] ])) : null;

            $marker = array(
                'markerType' => 'office-map',
                'id' => $office->id,
                'title' => $office->title,
                'location_lat' => $office->location_lat,
                'location_lng' => $office->location_lng,
                'location_zoom' => $office->location_zoom,
                'country' => $office->country->title,
                'continent' => $office->country->continent,
                'is_headquarter' => $office->is_headquarter,
                'content' => nl2br($office->address),
                'phone' => $office->phone,
                'fax' => $office->fax,
                'cta' => generateLink($office->cta, 'offices-map__box-icon-link offices-map__box-icon-link--external'),
                'detailImage' => $image,
                'contact' => $contact,
                'contactHash' => $contactHash
            );
            $officeMarkers[] = $marker;
        }

        RequestContext::set('load-google-maps', true);

        $view->with(array(
            'offices' => $officeMarkers
        ));
    }
}
