<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\AcademicPeriodModel;
use App\Models\AcademicYearModel;
use App\Models\ClassroomModel;
use App\Models\GradeModel;
use App\Models\StudentAcademicHistoryModel;
use App\Models\SchoolSettingModel;

class AttendanceSheet extends BaseController
{
    protected $periodModel;
    protected $yearModel;
    protected $classroomModel;
    protected $gradeModel;
    protected $historyModel;
    protected $schoolModel;

    public function __construct()
    {
        $this->periodModel   = new AcademicPeriodModel();
        $this->yearModel     = new AcademicYearModel();
        $this->classroomModel = new ClassroomModel();
        $this->gradeModel    = new GradeModel();
        $this->historyModel  = new StudentAcademicHistoryModel();
        $this->schoolModel   = new SchoolSettingModel();
    }

    private function checkLogin()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        return null;
    }

    public function index()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $activePeriod = $this->periodModel->getActive();
        
        $db = \Config\Database::connect();
        
        $teachers = $db->table('teachers')
            ->select('id, name, nip')
            ->where('deleted_at', null)
            ->orderBy('name', 'ASC')
            ->get()
            ->getResultArray();

        $subjects = $db->table('school_subjects')
            ->select('id, name, code')
            ->where('deleted_at', null)
            ->where('is_active', 1)
            ->orderBy('name', 'ASC')
            ->get()
            ->getResultArray();

        $data = [
            'title'        => 'Cetak Presensi & Dokumen',
            'activePeriod' => $activePeriod,
            'grades'       => $this->gradeModel->orderBy('order', 'ASC')->findAll(),
            'classrooms'   => $this->classroomModel->getAllWithRelations(),
            'months'       => $this->getMonths(),
            'teachers'     => $teachers,
            'subjects'     => $subjects,
        ];

        return view('attendance_sheet/index', $data);
    }

    public function print()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $activePeriod = $this->periodModel->getActive();
        if (!$activePeriod) {
            return redirect()->to('/attendance-sheet')
                ->with('error', 'Belum ada periode akademik yang aktif!');
        }

        $classroomId = $this->request->getGet('classroom_id');
        $gradeId     = $this->request->getGet('grade_id');
        $type        = $this->request->getGet('type') ?: 'bulanan'; // bulanan, guru, nilai, portrait

        // Parameter Bulanan/Guru/Nilai
        $month       = $this->request->getGet('month') ?: date('n');
        $year        = $this->request->getGet('year') ?: date('Y');
        
        // Parameter Mapel & Guru (opsional)
        $subjectId   = $this->request->getGet('subject_id');
        $teacherId   = $this->request->getGet('teacher_id');

        // Parameter Portrait dinamis
        $activityTitle = $this->request->getGet('activity_title') ?: 'Daftar Hadir Siswa';
        $activitySubtitle = $this->request->getGet('activity_subtitle') ?: '';
        $customDate    = $this->request->getGet('custom_date') ?: '';

        if (!$classroomId) {
            return redirect()->to('/attendance-sheet')
                ->with('error', 'Pilih kelas terlebih dahulu!');
        }

        $school       = $this->schoolModel->getSettings();
        $db           = \Config\Database::connect();

        $sheets = [];

        if ($classroomId === 'all') {
            // Ambil semua kelas di tingkat tersebut
            $classroomQuery = $db->table('classrooms')
                ->select('classrooms.*, grades.name as grade_name')
                ->join('grades', 'grades.id = classrooms.grade_id')
                ->where('classrooms.deleted_at', null);

            if ($gradeId) {
                $classroomQuery->where('classrooms.grade_id', $gradeId);
            }

            $classrooms = $classroomQuery->orderBy('classrooms.name', 'ASC')->get()->getResultArray();
        } else {
            // Ambil satu kelas
            $classroom = $this->classroomModel->getAllWithRelations();
            $classroom = array_filter($classroom, fn($c) => $c['id'] == $classroomId);
            $classroom = reset($classroom);
            $classrooms = $classroom ? [$classroom] : [];
        }

        foreach ($classrooms as $cls) {
            $students = $db->table('student_academic_histories as sah')
                ->select('students.id, students.nis, students.nisn, students.full_name, students.gender')
                ->join('students', 'students.id = sah.student_id')
                ->where('sah.classroom_id', $cls['id'])
                ->where('sah.academic_period_id', $activePeriod['id'])
                ->where('students.deleted_at', null)
                ->where('students.status', 'Aktif')
                ->orderBy('students.full_name', 'ASC')
                ->get()
                ->getResultArray();

            // Ambil Wali Kelas dari tabel homeroom_assignments
            $waliKelas = $db->table('homeroom_assignments')
                ->select('teachers.name, teachers.nip')
                ->join('teachers', 'teachers.id = homeroom_assignments.teacher_id')
                ->where('homeroom_assignments.classroom_id', $cls['id'])
                ->where('homeroom_assignments.academic_period_id', $activePeriod['id'])
                ->get()
                ->getRowArray();

            $sheets[] = [
                'classroom'  => $cls,
                'students'   => $students,
                'wali_kelas' => $waliKelas,
            ];
        }

        // Info Mapel & Guru (jika spesifik dipilih)
        $selectedSubject = null;
        if (!empty($subjectId)) {
            $selectedSubject = $db->table('school_subjects')->where('id', $subjectId)->get()->getRowArray();
        }
        $selectedTeacher = null;
        if (!empty($teacherId)) {
            $selectedTeacher = $db->table('teachers')->where('id', $teacherId)->get()->getRowArray();
        }

        // Jumlah hari dalam bulan (bawaan PHP)
        $daysInMonth = date('t', mktime(0, 0, 0, $month, 1, $year));

        // Nama hari tiap tanggal (1=Senin, 7=Minggu)
        $days = [];
        for ($d = 1; $d <= $daysInMonth; $d++) {
            $days[$d] = date('N', mktime(0, 0, 0, $month, $d, $year));
        }

        $data = [
            'title'            => 'Cetak Dokumen Administrasi Kelas',
            'school'           => $school,
            'activePeriod'     => $activePeriod,
            'sheets'           => $sheets,
            'month'            => $month,
            'monthName'        => $this->getMonths()[$month],
            'year'             => $year,
            'daysInMonth'      => $daysInMonth,
            'days'             => $days,
            'type'             => $type,
            'selectedSubject'  => $selectedSubject,
            'selectedTeacher'  => $selectedTeacher,
            'activityTitle'    => $activityTitle,
            'activitySubtitle' => $activitySubtitle,
            'customDate'       => $customDate,
        ];

        return view('attendance_sheet/print', $data);
    }

    private function getMonths()
    {
        return [
            1  => 'Januari',
            2  => 'Februari',
            3  => 'Maret',
            4  => 'April',
            5  => 'Mei',
            6  => 'Juni',
            7  => 'Juli',
            8  => 'Agustus',
            9  => 'September',
            10 => 'Oktober',
            11 => 'November',
            12 => 'Desember',
        ];
    }
}