<?php

namespace Ignite\Core\Models\Dashboard\Charts;

use Ignite\Core\Entities\User;
use Illuminate\Support\Facades\DB;
use Ignite\Core\Models\Dashboard\CorrelatedStat;

class ParticipantsEnrolledStat extends CorrelatedStat
{
    /**
     * Create a new stat instance.
     *
     * @param  array|object $attributes
     */
    public function __construct($attributes = [])
    {
        $attributes = array_merge([
            'label' => 'Participants Enrolled',
            'color' => 'blue',
            'icon'  => 'ion ion-ios-personadd-outline',
            'link'  => url('/admin/participant/participants'),
            'sort'  => 3
        ], $attributes);

        parent::__construct($attributes);
    }

    /**
     * The HTML element ID.
     *
     * @return string
     */
    public function getElement()
    {
        return 'participants-enrolled-correlated-stat';
    }

    /**
     * The chart size in the layout.
     *
     * @return string
     */
    public function getSize()
    {
        return $this->get('size', 'col-xs-6 col-sm-3');
    }

    /**
     * Get the correct data value from storage.
     *
     * @return mixed
     */
    public function getData()
    {
        if (! $this->get('data', false)) {
            /**
             * @var \Carbon\Carbon $start
             * @var \Carbon\Carbon $end
             */
            list($start, $end) = $this->getDateRange();

            $this->attributes['data'] = DB::query()
                ->select(DB::raw('COUNT(id) as total'))
                ->from('core_user')
                ->where('status', User::STAT_ACTIVE)
                ->where('internal', User::TYPE_PARTICIPANT)
                ->whereBetween('created_at', [$start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')])
                ->count();

            $this->attributes['total'] = DB::query()
                  ->select(DB::raw('COUNT(id) as total'))
                  ->from('core_user')
                  ->where('internal', 0)
                  ->whereBetween('created_at', [$start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')])
                  ->count() ?? 1;

            $this->attributes['percentage'] = $this->calculatePercentage();
        }

        return $this->get('data');
    }
}
