<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;

class KbmMonitor extends BaseController
{
    public function __construct()
    {
        helper(['app', 'letter']);
    }

    private function checkAccess()
    {
        if (!session()->get('logged_in')) {
            return redirect()->to('/login');
        }
        $role = session()->get('user_role');
        if (!in_array($role, ['superadmin', 'admin', 'kamad'])) {
            return redirect()->to('/dashboard')->with('error', 'Akses ditolak.');
        }
        return null;
    }

    // ── KBM HARI INI ──────────────────────────────────────────

    public function hariIni()
    {
        if ($redirect = $this->checkAccess()) return $redirect;

        $date   = $this->request->getGet('tanggal') ?: date('Y-m-d');
        $guruId = $this->request->getGet('guru') ? (int)$this->request->getGet('guru') : null;
        $kelasId = $this->request->getGet('kelas') ? (int)$this->request->getGet('kelas') : null;

        $db = db_connect();

        // Ambil periode akademik aktif beserta tahun ajaran terkait
        $activePeriod = $db->table('academic_periods ap')
            ->select('ap.id as period_id, ap.academic_year_id, ay.name as year_name')
            ->join('academic_years ay', 'ay.id = ap.academic_year_id')
            ->where('ap.is_active', 1)
            ->where('ap.deleted_at', null)
            ->get()->getRowArray();

        $activePeriodId = $activePeriod ? (int)$activePeriod['period_id'] : null;
        $activeYearId   = $activePeriod ? (int)$activePeriod['academic_year_id'] : null;

        // Ambil jurnal untuk tanggal tertentu
        $sql = "SELECT tj.*, t.name AS teacher_name, c.name AS classroom_name, ss.name AS subject_name
                FROM teaching_journals tj
                JOIN teachers t ON t.id = tj.teacher_id
                JOIN classrooms c ON c.id = tj.classroom_id
                JOIN school_subjects ss ON ss.id = tj.school_subject_id
                WHERE tj.meeting_date = ?
                  AND tj.deleted_at IS NULL";
        $params = [$date];

        if ($activePeriodId) {
            $sql .= " AND tj.academic_period_id = ?";
            $params[] = $activePeriodId;
        }
        if ($guruId) {
            $sql .= " AND tj.teacher_id = ?";
            $params[] = $guruId;
        }
        if ($kelasId) {
            $sql .= " AND tj.classroom_id = ?";
            $params[] = $kelasId;
        }

        $sql .= " ORDER BY c.name ASC, ss.name ASC";
        $journals = $db->query($sql, $params)->getResultArray();

        // Semua guru yang mengajar pada periode aktif (untuk filter)
        $semuaGuruSql = "SELECT DISTINCT t.id, t.name FROM teaching_journals tj
            JOIN teachers t ON t.id = tj.teacher_id
            WHERE tj.deleted_at IS NULL";
        $semuaGuruParams = [];
        if ($activePeriodId) {
            $semuaGuruSql .= " AND tj.academic_period_id = ?";
            $semuaGuruParams[] = $activePeriodId;
        }
        $semuaGuruSql .= " ORDER BY t.name";
        $semuaGuru = $db->query($semuaGuruSql, $semuaGuruParams)->getResultArray();

        // Semua kelas pada tahun ajaran aktif (untuk filter)
        if ($activeYearId) {
            $semuaKelas = $db->table('classrooms')
                ->select('id, name')
                ->where('academic_year_id', $activeYearId)
                ->where('deleted_at', null)
                ->orderBy('name', 'ASC')
                ->get()->getResultArray();
        } else {
            $semuaKelas = $db->table('classrooms')
                ->select('id, name')
                ->where('deleted_at', null)
                ->orderBy('name', 'ASC')
                ->get()->getResultArray();
        }

        // Cari guru yang belum isi jurnal hari ini — berdasarkan jadwal aktif hari tersebut
        $guruBelum = [];
        if ($activePeriodId) {
            $dayOfWeek = (int)date('N', strtotime($date));
            $sourceRow = $db->table('settings')->where('setting_key', 'schedule_source')->get()->getRowArray();
            $scheduleSource = $sourceRow['setting_value'] ?? 'local';

            if ($scheduleSource === 'asc') {
                $activeImport = $db->table('asc_imports')->where('is_active', 1)->get()->getRowArray();
                if ($activeImport) {
                    $guruBelumSql = "SELECT DISTINCT t.id, t.name, c.id AS classroom_id, c.name AS classroom_name
                        FROM asc_schedules asch
                        JOIN asc_teachers at ON at.asc_id = asch.teacher_asc_id AND at.import_id = asch.import_id
                        JOIN teachers t ON t.id = at.teacher_id
                        JOIN asc_classes ac ON ac.asc_id = asch.class_asc_id AND ac.import_id = asch.import_id
                        JOIN classrooms c ON c.id = ac.classroom_id
                        WHERE t.deleted_at IS NULL
                          AND t.is_active = 1
                          AND asch.import_id = ?
                          AND asch.day_number = ?
                          AND NOT EXISTS (
                              SELECT 1 FROM teaching_journals tj
                              WHERE tj.teacher_id = t.id
                                AND tj.classroom_id = c.id
                                AND tj.meeting_date = ?
                                AND tj.deleted_at IS NULL
                                AND tj.academic_period_id = ?
                          )
                        ORDER BY t.name, c.name";
                    $guruBelum = $db->query($guruBelumSql, [$activeImport['id'], $dayOfWeek, $date, $activePeriodId])->getResultArray();
                }
            } else {
                $publishedSchedule = $db->table('schedules')
                    ->where('academic_period_id', $activePeriodId)
                    ->where('status', 'published')
                    ->where('type', $scheduleSource)
                    ->get()->getRowArray();
                if ($publishedSchedule) {
                    $guruBelumSql = "SELECT DISTINCT t.id, t.name, c.id AS classroom_id, c.name AS classroom_name
                        FROM schedule_entries se
                        JOIN teachers t ON t.id = se.teacher_id
                        JOIN classrooms c ON c.id = se.classroom_id
                        WHERE t.deleted_at IS NULL
                          AND t.is_active = 1
                          AND se.schedule_id = ?
                          AND se.day = ?
                          AND NOT EXISTS (
                              SELECT 1 FROM teaching_journals tj
                              WHERE tj.teacher_id = t.id
                                AND tj.classroom_id = c.id
                                AND tj.meeting_date = ?
                                AND tj.deleted_at IS NULL
                                AND tj.academic_period_id = ?
                          )
                        ORDER BY t.name, c.name";
                    $guruBelum = $db->query($guruBelumSql, [$publishedSchedule['id'], $dayOfWeek, $date, $activePeriodId])->getResultArray();
                }
            }
        }

        $data = [
            'title'     => 'KBM Hari Ini',
            'journals'  => $journals,
            'guruBelum' => $guruBelum,
            'semuaGuru' => $semuaGuru,
            'semuaKelas'=> $semuaKelas,
            'tanggal'   => $date,
            'filterGuru' => $guruId,
            'filterKelas'=> $kelasId,
        ];

        return view('admin/kbm_hari_ini', $data);
    }

    // ── REKAP JURNAL ──────────────────────────────────────────

    public function rekap()
    {
        if ($redirect = $this->checkAccess()) return $redirect;

        $db = db_connect();

        // Ambil semester aktif
        $activePeriod = $db->query("SELECT ap.*, ay.name AS academic_year_name
            FROM academic_periods ap
            JOIN academic_years ay ON ay.id = ap.academic_year_id
            WHERE ap.is_active = 1
            LIMIT 1")->getRowArray();

        if (!$activePeriod) {
            return redirect()->to('/dashboard')->with('error', 'Tidak ada semester aktif.');
        }

        $periodId = $activePeriod['id'];

        // Rekap per guru — 1 baris per guru
        $sql = "SELECT
                    t.id AS teacher_id,
                    t.name AS teacher_name,
                    COUNT(tj.id) AS total_pertemuan,
                    COUNT(DISTINCT CONCAT(tj.classroom_id, '-', tj.school_subject_id)) AS total_kelas_mapel,
                    MAX(tj.meeting_date) AS terakhir_isi
                FROM teaching_journals tj
                JOIN teachers t ON t.id = tj.teacher_id
                WHERE tj.academic_period_id = ?
                  AND tj.deleted_at IS NULL
                GROUP BY t.id
                ORDER BY t.name ASC";
        $progress = $db->query($sql, [$periodId])->getResultArray();

        $data = [
            'title'    => 'Rekap Jurnal',
            'progress' => $progress,
            'targetJp' => 18,
            'period'   => $activePeriod,
        ];

        return view('admin/rekap_jurnal', $data);
    }

    // ── DETAIL JURNAL GURU (AJAX / VIEW) ─────────────────────

    public function detailGuru(int $teacherId)
    {
        if ($redirect = $this->checkAccess()) return $redirect;

        $db = db_connect();
        $activePeriod = $db->query("SELECT ap.id AS period_id, ay.name AS academic_year_name
            FROM academic_periods ap
            JOIN academic_years ay ON ay.id = ap.academic_year_id
            WHERE ap.is_active = 1 LIMIT 1")->getRowArray();
        if (!$activePeriod) return redirect()->to('/admin/kbm/rekap');

        $teacher = $db->query("SELECT * FROM teachers WHERE id = ?", [$teacherId])->getRowArray();
        if (!$teacher) return redirect()->to('/admin/kbm/rekap');

        $journals = $db->query("
            SELECT tj.*, c.name AS classroom_name, ss.name AS subject_name
            FROM teaching_journals tj
            JOIN classrooms c ON c.id = tj.classroom_id
            JOIN school_subjects ss ON ss.id = tj.school_subject_id
            WHERE tj.teacher_id = ?
              AND tj.academic_period_id = ?
              AND tj.deleted_at IS NULL
            ORDER BY c.name ASC, ss.name ASC, tj.meeting_date ASC
        ", [$teacherId, $activePeriod['period_id']])->getResultArray();

        // Ambil absensi
        $journalIds = array_column($journals, 'id');
        $absMap = [];
        if (!empty($journalIds)) {
            $placeholders = implode(',', $journalIds);
            $absentees = $db->query("SELECT ja.*, s.full_name FROM journal_attendances ja
                JOIN students s ON s.id = ja.student_id
                WHERE ja.journal_id IN ($placeholders)
                ORDER BY ja.journal_id, s.full_name")->getResultArray();
            foreach ($absentees as $a) {
                $absMap[$a['journal_id']][] = $a;
            }
        }

        // Kelompokkan jurnal per kelas+mapel
        $groups = [];
        foreach ($journals as $j) {
            $key = $j['classroom_id'] . '-' . $j['school_subject_id'];
            if (!isset($groups[$key])) {
                $groups[$key] = [
                    'classroom_name' => $j['classroom_name'],
                    'subject_name' => $j['subject_name'],
                    'journals' => [],
                ];
            }
            $groups[$key]['journals'][] = $j;
        }

        $data = [
            'title'    => 'Detail Jurnal Guru',
            'teacher'  => $teacher,
            'groups'   => $groups,
            'absMap'   => $absMap,
            'target'   => 18,
            'period'   => $activePeriod,
        ];

        return view('admin/kbm_detail_guru', $data);
    }

    // ── CETAK JURNAL KELAS BULANAN ─────────────────────────────

    public function jurnalKelas()
    {
        if ($redirect = $this->checkAccess()) return $redirect;

        $db = db_connect();

        // Get active period to filter classrooms by active academic year
        $activePeriod = $db->query("SELECT ap.*, ay.name AS academic_year_name
            FROM academic_periods ap
            JOIN academic_years ay ON ay.id = ap.academic_year_id
            WHERE ap.is_active = 1
            LIMIT 1")->getRowArray();

        $classrooms = [];
        if ($activePeriod) {
            $classrooms = $db->table('classrooms')
                ->where('academic_year_id', $activePeriod['academic_year_id'])
                ->where('deleted_at', null)
                ->orderBy('name', 'ASC')
                ->get()
                ->getResultArray();
        }

        $data = [
            'title'      => 'Cetak Jurnal Kelas',
            'classrooms' => $classrooms,
            'period'     => $activePeriod,
        ];

        return view('admin/jurnal_kelas_filter', $data);
    }

    public function exportJurnalKelas()
    {
        if ($redirect = $this->checkAccess()) return $redirect;

        $classroomId = $this->request->getGet('classroom_id');
        $month = $this->request->getGet('month');
        $year = $this->request->getGet('year');

        if (!$classroomId || !$month || !$year) {
            return redirect()->back()->with('error', 'Filter tidak lengkap!');
        }

        $db = db_connect();

        // Get active period
        $activePeriod = $db->query("SELECT ap.id, ay.name AS academic_year_name, ap.semester
            FROM academic_periods ap
            JOIN academic_years ay ON ay.id = ap.academic_year_id
            WHERE ap.is_active = 1
            LIMIT 1")->getRowArray();

        // Get classroom details
        $classroom = $db->table('classrooms')
            ->select('classrooms.*, grades.name as grade_name')
            ->join('grades', 'grades.id = classrooms.grade_id')
            ->where('classrooms.id', $classroomId)
            ->get()
            ->getRowArray();

        if (!$classroom) {
            return redirect()->back()->with('error', 'Kelas tidak ditemukan!');
        }

        // Get school settings
        $settingModel = new \App\Models\SchoolSettingModel();
        $schoolSettings = $settingModel->getSettings();

        // Get homeroom teacher (wali kelas)
        $homeroom = $db->table('homeroom_assignments')
            ->select('teachers.name as teacher_name, teachers.nip as teacher_nip')
            ->join('teachers', 'teachers.id = homeroom_assignments.teacher_id')
            ->where('homeroom_assignments.classroom_id', $classroomId)
            ->where('homeroom_assignments.academic_period_id', $activePeriod['id'])
            ->get()
            ->getRowArray();

        // Fetch journals for this classroom in selected month and year
        $startDate = "$year-$month-01";
        $endDate = date('Y-m-t', strtotime($startDate));

        $journals = $db->table('teaching_journals')
            ->select('teaching_journals.*, teachers.name as teacher_name, school_subjects.name as subject_name')
            ->join('teachers', 'teachers.id = teaching_journals.teacher_id')
            ->join('school_subjects', 'school_subjects.id = teaching_journals.school_subject_id')
            ->where('teaching_journals.classroom_id', $classroomId)
            ->where('teaching_journals.meeting_date >=', $startDate)
            ->where('teaching_journals.meeting_date <=', $endDate)
            ->where('teaching_journals.deleted_at', null)
            ->orderBy('teaching_journals.meeting_date', 'ASC')
            ->orderBy('teaching_journals.start_period', 'ASC')
            ->get()
            ->getResultArray();

        // Fetch all attendances for these journals
        $journalIds = array_column($journals, 'id');
        $absMap = [];
        if (!empty($journalIds)) {
            $placeholders = implode(',', $journalIds);
            $absentees = $db->query("SELECT ja.*, s.full_name, s.gender FROM journal_attendances ja
                JOIN students s ON s.id = ja.student_id
                WHERE ja.journal_id IN ($placeholders)
                ORDER BY ja.journal_id, s.full_name")->getResultArray();
            foreach ($absentees as $a) {
                $absMap[$a['journal_id']][] = $a;
            }
        }

        // Group journals by meeting_date
        $groupedJournals = [];
        foreach ($journals as $j) {
            $date = $j['meeting_date'];
            if (!isset($groupedJournals[$date])) {
                $groupedJournals[$date] = [];
            }
            $j['absentees'] = $absMap[$j['id']] ?? [];
            $groupedJournals[$date][] = $j;
        }

        $namaBulan = ['Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember'];

        $data = [
            'title'           => 'Jurnal Kelas ' . esc($classroom['name']),
            'classroom'       => $classroom,
            'groupedJournals' => $groupedJournals,
            'schoolSettings'  => $schoolSettings,
            'homeroom'        => $homeroom,
            'monthName'       => $namaBulan[(int)$month - 1],
            'year'            => $year,
            'activePeriod'    => $activePeriod,
        ];

        return view('admin/jurnal_kelas_print', $data);
    }
}
