<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Master\Instansi;
use App\Models\Master\Template;
use App\Models\Dataset;
use App\Models\Dataset\DatasetTable45;
use App\Models\Dataset\DatasetTable47;

class AjaxController extends Controller
{
    function getResourceData(Request $request){
        $_data = [];

        $keyId = decode_id($request->id);
        $instansi = Instansi::find($keyId);
        $resource = json_decode($instansi->resource_data);

        $data = Template::whereIn('MsTemplateId',$resource)->count();
        
        if(@$data != 0){
            $data = Template::whereIn('MsTemplateId',$resource)->get();
        }else{
            $data = Template::all();
        }

        foreach ($data as $key => $value) {
            $filename = pathinfo($value->template_url, PATHINFO_FILENAME); 

            $_data[$key]['id'] = encode_id($value->MsTemplateId);
            $_data[$key]['name'] = $filename.' - '.$value->name;
            $_data[$key]['excel'] = asset($value->template_url);
        }

        return response()->json(['data' => $_data,'status' => true]);
    }
    function getInstansi($type){
        $data = [];

        $instansi = Instansi::where('parent',$type)->get();

        foreach ($instansi as $key => $value) {
            $data[$key]['id'] = encode_id($value->MsInstansiId);
            $data[$key]['name'] = $value->name;
        }

        return response()->json(['data' => $data,'status' => true]);
    }

    function getPenduduk($tahun){
        $_data = [];

        $dataset = Dataset::whereIn('tahun',[$tahun])->pluck('DatasetId')->toArray();

        $data = DatasetTable45::whereIn('dataset_id',$dataset)->select('kabupaten_kota', 'jumlah_penduduk')->get();

        $labels = $data->pluck('kabupaten_kota');
        $series =  $data->pluck('jumlah_penduduk')->map(fn($v) => (int)$v);

        return response()->json([
            'labels' => $labels,
            'series' => $series,
        ]);

    }

    function getTimbulan($tahun){
        $_data = [];

        $dataset = Dataset::whereIn('tahun',[$tahun])->pluck('DatasetId')->toArray();

        $data = DatasetTable47::whereIn('dataset_id',$dataset)->select('kabupaten_kota', 'timbulan_sampah')->get();

        $labels = $data->pluck('kabupaten_kota');
        $series =  $data->pluck('timbulan_sampah')->map(fn($v) => (int)$v);

        return response()->json([
            'labels' => $labels,
            'series' => $series,
        ]);

    }
}
