<?php

namespace Ignite\Core\Models\Dashboard\Charts;

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

class TransactionTypeDonut extends Donut
{
    /**
     * Create a new stat instance.
     *
     * @param array|object $attributes
     */
    public function __construct($attributes = [])
    {
        $attributes = parent::__construct(array_merge([
            'label' => 'Transactions by type',
            'colors' => ['#ff851b', '#f56954'],
        ], $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'] = QueryPermissionFilters::for('core.user.transaction.browse')->apply(
                DB::query()
                    ->select(
                        DB::raw('type AS x'),
                        DB::raw('SUM(ABS(value)) as y')
                    )
                    ->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->x = ucwords(strtolower($row->x));
                    $row->y = (int)Format::amount($row->y, 2);
                    return $row;
                });
        }

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