<?php

namespace App\Utils;

use DB;
use Illuminate\Support\Carbon;
use App\Model\Master\ItemKantongs;
use Auth;

class DashboardUtil
{
    public function getDataLast30Days($param, $petugas_udd_id, $date_at)
    {
        $query = ItemKantongs::where('status_id', $param)
                    ->where('unit_donor_darah_id', $petugas_udd_id)
                    ->whereBetween(DB::raw('date(kantong_items.'.$date_at.')'), [\Carbon::now()->subDays(30), \Carbon::now()])
                    ->orderBy($date_at, 'ASC');
        $query->select(
            DB::raw("DATE_FORMAT(kantong_items.".$date_at.", '%Y-%m-%d') as date, count(*) as total"),
        )
        ->groupBy(DB::raw('Date(kantong_items.'.$date_at.')'));
        $data = $query->get();

        $arr= [];
        for ($i = 29; $i >= 0; $i--) {
            $date = \Carbon::now()->subDays($i)->format('Y-m-d');
            $arr[$date] = 0;
        }

        for ($i = 29; $i >= 0; $i--) {
            $date = \Carbon::now()->subDays($i)->format('Y-m-d');

            if(!empty($data[$i])){ //cek data histori pendonor
                $tanggal = $data[$i]->date;
                $arr[$tanggal] = $data[$i]->total;
            }
        }

        ksort($arr);
        return $arr;
    }

    public function getDataLast1Years($param, $petugas_udd_id)
    {
        $now = Carbon::now();
        $year = $now->year;

        $query = DB::select("SELECT COUNT(*) as jumlah, MONTH(updated_at) as bulan FROM kantong_items WHERE YEAR(updated_at) = $year and status_id = $param and unit_donor_darah_id = $petugas_udd_id GROUP BY MONTH(updated_at)");

        $data = array();
        for($i=0; $i<=12; $i++)
        {
            if(!empty($query[$i])){
                if($query[$i]->bulan != $i+1){
                    $data[$i] = 0;
                }
                $bulan = $query[$i]->bulan;
                $data[$bulan] = $query[$i]->jumlah;
            }else{
                if(empty($data[$i])){
                    $data[$i] = 0;
                }
            }
        }
        ksort($data);
        return $data;
    }
}
