<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;
use App\Models\SiswaModel;
use App\Models\AbsensiModel;

class Dashboard extends ResourceController
{
    protected $format = 'json';

    public function index()
    {
        $siswaModel = new SiswaModel();
        $absensiModel = new AbsensiModel();

        date_default_timezone_set('Asia/Jakarta');

        // Total siswa
        $totalSiswa = $siswaModel->countAllResults();

        // Tanggal hari ini
        $today = date('Y-m-d');

        // Total absensi hari ini
        $totalAbsensiHariIni = $absensiModel
            ->where('tanggal', $today)
            ->countAllResults();

        // Absensi terbaru 5 data (join dengan siswa untuk ambil nama & rombel)
        $absensiTerbaru = $absensiModel
            ->select('absensi.*, siswa.nama as nama_siswa, siswa.rombel')
            ->join('siswa', 'siswa.nisn = absensi.nisn', 'left')
            ->orderBy('absensi.tanggal', 'DESC')
            ->orderBy('absensi.waktu', 'DESC')
            ->limit(5)
            ->findAll();

        return $this->respond([
            'status' => true,
            'total_siswa' => $totalSiswa,
            'total_absensi_hari_ini' => $totalAbsensiHariIni,
            'absensi_terbaru' => $absensiTerbaru,
        ]);
    }

    /**
     * Endpoint untuk mendapatkan daftar rombel unik dari tabel siswa
     * GET /dashboard/rombel
     */
    public function rombel()
    {
        $siswaModel = new SiswaModel();
        $builder = $siswaModel->builder();
        $builder->select('rombel');
        $builder->groupBy('rombel');
        $rombelList = $builder->get()->getResultArray();

        $rombelNames = array_map(fn($r) => $r['rombel'], $rombelList);

        return $this->respond([
            'status' => true,
            'data' => $rombelNames,
        ]);
    }
}