<?php

namespace Ignite\Core\Models\Dashboard\Charts;

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

class TransactionTypeDonut extends Donut
{
    /**
     * Create a new stat instance.
     *
     * @param  array|object $attributes
     */
    public function __construct($attributes = [])
    {
        $attributes = array_merge([
            'label' => 'Transactions by Type',
            'colors' => ['#ff851b', '#f56954'],
            'icon'  => 'fa fa-money',
            'sort'  => 1
        ], $attributes);

        parent::__construct($attributes);
    }


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

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

    /**
     * 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('type AS label'),
                    DB::raw('SUM(ABS(value)) as value')
                )
                ->from('core_transaction')
                ->groupBy('type')
                ->whereIn('type', ['EARNED', 'REDEEMED'])
                ->whereNull('deleted_at')
                ->whereBetween('created_at', [$start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')])
                ->orderBy(DB::raw('FIELD(type, "EARNED", "REDEEMED")'))
                ->get()
                ->map(function ($row) {
                    $row->label = ucwords(strtolower($row->label));
                    $row->value = (int) Format::amount($row->value, 2);
                    return $row;
                });
        }

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