<?php namespace App\Libs\Composers\CF;

use EventItem;
use Lang;
use DB;
use CfDefaultTemplateCfg;

class CfEventsComposer
{
    use \App\Libs\Composers\SidebarComposerTrait,
        \App\Libs\Composers\BarComposerTrait,
        \App\Libs\Composers\CF\CfRelatedComposerTrait;

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

        $templateData = CfDefaultTemplateCfg::where('entry_id', $page->id)->first();

        $year = date('Y');
        $month = date('m');
        $today = date("Y-m-d");
        $events = EventItem::full()
            ->with('media', 'document')
            ->orderBy('date', 'asc')
            ->whereRaw("end_date >= '{$today}'")->get();

        $highlighted = EventItem::full()
            ->with('highlightImage')
            ->orderBy('date', 'asc')
            ->where("is_highlighted", 1)
            ->where('status', 'published')
            ->whereRaw("highlight_image_id IS NOT NULL")->first();

        $this->composeSidebar($view, \CfDefaultTemplateCfg::query());
        DB::flushQueryLog();
        $nextMonths = DB::table('event_items')
            ->select(DB::raw("DISTINCT YEAR(date) as year, MONTH(date) as month"))
            ->join('website_objects', 'website_objects.object_id', '=', 'event_items.id')
            ->where('website_objects.website_id', 2)
            ->where('website_objects.object_type', 'EventItem')
            ->whereRaw(DB::raw('end_date >= \''.$year.'-'.$month.'-01\''))
            ->where('status', 'published')
            ->orderBy('date', 'asc')
            ->get();

        $monthsNames = [
            'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august',
            'september', 'october', 'november', 'december'
        ];

        $months = array();
        array_push($months, array("id" => "0", "label" => Lang::get('frontend.all')));
        foreach ($nextMonths as $nextMonth) {
            $label = $monthsNames[($nextMonth->month - 1)];
            array_push($months, array(
                "id" => $nextMonth->month, "label" => Lang::get('frontend.'.$label), "sufix" => $nextMonth->year
            ));
        }

        $this->composeSidebar($view, \CfDefaultTemplateCfg::query());
        $this->composeBars($view, $templateData);
        $this->composeRelated($view, $templateData);

        $view->with(array(
            'events' => $events,
            'highlighted' => $highlighted,
            'filters' => array(
                array("id" => "month", "name" => Lang::get('frontend.month'), "values" => $months)
            )
        ));
    }
}
