<?php

namespace Ignite\Core\Models\Dashboard\Charts;

use Ignite\Core\Facades\Format;
use Illuminate\Support\Facades\DB;
use Ignite\Core\Models\Dashboard\Donut;

class ActivityStatusDonut extends Donut
{
    /**
     * Create a new stat instance.
     *
     * @param  array|object  $attributes
     */
    public function __construct($attributes = [])
    {
        $attributes = parent::__construct(array_merge([
            'label' => 'Referral Activity Status',
            /*'colors' => ['#d25454', '#394b87', '#40a147', '#a906f9', '#ececec'],*/
            'colors' => [
                "#ff595a", // 01 tomato
                "#10b9a2", // 02 lightseagreen
                "#8e82c1", // 03 mediumpurple
                "#cb5e93", // 04 palevioletred
                "#bed73c", // 05 yellowgreen
                "#eb961d", // 06 goldenrod
                "#626491", // 07 slategray
                "#febc14", // 08 orange -- really looks yellow
                "#f15622", // 09 chocolate (looks dark orange)
                "#575d60", // 10 dimgray
                "#7f2c2c", // 11 saddlebrown
            ],
        ], $attributes ?? []));
    }


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

    /**
     * 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("status AS x"),
                    DB::raw('count(*) as y')
                )
                ->from('activity_submission')
                ->groupBy('status')
                ->whereBetween('created_at', [$start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')])
                ->where('status', '<>', 'pending')
                ->orderBy('y')
                ->get()
                ->map(function ($row) {
                    $row->x = ucwords(strtolower($row->x));
                    $row->y = (int) Format::amount($row->y, 2);
                    return $row;
                });
        }

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