saya memiliki kode untuk fitur chat ini controllernya
<?php

namespace App\Controllers\siswa;

use App\Models\siswa\ChatModel;
use CodeIgniter\Controller;
use App\Models\siswa\UserModel;

class Chat extends Controller
{
    protected $chatModel;
    protected $userModel;

    public function __construct()
    {
        $this->chatModel = new ChatModel();
        $this->userModel = new UserModel();
    }

    public function index()
    {
        $current_user = service('authentication')->user();
        $user_id = $current_user ? $current_user->id : 0;

        $users = $this->userModel->findAll();

        return view('mahasiswa/chat/index', [
            'user_id' => $user_id,
            'users' => $users
        ]);
    }

    public function sendMessage()
    {
        log_message('debug', 'Starting sendMessage method.');

        $rules = [
            'sender_id' => 'required|is_natural_no_zero',
            'receiver_id' => 'required|is_natural_no_zero',
            'message' => 'required|string'
        ];

        if (!$this->validate($rules)) {
            $errors = $this->validator->getErrors();
            log_message('error', 'Validation failed: ' . print_r($errors, true));
            return $this->response->setJSON(['status' => 'error', 'message' => 'Validation failed.'])->setStatusCode(400);
        }

        $sender_id = $this->request->getPost('sender_id');
        $receiver_id = $this->request->getPost('receiver_id');
        $message = $this->request->getPost('message');

        log_message('debug', 'Sender ID: ' . $sender_id);
        log_message('debug', 'Receiver ID: ' . $receiver_id);
        log_message('debug', 'Message: ' . $message);

        try {
            if ($this->chatModel->save([
                'sender_id' => $sender_id,
                'receiver_id' => $receiver_id,
                'message' => $message,
                'created_at' => date('Y-m-d H:i:s')
            ])) {
                log_message('debug', 'Message saved successfully.');
                return $this->response->setJSON(['status' => 'success']);
            } else {
                log_message('error', 'Failed to save message. Validation errors: ' . print_r($this->chatModel->errors(), true));
                return $this->response->setJSON(['status' => 'error', 'message' => 'Failed to save message.'])->setStatusCode(500);
            }
        } catch (\Exception $e) {
            log_message('critical', 'Exception occurred: ' . $e->getMessage());
            return $this->response->setJSON(['status' => 'error', 'message' => 'Exception occurred: ' . $e->getMessage()])->setStatusCode(500);
        }
    }

    public function fetchMessages($sender_id, $receiver_id)
    {
        $messages = $this->chatModel->where(['sender_id' => $sender_id, 'receiver_id' => $receiver_id])
                                    ->orWhere(['sender_id' => $receiver_id, 'receiver_id' => $sender_id])
                                    ->orderBy('created_at', 'ASC')
                                    ->findAll();

        return $this->response->setJSON($messages);
    }
}

ini viewnya
<?= $this->extend('mahasiswa/layout/main') ?>

<?= $this->section('content') ?>
    <div class="chat-page">
        <div class="user-list">
            <?php foreach ($users as $user): ?>
                <div class="user-item" data-user-id="<?= $user['id'] ?>" data-user-name="<?= $user['name'] ?>" data-user-photo="<?= base_url('/uploads/foto/' . $user['foto']) ?>">
                    <img src="<?= base_url('/uploads/foto/' . $user['foto']) ?>" alt="<?= $user['name'] ?>" class="user-photo">
                    <span class="user-name"><?= $user['name'] ?></span>
                </div>
            <?php endforeach; ?>
        </div>
        <div class="chat-container">
            <div id="chat-header" class="chat-header">
                <img id="chat-header-photo" src="" alt="User Photo" class="chat-header-photo">
                <span id="chat-header-name" class="chat-header-name">Select a user to chat</span>
            </div>
            <div id="chat-box" class="chat-box"></div>
            <form id="chat-form" class="chat-form">
                <?= csrf_field() ?>
                <input type="hidden" name="sender_id" value="<?= $user_id ?>">
                <input type="hidden" name="receiver_id" id="receiver_id">
                <input type="text" name="message" class="chat-input" placeholder="Type your message...">
                <button type="submit" class="chat-send-button">Send</button>
            </form>
        </div>
    </div>

    <style>
        .chat-page {
            display: flex;
        }
        
        .user-list {
            width: 200px;
            border-right: 1px solid #ccc;
            padding: 10px;
        }

        .user-item {
            display: flex;
            align-items: center;
            padding: 10px;
            cursor: pointer;
            border-bottom: 1px solid #ccc;
        }

        .user-item:hover {
            background-color: #f0f0f0;
        }

        .user-photo {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 10px;
        }

        .chat-container {
            flex-grow: 1;
            display: flex;
            flex-direction: column;
            max-width: 600px;
            margin: auto;
            padding: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #f9f9f9;
        }

        .chat-header {
            display: flex;
            align-items: center;
            padding: 10px;
            border-bottom: 1px solid #ccc;
            margin-bottom: 20px;
        }

        .chat-header-photo {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            margin-right: 10px;
        }

        .chat-header-name {
            font-size: 18px;
            font-weight: bold;
        }

        .chat-box {
            flex-grow: 1;
            margin-bottom: 20px;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            background-color: #fff;
            height: 400px;
            overflow-y: scroll;
        }

        .chat-form {
            display: flex;
        }

        .chat-input {
            flex-grow: 1;
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 5px;
            margin-right: 10px;
        }

        .chat-send-button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            background-color: #007bff;
            color: #fff;
            cursor: pointer;
        }

        .chat-send-button:hover {
            background-color: #0056b3;
        }
    </style>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            const base_url = '<?= base_url() ?>';
            const sender_id = $('input[name="sender_id"]').val();
            
            function fetchMessages(receiver_id) {
                $.get(`${base_url}siswa/chat/fetchMessages/${sender_id}/${receiver_id}`, function(data) {
                    let chatBox = $('#chat-box');
                    chatBox.html('');
                    data.forEach(message => {
                        chatBox.append(`<div class="chat-message"><strong>${message.sender_id == sender_id ? 'You' : 'Them'}:</strong> ${message.message}</div>`);
                    });
                    chatBox.scrollTop(chatBox[0].scrollHeight);
                }).fail(function() {
                    console.error('Error fetching messages');
                });
            }

            $('.user-item').on('click', function() {
                const receiver_id = $(this).data('user-id');
                const receiver_name = $(this).data('user-name');
                const receiver_photo = $(this).data('user-photo');

                $('#receiver_id').val(receiver_id);
                $('#chat-header-photo').attr('src', receiver_photo);
                $('#chat-header-name').text(receiver_name);

                fetchMessages(receiver_id);
            });

            $('#chat-form').on('submit', function(e) {
                e.preventDefault();
                const receiver_id = $('#receiver_id').val();
                $.post(`${base_url}siswa/chat/sendMessage`, $(this).serialize(), function(response) {
                    if (response.status === 'success') {
                        fetchMessages(receiver_id);
                        $('input[name="message"]').val(''); // Clear message input
                    } else {
                        console.error('Error sending message');
                    }
                }, 'json');
            });
        });
    </script>
<?= $this->endSection() ?>