<?php

namespace Ignite\Core\Models\Dashboard\Charts;

use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use Ignite\Core\Models\Dashboard\Line;

class ParticipantEnrollmentLine extends Line
{
    /**
     * ParticipantEnrollmentLine.
     *
     * @param array $attributes
     */
    public function __construct($attributes = [])
    {
        parent::__construct(array_merge([
            'icon' => 'ion ion-ios-people',
            'label' => 'Participant Enrollment',
            'element' => 'participant-chart',
            'colors' => ['#3c8dbc', '#a0d0e0'],
            'labels' => ['Participants Approved', 'Participants Pending'],
            'xkey' => 'date',
            'ykeys' => ['approved', 'pending']
        ], $attributes));
    }

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

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

    /**
     * Get the correct data value from storage.
     *
     * @return mixed
     */
    public function getData()
    {
        if (! $this->get('data', false)) {
            $this->attributes['data'] = array_values(
                $this->transformData($this->query())
            );
        }

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

    /**
     * Transform the data.
     *
     * @param  Collection $results
     * @return array
     */
    private function transformData(Collection $results)
    {
        $data = [];

        foreach ($results as $result) {
            $date = $result->pending_date;
            $data[$date]['date'] = $date;
            $data[$date]['pending'] = ($result->status === 2) ? $result->total : $data[$date]['pending'] ?? 0;
            $data[$date]['approved'] = ($result->status === 1) ? $result->total : $data[$date]['approved'] ?? 0;
        }

        return $data;
    }

    /**
     * Query the database.
     *
     * @return Collection
     */
    private function query()
    {
        DB::select(DB::raw('SET session sql_mode=""'));

        /**
         * @var \Carbon\Carbon $start
         * @var \Carbon\Carbon $end
         */
        list($start, $end) = $this->getDateRange();
        return DB::query()
            ->select(
                DB::raw('DATE_FORMAT(created_at, "%Y-%m") AS pending_date'),
                DB::raw('DATE_FORMAT(approved_at, "%Y-%m") AS approved_date'),
                'status',
                DB::raw('COUNT(status) as total')
            )
            ->from('core_participant')
            ->where(function ($query) {
                $query->where('status', '=', '2')->orWhere('status', '=', '1');
            })
            ->whereBetween('created_at', [$start->format('Y-m-d H:i:s'), $end->format('Y-m-d H:i:s')])
            ->groupBy(
                'status',
                DB::raw('DATE_FORMAT(created_at, "%Y-%m")'),
                DB::raw('DATE_FORMAT(approved_at, "%Y-%m")')
            )
            ->orderBy('approved_at', 'ASC')
            ->orderBy('created_at', 'ASC')
            ->get();
    }
}
