<?php namespace App\Libs\Composers;

class ArticlesBlocksComposer
{
    public function compose($view)
    {
        $articleTypeModel = [
          'events' => 'EventItem',
          'publications' => 'Publication',
          'news' => 'News',
          'clippings' => 'Clipping'
        ];
        $block = $view->block;
        $articles = null;

        $listModel = 'News';
        if (in_array($block->type, ['clipping-news', 'clipping-list-news'])) {
            $listModel = 'Clipping';
        } else if (!empty($articleTypeModel[$block->article_type])) {
            $listModel = $articleTypeModel[$block->article_type];
        }

        if ($block->list_type == 'select') {
            $articles = $block->related('articles', 'position');
        } else {
            $itemCount = $block->item_count ?? 6;
            $articleQuery = $listModel::full()
                ->where('status', 'published')
                ->where('lang_status', 'published')
                ->orderBy('date', 'DESC')
                ->limit($itemCount);

            if ($block->article_type == 'publications') {
                $articleQuery->where('list_on_publications', 1);
            }

            if ($block->article_type == 'events') {
                $articleQuery->where('no_index', 0);
            }

            $articles = $articleQuery->get();
        }

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