<?php namespace App\Libs\Composers;

use App\Libs\Facades\Localization;
use EventItem;
use Illuminate\Support\Facades\DB;
use stdClass;

class UpcomingEventsComposer
{
    public function compose($view)
    {
        $day = date('d');
        $year = date('Y');
        $month = date('m');

        $lang = Localization::getActiveLocale();

        $nextMonths = DB::table('event_items')
            ->select(DB::raw("DISTINCT YEAR(date) as year, MONTH(date) as month"))
            ->join('website_objects AS wo', 'wo.object_id', '=', 'event_items.id')
            ->join('website_objects_lang AS wol', 'wol.website_object_id', '=', 'wo.website_object_id')
            ->where('wol.wo_language_id', $lang)
            ->where('lang_status', 'published')
            ->where('wo.content_type', 'event_item')
            ->where('status', 'published')
            ->where('no_index', 0)
            ->whereNull('event_items.deleted_at')
            ->whereRaw(DB::raw('event_items.end_date >= \''.$year.'-'.$month.'-'.$day.'\''))
            ->orderBy('year', 'asc')
            ->orderBy('month', 'asc')
            ->get();

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

        $months = array();

        foreach ($nextMonths as $nextMonth) {
            $label = $monthsNames[($nextMonth->month - 1)];
            $monthEvents = EventItem::full()
                ->where('status', 'published')
                ->where('lang_status', 'published')
                ->where('no_index', 0)
                ->whereRaw("YEAR(date) = $nextMonth->year AND MONTH(date) = $nextMonth->month")
                ->whereRaw(DB::raw('event_items.end_date >= \''.$year.'-'.$month.'-'.$day.'\''))
                ->orderBy('date', 'asc')
                ->get();

            $monthData = new stdClass();
            $monthData->title = trans('frontend.'.$label);
            $monthData->events = $monthEvents;

            array_push($months, $monthData);
        }

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