<?php
class Chat extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();

        if (!$this->session->userdata('user_logged_in')) {
            redirect('user/login');
        }

        $this->load->model('Chat_model');
        $this->load->model('admin/Admin_model');
    }

    public function index()
    {
        $id_penghuni = $this->session->userdata('user_id');

        // Get admin from kos penghuni
        $penghuni = $this->db->get_where('penghuni', ['id_penghuni' => $id_penghuni])->row();

        if (!$penghuni || !$penghuni->id_kos) {
            show_error('Anda belum terdaftar di kos manapun.');
        }

        $kos = $this->db->get_where('kos', ['id_kos' => $penghuni->id_kos])->row();

        if (!$kos) {
            show_error('Kos tidak ditemukan.');
        }

        $id_admin = $kos->id_admin;

        // Check subscription
        $sub = $this->Chat_model->check_subscription($id_admin);

        if (!$sub) {
            $data['chat_disabled'] = true;
            $data['disabled_message'] = 'Admin belum mengaktifkan fitur chat.';
        } else {
            $data['chat_disabled'] = false;
            $data['messages'] = $this->Chat_model->get_messages($id_penghuni, $id_admin);
        }

        $data['id_admin'] = $id_admin;
        $data['title'] = "Chat Admin";

        // Get admin info
        $admin = $this->db->get_where('admin', ['id' => $id_admin])->row();

        // Pass WebSocket config
        $data['ws_config'] = [
            'userType' => 'penghuni',
            'userId' => $id_penghuni,
            'targetType' => 'admin',
            'targetId' => $id_admin,
            'userName' => $penghuni->nama_penghuni,
            'targetName' => $admin->nama ?? 'Admin'
        ];

        $this->load->view('user/chat/index', $data);
    }

    public function send()
    {
        // Tambahkan header JSON
        header('Content-Type: application/json');

        if (!$this->input->is_ajax_request()) {
            echo json_encode(['status' => 'error', 'message' => 'Invalid request']);
            return;
        }

        $id_penghuni = $this->session->userdata('user_id');
        $id_admin = $this->input->post('id_admin');
        $message = $this->input->post('message');

        // Check subscription admin
        $sub = $this->Chat_model->check_subscription($id_admin);
        if (!$sub) {
            echo json_encode(['status' => 'error', 'message' => 'Chat tidak tersedia']);
            return;
        }

        $result = $this->Chat_model->send_message([
            'id_penghuni' => $id_penghuni,
            'id_admin' => $id_admin,
            'message' => $message,
            'sender' => 'penghuni',
            'is_read' => 0,
            'is_read_admin' => 0,
            'is_read_penghuni' => 1
        ]);

        if ($result) {
            echo json_encode(['status' => 'success', 'message_id' => $result]);
        } else {
            echo json_encode(['status' => 'error', 'message' => 'Gagal mengirim pesan']);
        }
        exit; // Penting untuk menghentikan eksekusi
    }
    public function get_unread_count()
    {
        if (!$this->input->is_ajax_request()) {
            show_404();
        }

        $id_penghuni = $this->session->userdata('user_id');
        $count = $this->Chat_model->get_unread_count_penghuni($id_penghuni);

        echo json_encode(['status' => 'success', 'count' => $count]);
    }
}
