<?php namespace Tobuli\Helpers\Dashboard\Blocks;

use Illuminate\Support\Facades\DB;
use ModalHelpers\AlertModalHelper;
use Tobuli\Helpers\Dashboard\Traits\HasPeriodOption;

class LatestEventsBlock extends Block
{
    use HasPeriodOption;

    protected function getName()
    {
        return 'latest_events';
    }

    protected function getContent()
    {
        $alerts_with_count = $this->user->events()
            ->select(DB::raw('count(*) as count, alerts.type'))
            ->join('alerts', 'alerts.id', '=', 'events.alert_id')
            ->where('events.created_at', '>=', $this->getPeriod())
            ->groupBy('alerts.type')
            ->get();

        if (is_null($alerts_with_count))
            return null;

        $types = array_pluck(AlertModalHelper::getTypes(), 'type');

        $events = array_combine($types, AlertModalHelper::getTypes());

        foreach ($alerts_with_count as $alert) {
            if ( ! isset($events[$alert->type]))
                continue;

            $events[$alert->type]['count'] = $alert->count;
        }

        arsort($events);

        return ['events' => $events];
    }

}