<?php

namespace App\Libs\Composers;

use CopItem;
use CopTopic;
use Storage;

class CopLandingPageComposer
{

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

        $topics = CopTopic::full()
            ->where('status', 'published')
            ->orderBy('website_objects.position', 'asc')
            ->with(['image', 'icon', 'copItems' => function($query) {
                $query->full()
                    ->with(['image'])
                    ->where('status', 'published');
            }])
            ->get();

        $itemsArray = [];
        $topicsArray = [];
        $ctaSuffix = '<span>' . view('frontend.svg.icon-arrow-complete')->render() . '</span>';
        foreach ($topics as $topic) {
            $topicSvg = file_get_contents(Storage::path(config('path.internal.media') . '/' . $topic->icon->filename));

            $topicsArray[] = [
                'id' => $topic->id,
                'title' => $topic->title,
                'svg' => $topicSvg,
                'color' => $topic->topic_color,
                'shortDescription' => $topic->short_description,
                'longDescription' => $topic->long_description,
                'cta' => $topic->cta ? generateLink($topic->cta, 'cop__contact-button', $ctaSuffix) : null,
                'image' => $topic->image ? getMediaUrl($topic->image->filename, "600x445") : null
            ];
            foreach ($topic->copItems as $item) {
                $itemsArray[] = [
                    'id' => $item->id,
                    'title' => $item->title,
                    'type' => $item->type,
                    'shortDescription' => $item->short_description,
                    'topicId' => $topic->id,
                    'topicTitle' => $topic->title,
                    'svg' => $topicSvg,
                    'location_lat' => $item->location_lat,
                    'location_lng' => $item->location_lng,
                    'markerType' => 'copitem',
                    'image' => $item->image ? getMediaUrl($item->image->filename, "600x445") : null,
                    'sourceUrl' => $item->source_url,
                    'ctaLabel' => $item->cta_label ? $item->cta_label : 'Click to view more',
                    'ctaDescription' => $item->cta_desc,
                    'cta' => $item->cta ? generateLink($item->cta) : null
                ];
            }
        }

        $view->with([
            'topics' => $topicsArray,
            'items' => $itemsArray
        ]);
    }
}
