<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use CodeIgniter\HTTP\ResponseInterface;
use App\Models\EvaluasiModel;
use App\Models\GuruModel;
use App\Models\Periode;

class RekapPeform extends BaseController
{
    protected $evaluasiModel;
    protected $guruModel;

    public function __construct()
    {
        $this->evaluasiModel = new EvaluasiModel();
        $this->guruModel = new GuruModel();
    }

    public function index()
    {
        $periodeModel = new Periode();
        $dataperiode = $periodeModel->findAll();
        $guruList = $this->guruModel->findAll();

        $rekap = [];

        foreach ($dataperiode as $periode) {
            $periodeRekap = [
                'periode' => $periode,
                'guru' => []
            ];

            foreach ($guruList as $guru) {
                $evaluasi = $this->evaluasiModel
                    ->where('periode', $periode['id'])
                    ->where('id_guru', $guru['id'])
                    ->first();

                $totalNilai = 0;

               if ($evaluasi) {
                // Ambil nilai akhir yang sudah dihitung dari tabel evaluasi_kinerja
                $totalNilai = $evaluasi['nilai'] ?? 0;
            }


                $periodeRekap['guru'][] = [
                    'id_guru' => $guru['id'],
                    'nama_guru' => $guru['nama_guru'],
                    'total_nilai' => $totalNilai
                ];
            }

            $rekap[] = $periodeRekap;
        }

        // Tambahkan pembuatan periodeList dari $rekap
        $periodeList = [];
        foreach ($rekap as $item) {
            $label = $item['periode']['nama_periode'] . ' ' . $item['periode']['tahun_ajaran'];
            if (!in_array($label, $periodeList)) {
                $periodeList[] = $label;
            }
        }

        return view('rekap_perform/index', [
            'rekap' => $rekap,
            'periodeList' => $periodeList
        ]);
    }
}
