<?php

namespace App\Livewire\Charts;

use Livewire\Component;
use App\Models\Form;
use DB;

class AreaChart extends Component
{
    public $chartData;

    public function render()
    {
        $chartData = $this->chartData;
        $categories = array();
        if (!empty($chartData->xaxis_categories)) {
            $cat = Form::where('form_id',$chartData->form_id)
                    ->select('form_content->'.$chartData->xaxis_categories.' as categories')
                    ->groupBy('form_content->'.$chartData->xaxis_categories)
                    ->get()
                    ->toArray();
            foreach ($cat as $val) {
                array_push($categories,$val['categories']);
            }
        }
        $datSeries = array();
        foreach ($chartData->series as $key => $item) {
            $datSeries[$key]['name'] = $item['name'];
            $datSeries[$key]['data'] = array();
            $formData = DB::select("SELECT
                SUM(JSON_UNQUOTE(JSON_EXTRACT(form_content, '$.\"" . $item['data'] . "\"'))) AS total
                FROM
                    `forms`
                WHERE
                    `form_id` = '".$chartData->form_id."'
                GROUP BY
                JSON_UNQUOTE(JSON_EXTRACT(form_content, '$.\"".$chartData->xaxis_categories."\"'))");
            foreach ($formData as $ke => $value) {
                $datSeries[$key]['data'][] = $value->total;
            }
        }
        return view('livewire.charts.area-chart',['series'=>$datSeries,'categories'=>$categories,'chart_data'=>$chartData]);
    }
}
