<?php

namespace Ignite\Core\Models\Dashboard\Charts;

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

class ParticipantEngagementGauge extends Gauge
{
    /**
     * Create a new stat instance.
     *
     * @param  array|object  $attributes
     */
    public function __construct($attributes = [])
    {
        parent::__construct(array_merge([
            'label' => 'Participant Engagement',
        ], $attributes ?? []));
    }


    /**
     * The HTML element ID.
     *
     * @return string
     */
    public function getElement()
    {
        return 'participant-engagement';
    }

    /**
     * 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();


            /*
             * select count(last_login_at between DATE_ADD(CURDATE(), INTERVAL -30 DAY) AND CURDATE()) / count(*) as percentage
                from core_user
                    join core_participant cp on core_user.user_id = cp.user_id
                where type = 'Participant';
            */
            $this->attributes['data'] = DB::query()
                ->select(
                    DB::raw(
                        'FORMAT(
                            (
                                count(
                                    last_login_at between DATE_ADD(CURDATE(), INTERVAL -90 DAY) AND CURDATE()
                                ) / count(*)
                            ) * 100
                        , 0) as percentage'
                    )
                )
                ->from('core_user')
                ->join('core_participant', 'core_user.user_id', 'core_participant.user_id')
                ->where('core_participant.internal', User::TYPE_PARTICIPANT)
                ->where('core_participant.status', '=', User::STAT_ACTIVE)
                ->where('core_participant.type', 'Participant')
                ->get();
        }

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