<?php

namespace Ignite\Core\Models\Dashboard\Charts;

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

class ParticipantsInactiveStat extends CorrelatedStat
{
    /**
     * Create a new stat instance.
     *
     * @param array|object $attributes
     */
    public function __construct($attributes = [])
    {
        $attributes = array_merge([
            'label' => 'Participants Inactive',
            'color' => 'aqua',
            'icon' => 'fa-solid fa-user',
            'link' => url('/admin/participant/participants'),
            'sort' => 4,
        ], $attributes);

        parent::__construct($attributes);
    }


    /**
     * The HTML element ID.
     *
     * @return string
     */
    public function getElement()
    {
        return 'participants-inactive-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'] = QueryPermissionFilters::for('core.user.participant.browse')->apply(
                DB::query()
                    ->select(DB::raw('COUNT(id) as total'))
                    ->from('core_user')
                    ->where('status', User::STAT_INACTIVE)
                    ->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'] = QueryPermissionFilters::for('core.user.participant.browse')->apply(
                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();

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

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