<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Admin\Penelaah;
use App\Models\Admin\Pengajuan;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class ApiSakuController extends Controller
{
    public function index(){
        $penelaah = Penelaah::query()
            ->with('penelaah')
            // ->where('created_at', '<', '2024-05-20')
            ->orderBy('nip')
            ->get();

        foreach ($penelaah as $key => $pen) {
            $dataTelaah[] = [
                'id' => $pen->id,
                'nama' => $pen->nama,
                'nip' => $pen->nip,
                'nik' => $pen->nik,
                'unit' => $pen->unit,
                'created_at' => $pen->created_at,
                'judul' => $pen->penelaah->judul,
                'kode_kategori' => $pen->penelaah->kategori->kode_kategori,
                'nama_kategori' => $pen->penelaah->kategori->nama_kategori,
                'poin_saku' => $pen->penelaah->kategori->poin_saku,
                'tahun' => $pen->penelaah->tahun
            ];
        }

        return response()->json($dataTelaah);
    }

    public function saku1() {
        $totalPoin = 0;
        $jmlTelaah = Penelaah::query()
            ->select('nip', DB::raw('COUNT(nip) as jumlah'))
            ->groupBy('nip')
            ->where('created_at', '<', '2024-05-20')
            ->get();

        foreach ($jmlTelaah as $key => $telaah) {
            $penelaah = Penelaah::query()
                ->with('penelaah')
                ->where('nip', $telaah->nip)
                ->where('created_at', '<', '2024-05-20')
                ->get();

            foreach ($penelaah as $keys => $pen) {
                $totalPoin = $totalPoin + $pen->penelaah->kategori->poin_saku;

                $dataPenelaah[$telaah->nip] = [
                    'nama' => $pen->nama,
                    'nik' => $pen->nik,
                    'nip' => $pen->nip,
                    'unit' => $pen->unit,
                    'jumlah' => $telaah->jumlah,
                ];

                $dataTelaah[$keys] = [
                    'id_pengajuan_epk' => $pen->penelaah->id_pengajuan,
                    'judul' => $pen->penelaah->judul,
                    'peneliti' => $pen->penelaah->peneliti,
                    'klasifikasi' => $pen->penelaah->klasifikasi,
                    'file_ec' => $pen->penelaah->file_ec,
                    'no_sk' => $pen->penelaah->no_sk,
                    'kode_kategori' => $pen->penelaah->kategori->kode_kategori,
                    'nama_kategori' => $pen->penelaah->kategori->nama_kategori,
                    'poin_saku' => $pen->penelaah->kategori->poin_saku,
                ];

                $dataPenelaah[$telaah->nip]['telaah']=$dataTelaah;
                $dataPenelaah[$telaah->nip]['totalPoin']=$totalPoin;
            }
        }

        return response()->json($dataPenelaah);
    }
}
