<?php

namespace App\Controllers\TataUsaha;

use App\Controllers\BaseController;
use App\Models\SchoolSettingModel;
use App\Models\StudentModel;
use App\Models\TeacherModel;
use App\Models\ClassroomModel;
use App\Models\DashboardModel;
use App\Models\LetterLogModel;

class Dashboard extends BaseController
{
    public function index()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }

        if (session()->get('user_role') !== 'tata_usaha') {
            return redirect()->to('/dashboard');
        }

        $settingModel    = new SchoolSettingModel();
        $studentModel    = new StudentModel();
        $teacherModel    = new TeacherModel();
        $classroomModel  = new ClassroomModel();
        $dashboardModel  = new DashboardModel();
        $letterLogModel  = new LetterLogModel();

        // Ambil data dari dashboard model
        $activePeriod        = $dashboardModel->getActivePeriod();
        $totalActiveStudents = $dashboardModel->getTotalActiveStudents();
        $genderStats         = $dashboardModel->getGenderStats();

        // Hitung total guru, kelas
        $totalTeachers   = $teacherModel->where('deleted_at', null)->countAllResults();
        $totalClassrooms = $classroomModel->where('deleted_at', null)->countAllResults();

        // Hitung total surat yang diterbitkan
        $totalActiveLetters = $letterLogModel->where('letter_type', 'keterangan_aktif')->countAllResults();
        $totalMutasiLetters = $letterLogModel->where('letter_type', 'mutasi_keluar')->countAllResults();

        // Ambil 5 riwayat surat terbaru
        $recentLetters = $letterLogModel->getLogs(null, 5);

        // Ambil rekap siswa per kelas
        $classSummary = $dashboardModel->getClassSummary();

        $data = [
            'title'                 => 'Dasbor Tata Usaha',
            'setting'               => $settingModel->getSettings(),
            'total_active_students' => $totalActiveStudents,
            'total_teachers'        => $totalTeachers,
            'total_classrooms'      => $totalClassrooms,
            'total_active_letters'  => $totalActiveLetters,
            'total_mutasi_letters'  => $totalMutasiLetters,
            'active_period'         => $activePeriod,
            'gender_stats'          => $genderStats,
            'recent_letters'        => $recentLetters,
            'class_summary'         => $classSummary,
        ];

        return view('tata_usaha/dashboard', $data);
    }
}
