<?php

namespace App\Controllers\Siswa;

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

class Counseling extends BaseController
{
    protected $studentModel;
    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->studentModel = new StudentModel();
        $this->teacherModel = new TeacherModel();
        $this->periodModel  = new AcademicPeriodModel();
        $this->ticketModel  = new CounselingTicketModel();
        $this->messageModel = new CounselingMessageModel();

        // Password reset enforcement check (standard across Student Portal)
        $userId = session()->get('user_id');
        if (session()->get('user_role') === 'siswa' && $userId) {
            $userModel = new \App\Models\UserModel();
            $user = $userModel->find($userId);
            if ($user && (int)$user['is_password_reset'] === 1) {
                $response->redirect(site_url('siswa/change-password'))->send();
                exit;
            }
        }
    }

    private function getStudentOrRedirect()
    {
        $studentId = session()->get('student_id');
        if (!$studentId) {
            session()->destroy();
            return redirect()->to('/login')->with('error', 'Sesi siswa tidak valid.');
        }

        $student = $this->studentModel->find($studentId);
        if (!$student) {
            session()->destroy();
            return redirect()->to('/login')->with('error', 'Data siswa tidak ditemukan.');
        }

        return $student;
    }

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

        // Get tickets for this student
        $tickets = $this->ticketModel
            ->select('counseling_tickets.*, teachers.name as teacher_name')
            ->join('teachers', 'teachers.id = counseling_tickets.assigned_teacher_id')
            ->where('student_id', $student['id'])
            ->orderBy('counseling_tickets.updated_at', 'DESC')
            ->findAll();

        return view('siswa/counseling/index', [
            'title'   => 'Pengaduan & Konseling',
            'student' => $student,
            'tickets' => $tickets
        ]);
    }

    public function create()
    {
        $student = $this->getStudentOrRedirect();
        if ($student instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $student;
        }

        // Load all active teachers
        $teachers = $this->teacherModel->orderBy('name', 'ASC')->findAll();

        return view('siswa/counseling/create', [
            'title'    => 'Buat Pengaduan & Konseling Baru',
            'student'  => $student,
            'teachers' => $teachers
        ]);
    }

    public function store()
    {
        $student = $this->getStudentOrRedirect();
        if ($student instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $student;
        }

        $rules = [
            'assigned_teacher_id' => 'required',
            'subject'             => 'required|min_length[5]|max_length[255]',
            'category'            => 'required',
            'type'                => 'required',
            'message'             => 'required|min_length[5]'
        ];

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

        $teacherId   = $this->request->getPost('assigned_teacher_id');
        $subject     = $this->request->getPost('subject');
        $category    = $this->request->getPost('category');
        $type        = $this->request->getPost('type');
        $isAnonymous = $this->request->getPost('is_anonymous') ? 1 : 0;
        $messageText = $this->request->getPost('message');

        // Check active academic period
        $activePeriod = $this->periodModel->getActive();
        $periodId = $activePeriod ? $activePeriod['id'] : null;

        // Start Transaction
        $db = \Config\Database::connect();
        $db->transStart();

        // Create Ticket
        $ticketId = $this->ticketModel->insert([
            'student_id'            => $student['id'],
            'academic_period_id'    => $periodId,
            'student_name_fallback' => $student['full_name'],
            'assigned_teacher_id'   => $teacherId,
            'subject'               => $subject,
            'category'              => $category,
            'type'                  => $type,
            'status'                => 'open',
            'is_anonymous'          => $isAnonymous,
            'internal_notes'        => null
        ]);

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

        $db->transComplete();

        if ($db->transStatus() === false) {
            return redirect()->back()->withInput()->with('error', 'Gagal membuat sesi pengaduan.');
        }

        // Kirim Notifikasi WhatsApp ke Guru Pengampu
        try {
            $waService = new \App\Services\WhatsappService();
            if ($waService->isConfigured()) {
                $teacher = $this->teacherModel->find($teacherId);
                if ($teacher && !empty($teacher['phone'])) {
                    $typeName = ($type === 'counseling') ? 'Bimbingan Konseling' : 'Pengaduan';
                    $catName  = ucfirst($category);
                    $appUrl   = base_url('/login');

                    $msg  = "Assalamu'alaikum Wr. Wb. Bpk/Ibu *{$teacher['name']}* 🙏\n\n";
                    $msg .= "Ada sesi e-Konseling/Pengaduan baru yang ditujukan kepada Anda.\n";
                    $msg .= "• Kategori: {$catName}\n";
                    $msg .= "• Tipe: {$typeName}\n";
                    $msg .= "• Subjek: {$subject}\n\n";
                    $msg .= "Silakan masuk ke aplikasi SIMAK untuk meninjau dan merespon:\n";
                    $msg .= "{$appUrl}\n\n";
                    $msg .= "Terima kasih.";

                    $waService->send($teacher['phone'], $msg);
                }
            }
        } catch (\Exception $e) {
            // Ignore
        }

        return redirect()->to('/siswa/counseling/chat/' . $ticketId)->with('success', 'Sesi bimbingan berhasil dibuat.');
    }

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

        // Get ticket details and verify ownership
        $ticket = $this->ticketModel
            ->select('counseling_tickets.*, teachers.name as teacher_name')
            ->join('teachers', 'teachers.id = counseling_tickets.assigned_teacher_id')
            ->where('counseling_tickets.id', $id)
            ->first();

        if (!$ticket || (int)$ticket['student_id'] !== (int)$student['id']) {
            return redirect()->to('/siswa/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();

        return view('siswa/counseling/chat', [
            'title'    => 'Obrolan Bimbingan',
            'student'  => $student,
            'ticket'   => $ticket,
            'messages' => $messages
        ]);
    }

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

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

        if ($ticket['status'] === 'closed') {
            return $this->response->setJSON(['success' => false, 'message' => 'Sesi bimbingan ini telah diselesaikan oleh Guru.']);
        }

        $messageText = $this->request->getPost('message');
        if (empty(trim($messageText))) {
            return $this->response->setJSON(['success' => false, 'message' => 'Pesan tidak boleh kosong.']);
        }

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

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

        // Kirim Notifikasi WhatsApp ke Guru Pengampu
        try {
            $waService = new \App\Services\WhatsappService();
            if ($waService->isConfigured()) {
                $teacher = $this->teacherModel->find($ticket['assigned_teacher_id']);
                if ($teacher && !empty($teacher['phone'])) {
                    $appUrl = base_url('/login');

                    $msg  = "Assalamu'alaikum Wr. Wb. Bpk/Ibu *{$teacher['name']}* 🙏\n\n";
                    $msg .= "Ada pesan chat baru masuk pada sesi e-Konseling Anda di SIMAK.\n\n";
                    $msg .= "Silakan masuk ke aplikasi SIMAK untuk membalas pesan siswa:\n";
                    $msg .= "{$appUrl}\n\n";
                    $msg .= "Terima kasih.";

                    $waService->send($teacher['phone'], $msg);
                }
            }
        } catch (\Exception $e) {
            // Ignore
        }

        return redirect()->back();
    }

    public function getNewMessages($ticketId, $lastMessageId)
    {
        $student = $this->getStudentOrRedirect();
        if ($student instanceof \CodeIgniter\HTTP\RedirectResponse) {
            return $this->response->setJSON(['success' => false, 'message' => 'Sesi tidak valid.']);
        }

        // Verify ticket ownership
        $ticket = $this->ticketModel->find($ticketId);
        if (!$ticket || (int)$ticket['student_id'] !== (int)$student['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']
        ]);
    }
}
