<?php

namespace App\Controllers\Guru;

use App\Controllers\BaseController;
use App\Models\TeacherModel;
use App\Models\AcademicPeriodModel;
use App\Models\CounselingTicketModel;
use App\Models\CounselingMessageModel;

class Counseling extends BaseController
{
    protected $teacherModel;
    protected $periodModel;
    protected $ticketModel;
    protected $messageModel;

    public function initController(\CodeIgniter\HTTP\RequestInterface $request, \CodeIgniter\HTTP\ResponseInterface $response, \Psr\Log\LoggerInterface $logger)
    {
        parent::initController($request, $response, $logger);

        $this->teacherModel = new TeacherModel();
        $this->periodModel  = new AcademicPeriodModel();
        $this->ticketModel  = new CounselingTicketModel();
        $this->messageModel = new CounselingMessageModel();
    }

    private function getTeacherOrRedirect()
    {
        if (!session()->get('logged_in') || session()->get('user_role') !== 'guru') {
            return redirect()->to('/login')->with('error', 'Akses ditolak.');
        }

        $userId = session()->get('user_id');
        $teacher = $this->teacherModel->where('user_id', $userId)->first();

        if (!$teacher) {
            return redirect()->to('/login')->with('error', 'Data guru tidak ditemukan.');
        }

        return $teacher;
    }

    public function index()
    {
        $teacher = $this->getTeacherOrRedirect();
        if ($teacher instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $teacher;
        }

        $activePeriod = $this->periodModel->getActive();
        $selectedPeriodId = $this->request->getGet('period_id') ?: ($activePeriod ? $activePeriod['id'] : null);
        $periods = $this->periodModel->getAllWithYear();

        // Filters
        $typeFilter   = $this->request->getGet('type');   // 'pengaduan' or 'konseling'
        $statusFilter = $this->request->getGet('status') ?: 'open'; // 'open' or 'closed'

        // Fetch tickets
        $query = $this->ticketModel
            ->select('counseling_tickets.*, students.full_name as student_real_name, students.nisn as student_nisn')
            ->join('students', 'students.id = counseling_tickets.student_id', 'left')
            ->where('assigned_teacher_id', $teacher['id']);

        if ($selectedPeriodId) {
            $query->where('academic_period_id', $selectedPeriodId);
        }
        if ($typeFilter) {
            $query->where('type', $typeFilter);
        }
        if ($statusFilter) {
            $query->where('counseling_tickets.status', $statusFilter);
        }

        $tickets = $query->orderBy('counseling_tickets.updated_at', 'DESC')->findAll();

        return view('guru/counseling/index', [
            'title'            => 'E-Konseling & Pengaduan Masuk',
            'teacher'          => $teacher,
            'tickets'          => $tickets,
            'periods'          => $periods,
            'selectedPeriodId' => $selectedPeriodId,
            'typeFilter'       => $typeFilter,
            'statusFilter'     => $statusFilter
        ]);
    }

    public function chat($id)
    {
        $teacher = $this->getTeacherOrRedirect();
        if ($teacher instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $teacher;
        }

        // Fetch ticket and check assignment
        $ticket = $this->ticketModel
            ->select('counseling_tickets.*, students.full_name as student_real_name, students.nisn as student_nisn, classrooms.name as classroom_name')
            ->join('students', 'students.id = counseling_tickets.student_id', 'left')
            ->join('student_academic_histories', 'student_academic_histories.student_id = students.id AND student_academic_histories.academic_period_id = counseling_tickets.academic_period_id', 'left')
            ->join('classrooms', 'classrooms.id = student_academic_histories.classroom_id', 'left')
            ->where('counseling_tickets.id', $id)
            ->first();

        if (!$ticket || (int)$ticket['assigned_teacher_id'] !== (int)$teacher['id']) {
            return redirect()->to('/guru/counseling')->with('error', 'Sesi tidak ditemukan atau Anda tidak memiliki akses.');
        }

        // Get messages
        $messages = $this->messageModel
            ->where('ticket_id', $id)
            ->orderBy('created_at', 'ASC')
            ->findAll();

        // Get list of all other teachers for referral dropdown
        $allTeachers = $this->teacherModel->where('id !=', $teacher['id'])->orderBy('name', 'ASC')->findAll();

        return view('guru/counseling/chat', [
            'title'       => 'Sesi Bimbingan & Konseling',
            'teacher'     => $teacher,
            'ticket'      => $ticket,
            'messages'    => $messages,
            'allTeachers' => $allTeachers
        ]);
    }

    public function sendMessage($id)
    {
        $teacher = $this->getTeacherOrRedirect();
        if ($teacher instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $teacher;
        }

        $ticket = $this->ticketModel->find($id);
        if (!$ticket || (int)$ticket['assigned_teacher_id'] !== (int)$teacher['id']) {
            return $this->response->setJSON(['success' => false, 'message' => 'Sesi tidak ditemukan.']);
        }

        if ($ticket['status'] === 'closed') {
            return redirect()->back()->with('error', 'Sesi bimbingan ini telah ditutup.');
        }

        $messageText = $this->request->getPost('message');
        if (empty(trim($messageText))) {
            return redirect()->back()->with('error', 'Pesan tidak boleh kosong.');
        }

        // Send reply
        $this->messageModel->insert([
            'ticket_id'   => $id,
            'sender_id'   => session()->get('user_id'),
            'sender_role' => 'teacher',
            'message'     => trim($messageText),
            'created_at'  => date('Y-m-d H:i:s')
        ]);

        // Touch ticket updated_at
        $this->ticketModel->update($id, [
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        return redirect()->back();
    }

    public function closeTicket($id)
    {
        $teacher = $this->getTeacherOrRedirect();
        if ($teacher instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $teacher;
        }

        $ticket = $this->ticketModel->find($id);
        if (!$ticket || (int)$ticket['assigned_teacher_id'] !== (int)$teacher['id']) {
            return redirect()->back()->with('error', 'Akses ditolak.');
        }

        // Update status to closed
        $this->ticketModel->update($id, [
            'status'     => 'closed',
            'updated_at' => date('Y-m-d H:i:s')
        ]);

        // Append system notification message
        $this->messageModel->insert([
            'ticket_id'   => $id,
            'sender_id'   => session()->get('user_id'),
            'sender_role' => 'teacher',
            'message'     => '[Sistem] Sesi bimbingan/pengaduan ini telah ditandai SELESAI oleh Guru.',
            'created_at'  => date('Y-m-d H:i:s')
        ]);

        return redirect()->back()->with('success', 'Sesi bimbingan berhasil diselesaikan.');
    }

    public function saveNotes($id)
    {
        $teacher = $this->getTeacherOrRedirect();
        if ($teacher instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $teacher;
        }

        $ticket = $this->ticketModel->find($id);
        if (!$ticket || (int)$ticket['assigned_teacher_id'] !== (int)$teacher['id']) {
            return redirect()->back()->with('error', 'Akses ditolak.');
        }

        $notes = $this->request->getPost('internal_notes');
        $this->ticketModel->update($id, [
            'internal_notes' => $notes,
            'updated_at'     => date('Y-m-d H:i:s')
        ]);

        return redirect()->back()->with('success', 'Catatan perkembangan kasus berhasil disimpan.');
    }

    public function referTicket($id)
    {
        $teacher = $this->getTeacherOrRedirect();
        if ($teacher instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $teacher;
        }

        $ticket = $this->ticketModel->find($id);
        if (!$ticket || (int)$ticket['assigned_teacher_id'] !== (int)$teacher['id']) {
            return redirect()->back()->with('error', 'Akses ditolak.');
        }

        $newTeacherId = $this->request->getPost('new_teacher_id');
        $newTeacher = $this->teacherModel->find($newTeacherId);

        if (!$newTeacher) {
            return redirect()->back()->with('error', 'Guru penerima rujukan tidak valid.');
        }

        // Reassign
        $this->ticketModel->update($id, [
            'assigned_teacher_id' => $newTeacherId,
            'updated_at'          => date('Y-m-d H:i:s')
        ]);

        // Insert notification message about referral
        $this->messageModel->insert([
            'ticket_id'   => $id,
            'sender_id'   => session()->get('user_id'),
            'sender_role' => 'teacher',
            'message'     => sprintf('[Rujukan] Sesi bimbingan ini telah dirujuk/dialihkan kepada Guru: "%s" oleh Guru sebelumnya: "%s".', $newTeacher['name'], $teacher['name']),
            'created_at'  => date('Y-m-d H:i:s')
        ]);

        return redirect()->to('/guru/counseling')->with('success', 'Sesi bimbingan berhasil dialihkan ke ' . $newTeacher['name']);
    }

    public function exportRecap()
    {
        $teacher = $this->getTeacherOrRedirect();
        if ($teacher instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $teacher;
        }

        $selectedPeriodId = $this->request->getGet('period_id');
        $activePeriod = $this->periodModel->getActive();
        $period = null;
        if ($selectedPeriodId) {
            $period = $this->periodModel->select('academic_periods.*, academic_years.name as year_name')
                ->join('academic_years', 'academic_years.id = academic_periods.academic_year_id')
                ->find($selectedPeriodId);
        } else {
            $period = $activePeriod;
        }

        $typeFilter   = $this->request->getGet('type');
        $statusFilter = $this->request->getGet('status');

        $query = $this->ticketModel
            ->select('counseling_tickets.*, students.full_name as student_real_name, classrooms.name as classroom_name, teachers.name as teacher_name')
            ->join('students', 'students.id = counseling_tickets.student_id', 'left')
            ->join('student_academic_histories', 'student_academic_histories.student_id = students.id AND student_academic_histories.academic_period_id = counseling_tickets.academic_period_id', 'left')
            ->join('classrooms', 'classrooms.id = student_academic_histories.classroom_id', 'left')
            ->join('teachers', 'teachers.id = counseling_tickets.assigned_teacher_id')
            ->where('assigned_teacher_id', $teacher['id']);

        if ($period) {
            $query->where('counseling_tickets.academic_period_id', $period['id']);
        }
        if ($typeFilter) {
            $query->where('type', $typeFilter);
        }
        if ($statusFilter) {
            $query->where('counseling_tickets.status', $statusFilter);
        }

        $tickets = $query->orderBy('counseling_tickets.created_at', 'ASC')->findAll();

        $settingsModel = new \App\Models\SchoolSettingModel();
        $schoolSettings = $settingsModel->getSettings();

        return view('guru/counseling/export_recap', [
            'teacher'        => $teacher,
            'period'         => $period,
            'tickets'        => $tickets,
            'type'           => $typeFilter,
            'status'         => $statusFilter,
            'schoolSettings' => $schoolSettings
        ]);
    }

    public function getNewMessages($ticketId, $lastMessageId)
    {
        $teacher = $this->getTeacherOrRedirect();
        if ($teacher instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $this->response->setJSON(['success' => false, 'message' => 'Akses ditolak.']);
        }

        // Verify ticket assignment
        $ticket = $this->ticketModel->find($ticketId);
        if (!$ticket || (int)$ticket['assigned_teacher_id'] !== (int)$teacher['id']) {
            return $this->response->setJSON(['success' => false, 'message' => 'Akses ditolak.']);
        }

        // Fetch new messages
        $messages = $this->messageModel
            ->where('ticket_id', $ticketId)
            ->where('id >', $lastMessageId)
            ->orderBy('created_at', 'ASC')
            ->findAll();

        return $this->response->setJSON([
            'success' => true,
            'messages' => $messages,
            'status' => $ticket['status']
        ]);
    }
}
