<?php

namespace App\Controllers\Admin;

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

class LetterController extends BaseController
{
    protected $letterLogModel;
    protected $studentModel;
    protected $historyModel;
    protected $classroomModel;
    protected $gradeModel;
    protected $academicYearModel;
    protected $academicPeriodModel;
    protected $schoolSettingModel;
    protected $teacherModel;

    public function __construct()
    {
        $this->letterLogModel      = new LetterLogModel();
        $this->studentModel        = new StudentModel();
        $this->historyModel        = new StudentAcademicHistoryModel();
        $this->classroomModel      = new ClassroomModel();
        $this->gradeModel          = new GradeModel();
        $this->academicYearModel   = new AcademicYearModel();
        $this->academicPeriodModel = new AcademicPeriodModel();
        $this->schoolSettingModel  = new SchoolSettingModel();
        $this->teacherModel        = new TeacherModel();
    }

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

    /**
     * Halaman index - daftar riwayat semua surat
     */
    public function index(): string
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $type = $this->request->getGet('type');
        $logs = $this->letterLogModel->getLogs($type);

        $data = [
            'title' => 'Riwayat Surat Resmi',
            'logs'  => $logs,
            'type'  => $type,
        ];

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

    /**
     * Form: Surat Keterangan Aktif
     */
    public function keteranganAktif(): string
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $activePeriod = $this->academicPeriodModel->getActive();
        $activeStudents = $this->studentModel->where('status', 'Aktif')
                                             ->orderBy('full_name', 'ASC')
                                             ->findAll();

        $data = [
            'title'           => 'Surat Keterangan Aktif',
            'activeYear'      => $this->academicYearModel->getActive(),
            'activePeriod'    => $activePeriod,
            'activeStudents'  => $activeStudents,
        ];

        return view('letter/form_keterangan_aktif', $data);
    }

    /**
     * Preview: Surat Keterangan Aktif
     */
    public function keteranganAktifPreview()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'student_id'     => 'required|numeric',
            'letter_number'  => 'required|max_length[100]',
            'letter_date'    => 'required|valid_date',
            'purpose'        => 'required',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        $studentId = $this->request->getPost('student_id');
        $student = $this->studentModel->find($studentId);

        if (!$student) {
            return redirect()->back()->with('error', 'Data siswa tidak ditemukan');
        }

        // Get student class info
        $history = $this->historyModel->where('student_id', $studentId)
                                      ->where('academic_period_id', $this->academicPeriodModel->getActive()['id'])
                                      ->first();

        $classInfo = null;
        if ($history) {
            $classroom = $this->classroomModel->find($history['classroom_id']);
            $grade = $this->gradeModel->find($classroom['grade_id'] ?? null);
            $classInfo = [
                'classroom' => $classroom['name'] ?? '-',
                'grade'     => $grade['name'] ?? '-',
            ];
        }

        // Save log
        $logData = [
            'letter_type'   => 'keterangan_aktif',
            'letter_number' => $this->request->getPost('letter_number'),
            'student_id'    => $studentId,
            'student_name'  => $student['full_name'],
            'student_nis'   => $student['nis'],
            'letter_date'   => $this->request->getPost('letter_date'),
            'purpose'       => $this->request->getPost('purpose'),
            'printed_by'    => session()->get('user_id'),
        ];

        $logId = $this->letterLogModel->saveLog($logData);

        return redirect()->to('/letter')->with('success', 'Surat Keterangan Aktif berhasil disimpan!');
    }

    /**
     * Print: Surat Keterangan Aktif
     */
    public function keteranganAktifPrint($logId): string
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $log = $this->letterLogModel->find($logId);
        if (!$log) {
            return redirect()->to('/letter')->with('error', 'Data surat tidak ditemukan');
        }

        $student = $this->studentModel->find($log['student_id']);
        $schoolSettings = $this->schoolSettingModel->first();
        $activeYear = $this->academicYearModel->getActive();
        $activePeriod = $this->academicPeriodModel->getActive();

        // Get student class info
        $history = $this->historyModel->where('student_id', $log['student_id'])
                                      ->where('academic_period_id', $activePeriod['id'])
                                      ->first();

        $classInfo = null;
        if ($history) {
            $classroom = $this->classroomModel->find($history['classroom_id']);
            $grade = $this->gradeModel->find($classroom['grade_id'] ?? null);
            $classInfo = [
                'classroom' => $classroom['name'] ?? '-',
                'grade'     => $grade['name'] ?? '-',
            ];
        }

        // Get letter settings
        $settings = $this->getLetterSettings();

        $data = [
            'title'           => 'Cetak Surat Keterangan Aktif',
            'log'             => $log,
            'student'         => $student,
            'schoolSettings'  => $schoolSettings,
            'activeYear'      => $activeYear,
            'activePeriod'    => $activePeriod,
            'classInfo'       => $classInfo,
            'letterSettings'  => $settings,
        ];

        return view('letter/print_keterangan_aktif', $data);
    }

    /**
     * Form: Surat Mutasi
     */
    public function mutasi(): string
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        // Get only students with status 'Mutasi'
        $students = $this->studentModel->where('status', 'Mutasi')
                                       ->orderBy('full_name', 'ASC')
                                       ->findAll();

        $data = [
            'title'    => 'Surat Mutasi Keluar',
            'students' => $students,
        ];

        return view('letter/form_mutasi', $data);
    }

    /**
     * Preview: Surat Mutasi
     */
    public function mutasiPreview()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'student_id'     => 'required|numeric',
            'letter_number'  => 'required|max_length[100]',
            'letter_date'    => 'required|valid_date',
            'destination'    => 'required|max_length[200]',
            'reason'         => 'required',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        $studentId = $this->request->getPost('student_id');
        $student = $this->studentModel->find($studentId);

        if (!$student) {
            return redirect()->back()->with('error', 'Data siswa tidak ditemukan');
        }

        if ($student['status'] !== 'Mutasi') {
            return redirect()->back()->with('error', 'Siswa tidak berstatus Mutasi');
        }

        // Get student class info
        $history = $this->historyModel->where('student_id', $studentId)
                                      ->orderBy('id', 'DESC')
                                      ->first();

        $classInfo = null;
        if ($history) {
            $classroom = $this->classroomModel->find($history['classroom_id']);
            $grade = $this->gradeModel->find($classroom['grade_id'] ?? null);
            $classInfo = [
                'classroom' => $classroom['name'] ?? '-',
                'grade'     => $grade['name'] ?? '-',
            ];
        }

        // Save log
        $logData = [
            'letter_type'   => 'mutasi_keluar',
            'letter_number' => $this->request->getPost('letter_number'),
            'student_id'    => $studentId,
            'student_name'  => $student['full_name'],
            'student_nis'   => $student['nis'],
            'letter_date'   => $this->request->getPost('letter_date'),
            'destination'   => $this->request->getPost('destination'),
            'reason'        => $this->request->getPost('reason'),
            'printed_by'    => session()->get('user_id'),
        ];

        $logId = $this->letterLogModel->saveLog($logData);

        return redirect()->to('/letter')->with('success', 'Surat Mutasi Keluar berhasil disimpan!');
    }

    /**
     * Print: Surat Mutasi
     */
    public function mutasiPrint($logId): string
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $log = $this->letterLogModel->find($logId);
        if (!$log) {
            return redirect()->to('/letter')->with('error', 'Data surat tidak ditemukan');
        }

        $student = $this->studentModel->find($log['student_id']);
        $schoolSettings = $this->schoolSettingModel->first();

        // Get student class info
        $history = $this->historyModel->where('student_id', $log['student_id'])
                                      ->orderBy('id', 'DESC')
                                      ->first();

        $classInfo = null;
        if ($history) {
            $classroom = $this->classroomModel->find($history['classroom_id']);
            $grade = $this->gradeModel->find($classroom['grade_id'] ?? null);
            $classInfo = [
                'classroom' => $classroom['name'] ?? '-',
                'grade'     => $grade['name'] ?? '-',
            ];
        }

        // Get letter settings
        $settings = $this->getLetterSettings();

        $data = [
            'title'           => 'Cetak Surat Mutasi Keluar',
            'log'             => $log,
            'student'         => $student,
            'schoolSettings'  => $schoolSettings,
            'classInfo'       => $classInfo,
            'letterSettings'  => $settings,
        ];

        return view('letter/print_mutasi', $data);
    }

    /**
     * AJAX: Ambil data siswa untuk auto-fill
     */
    public function getStudentData()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $studentId = $this->request->getGet('id');
        $student = $this->studentModel->find($studentId);

        if (!$student) {
            return $this->response->setJSON(['error' => 'Siswa tidak ditemukan']);
        }

        // Get class info
        $activePeriod = $this->academicPeriodModel->getActive();
        $history = $this->historyModel->where('student_id', $studentId)
                                      ->where('academic_period_id', $activePeriod['id'])
                                      ->first();

        $classInfo = null;
        if ($history) {
            $classroom = $this->classroomModel->find($history['classroom_id']);
            $grade = $this->gradeModel->find($classroom['grade_id'] ?? null);
            $classInfo = [
                'classroom' => $classroom['name'] ?? '-',
                'grade'     => $grade['name'] ?? '-',
            ];
        }

        return $this->response->setJSON([
            'student'   => $student,
            'classInfo' => $classInfo,
        ]);
    }

    /**
     * Hapus riwayat surat
     */
    public function deleteLog($id)
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $this->letterLogModel->delete($id);
        return redirect()->to('/letter')->with('success', 'Riwayat surat berhasil dihapus');
    }

    /**
     * Get letter settings from settings table
     */
    private function getLetterSettings()
    {
        $settings = $this->schoolSettingModel->first();
        
        return [
            'kemenag_office'     => $settings['letter_kemenag_office'] ?? 'Kantor Kementerian Agama Kab. Wonogiri',
            'letter_school_name' => $settings['letter_school_name']
                ?? strtoupper($settings['school_name'] ?? 'MADRASAH TSANAWIYAH NEGERI'),
            'school_code'        => $settings['letter_school_code'] ?? 'MTs.11.22',
            'city'               => $settings['letter_city'] ?? $settings['city'] ?? 'Wonogiri',
            'logo_kemenag'       => $settings['logo_kemenag'] ?? 'logo_kemenag.png',
        ];
    }

    /**
     * AJAX: Ambil data guru untuk auto-fill
     */
    public function getTeacherData()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teacherId = $this->request->getGet('id');
        $teacher   = $this->teacherModel->find($teacherId);

        if (!$teacher) {
            return $this->response->setJSON(['error' => 'Guru tidak ditemukan']);
        }

        return $this->response->setJSON(['teacher' => $teacher]);
    }

    // =========================================================
    // SURAT TUGAS
    // =========================================================

    /**
     * Form: Surat Tugas
     */
    public function suratTugas(): string
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teachers = $this->teacherModel
            ->where('is_active', 1)
            ->where('deleted_at', null)
            ->orderBy('name', 'ASC')
            ->findAll();

        $data = [
            'title'      => 'Surat Tugas',
            'activeYear' => $this->academicYearModel->getActive(),
            'teachers'   => $teachers,
        ];

        return view('letter/form_surat_tugas', $data);
    }

    /**
     * Preview & Simpan: Surat Tugas
     */
    public function suratTugasPreview()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'officer_name'     => 'required|max_length[200]',
            'letter_number'    => 'required|max_length[100]',
            'letter_date'      => 'required|valid_date',
            'assignment_detail'=> 'required',
            'assignment_start' => 'required|valid_date',
            'assignment_end'   => 'required|valid_date',
            'assignment_place' => 'required|max_length[300]',
            'is_reference'     => 'required|in_list[0,1]',
        ];

        if ($this->request->getPost('is_reference') === '1') {
            $rules['reference_officer'] = 'required|max_length[200]';
            $rules['reference_number']  = 'required|max_length[100]';
            $rules['reference_date']    = 'required|valid_date';
            $rules['reference_theme']   = 'required|max_length[300]';
        }

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        // Capture teacher info for dynamic identifier label
        $teacherId = $this->request->getPost('teacher_id') ?: null;
        $teacherIdNumber = $this->request->getPost('officer_nip');
        $teacherIdLabel  = 'NIP';
        if ($teacherId) {
            $teacher = $this->teacherModel->find($teacherId);
            if ($teacher) {
                $teacherIdNumber = teacher_id_number($teacher);
                $teacherIdLabel  = teacher_id_label($teacher['status_kepegawaian'] ?? null);
            }
        } elseif (!empty($teacherIdNumber) && strlen($teacherIdNumber) !== 18) {
            $teacherIdLabel = 'PEG ID/NPK/NUPTK';
        }

        $logData = [
            'letter_type'       => 'surat_tugas',
            'letter_number'     => $this->request->getPost('letter_number'),
            'letter_date'       => $this->request->getPost('letter_date'),
            'officer_name'      => $this->request->getPost('officer_name'),
            'teacher_id'        => $teacherId,
            'teacher_id_number' => $teacherIdNumber,
            'teacher_id_label'  => $teacherIdLabel,
            'officer_nip'       => $this->request->getPost('officer_nip'),
            'officer_rank'      => $this->request->getPost('officer_rank'),
            'officer_position'  => $this->request->getPost('officer_position'),
            'task_description'  => $this->request->getPost('assignment_detail'),
            'date_start'        => $this->request->getPost('assignment_start'),
            'date_end'          => $this->request->getPost('assignment_end'),
            'origin'            => $this->request->getPost('assignment_place'),
            'is_reference'      => (int)$this->request->getPost('is_reference'),
            'reference_officer' => $this->request->getPost('reference_officer') ?: null,
            'reference_number'  => $this->request->getPost('reference_number') ?: null,
            'reference_date'    => $this->request->getPost('reference_date') ?: null,
            'reference_theme'   => $this->request->getPost('reference_theme') ?: null,
            'printed_by'        => session()->get('user_id'),
        ];

        $logId = $this->letterLogModel->saveLog($logData);

        return redirect()->to('/letter')->with('success', 'Surat Tugas berhasil disimpan!');
    }

    /**
     * Print: Surat Tugas
     */
    public function suratTugasPrint($logId): string
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $log = $this->letterLogModel->find($logId);
        if (!$log) {
            return redirect()->to('/letter')->with('error', 'Data surat tidak ditemukan');
        }

        $schoolSettings = $this->schoolSettingModel->first();
        $settings       = $this->getLetterSettings();
        $activeYear     = $this->academicYearModel->getActive();

        $data = [
            'title'          => 'Cetak Surat Tugas',
            'log'            => $log,
            'schoolSettings' => $schoolSettings,
            'letterSettings' => $settings,
            'activeYear'     => $activeYear,
        ];

        return view('letter/print_surat_tugas', $data);
    }

    // =========================================================
    // SPPD (Surat Perjalanan Dinas)
    // =========================================================

    /**
     * Form: SPPD
     */
    public function sppd(): string
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $teachers = $this->teacherModel
            ->where('is_active', 1)
            ->where('deleted_at', null)
            ->orderBy('name', 'ASC')
            ->findAll();

        // Ambil sumber biaya SPPD terakhir sebagai default agar admin tidak perlu mengetik ulang tiap surat
        $latestSppd = $this->letterLogModel
            ->where('letter_type', 'sppd')
            ->orderBy('id', 'DESC')
            ->first();
        $defaultBudgetSource = $latestSppd['budget_source'] ?? '';

        $data = [
            'title'               => 'Surat Perjalanan Dinas (SPPD)',
            'activeYear'          => $this->academicYearModel->getActive(),
            'teachers'            => $teachers,
            'defaultBudgetSource' => $defaultBudgetSource,
        ];

        return view('letter/form_sppd', $data);
    }

    /**
     * Preview & Simpan: SPPD
     */
    public function sppdPreview()
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $rules = [
            'officer_name'          => 'required|max_length[200]',
            'letter_number'         => 'required|max_length[100]',
            'letter_date'           => 'required|valid_date',
            'assignment_detail'     => 'required',
            'assignment_start'      => 'required|valid_date',
            'assignment_end'        => 'required|valid_date',
            'assignment_place'      => 'required|max_length[300]',
            'assignment_place_city' => 'required|max_length[100]',
            'transport_mode'        => 'required|max_length[100]',
        ];

        if (!$this->validate($rules)) {
            return redirect()->back()
                ->with('errors', $this->validator->getErrors())
                ->withInput();
        }

        // Capture teacher info for dynamic identifier label
        $teacherId = $this->request->getPost('teacher_id') ?: null;
        $teacherIdNumber = $this->request->getPost('officer_nip');
        $teacherIdLabel  = 'NIP';
        if ($teacherId) {
            $teacher = $this->teacherModel->find($teacherId);
            if ($teacher) {
                $teacherIdNumber = teacher_id_number($teacher);
                $teacherIdLabel  = teacher_id_label($teacher['status_kepegawaian'] ?? null);
            }
        } elseif (!empty($teacherIdNumber) && strlen($teacherIdNumber) !== 18) {
            $teacherIdLabel = 'PEG ID/NPK/NUPTK';
        }

        $logData = [
            'letter_type'      => 'sppd',
            'letter_number'    => $this->request->getPost('letter_number'),
            'letter_date'      => $this->request->getPost('letter_date'),
            'officer_name'     => $this->request->getPost('officer_name'),
            'teacher_id'       => $teacherId,
            'teacher_id_number'=> $teacherIdNumber,
            'teacher_id_label' => $teacherIdLabel,
            'officer_nip'      => $this->request->getPost('officer_nip'),
            'officer_rank'     => $this->request->getPost('officer_rank'),
            'officer_position' => $this->request->getPost('officer_position'),
            'task_description' => $this->request->getPost('assignment_detail'),
            'date_start'       => $this->request->getPost('assignment_start'),
            'date_end'         => $this->request->getPost('assignment_end'),
            'origin'           => $this->request->getPost('assignment_place'),
            'destination'      => $this->request->getPost('assignment_place_city'),
            'transport'        => $this->request->getPost('transport_mode'),
            'budget_source'    => $this->request->getPost('cost_source'),
            'printed_by'       => session()->get('user_id'),
        ];

        $logId = $this->letterLogModel->saveLog($logData);

        return redirect()->to('/letter')->with('success', 'SPPD berhasil disimpan!');
    }

    /**
     * Print: SPPD
     */
    public function sppdPrint($logId): string
    {
        if ($redirect = $this->checkLogin()) return $redirect;

        $log = $this->letterLogModel->find($logId);
        if (!$log) {
            return redirect()->to('/letter')->with('error', 'Data surat tidak ditemukan');
        }

        $schoolSettings = $this->schoolSettingModel->first();
        $settings       = $this->getLetterSettings();

        $data = [
            'title'          => 'Cetak SPPD',
            'log'            => $log,
            'schoolSettings' => $schoolSettings,
            'letterSettings' => $settings,
        ];

        return view('letter/print_sppd', $data);
    }
}