<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AbsensiModel;
use App\Models\SekolahModel;
use App\Models\KelasModel;
use App\Models\GuruModel;
use App\Models\SiswaModel;
use App\Models\SettingHariModel;
use App\Models\LiburNasionalModel; // Load Model Libur

class Laporan extends BaseController
{
    public function index()
    {
        $kelasModel = new KelasModel();
        $data = [
            'title' => 'Pusat Laporan',
            'kelas' => $kelasModel->findAll()
        ];
        return view('admin/laporan/index', $data);
    }

    public function cetakGuruDetail()
    {
        return $this->processDetail('guru', 'admin/laporan/cetak_guru_detail');
    }

    public function cetakSiswaDetail()
    {
        return $this->processDetail('siswa', 'admin/laporan/cetak_siswa_detail');
    }

    private function processDetail($type, $view)
    {
        $absensiModel = new AbsensiModel();
        $sekolahModel = new SekolahModel();

        $tglAwal = $this->request->getPost('tgl_awal');
        $tglAkhir = $this->request->getPost('tgl_akhir');
        $kelasId = $this->request->getPost('kelas_id');

        $dataLaporan = $absensiModel->getLaporan($tglAwal, $tglAkhir, $type, $kelasId);
        $sekolah = $sekolahModel->first();

        $infoKelas = '';
        if($type == 'siswa' && $kelasId) {
            $kelasModel = new KelasModel();
            $k = $kelasModel->find($kelasId);
            $infoKelas = $k['nama_kelas'] . ' ' . $k['jurusan'];
        }

        $data = [
            'absensi' => $dataLaporan,
            'sekolah' => $sekolah,
            'tgl_awal' => $tglAwal,
            'tgl_akhir' => $tglAkhir,
            'info_kelas' => $infoKelas
        ];

        return view($view, $data);
    }

    public function cetakGuruRekap()
    {
        $guruModel = new GuruModel();
        $users = $guruModel->orderBy('nama_guru', 'ASC')->findAll();
        return $this->processRekap('guru', $users, 'admin/laporan/cetak_guru_rekap');
    }

    public function cetakSiswaRekap()
    {
        $siswaModel = new SiswaModel();
        $kelasId = $this->request->getPost('kelas_id');
        
        $users = $siswaModel->where('kelas_id', $kelasId)->orderBy('nama_lengkap', 'ASC')->findAll();
        
        $kelasModel = new KelasModel();
        $k = $kelasModel->find($kelasId);
        $infoKelas = $k['nama_kelas'] . ' ' . $k['jurusan'];

        return $this->processRekap('siswa', $users, 'admin/laporan/cetak_siswa_rekap', $kelasId, $infoKelas);
    }

    private function processRekap($type, $users, $view, $kelasId = null, $infoKelas = '')
    {
        $absensiModel = new AbsensiModel();
        $sekolahModel = new SekolahModel();
        $settingHariModel = new SettingHariModel();
        $liburModel = new LiburNasionalModel(); // Init Model Libur

        $bulan = $this->request->getPost('bulan');
        $tahun = $this->request->getPost('tahun');

        $rekapAbsen = $absensiModel->getRekapBulanan($bulan, $tahun, $type, $kelasId);
        $sekolah = $sekolahModel->first();
        
        // Ambil mapping hari efektif [Senin=>1, Minggu=>0]
        $settingHariDB = $settingHariModel->findAll();
        $hariEfektif = [];
        foreach($settingHariDB as $h) {
            $hariEfektif[$h['nama_hari']] = $h['tampilkan'];
        }

        // --- LOGIKA BARU: Ambil Daftar Tanggal Libur Nasional Bulan Ini ---
        $tglAwalBulan = "$tahun-$bulan-01";
        $tglAkhirBulan = date("Y-m-t", strtotime($tglAwalBulan));
        
        // Cari libur yang beririsan dengan bulan ini
        $liburData = $liburModel->where('tanggal_akhir >=', $tglAwalBulan)
                                ->where('tanggal_mulai <=', $tglAkhirBulan)
                                ->findAll();
        
        $listLiburNasional = [];
        foreach ($liburData as $l) {
            // Expand range tanggal menjadi array tanggal tunggal (Y-m-d)
            $period = new \DatePeriod(
                new \DateTime($l['tanggal_mulai']),
                new \DateInterval('P1D'),
                (new \DateTime($l['tanggal_akhir']))->modify('+1 day')
            );
            foreach ($period as $dt) {
                // Masukkan hanya jika tanggal berada di bulan yang dipilih
                if ($dt->format('n') == $bulan && $dt->format('Y') == $tahun) {
                    $listLiburNasional[] = $dt->format('Y-m-d');
                }
            }
        }
        // -----------------------------------------------------------------

        $data = [
            'users' => $users,
            'rekap' => $rekapAbsen,
            'sekolah' => $sekolah,
            'bulan' => $bulan,
            'tahun' => $tahun,
            'jumlah_hari' => cal_days_in_month(CAL_GREGORIAN, $bulan, $tahun),
            'info_kelas' => $infoKelas,
            'hari_efektif' => $hariEfektif,
            'libur_nasional' => $listLiburNasional // Kirim data libur ke view
        ];

        return view($view, $data);
    }
}