<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Chat_model extends CI_Model {

    public function get_messages() {
        // Ambil data pesan beserta data pengguna yang relevan melalui JOIN
        $this->db->select('chat.message, chat.created_at, pengguna.pengguna_nama as username, pengguna.pengguna_sampul as sampul, pengguna.pengguna_status as status');
        $this->db->from('chat');
        $this->db->join('pengguna', 'pengguna.pengguna_id = chat.user_id');
        $this->db->order_by('chat.created_at', 'ASC');
        return $this->db->get()->result_array();
    }

    public function insert_message($user_id, $message) {
        $data = [
            'user_id' => $user_id,
            'message' => $message
        ];
        if($this->db->insert('chat', $data)) {
            return true;
        } else {
            // Catat error database ke log
            log_message('error', 'DB Error: ' . $this->db->error()['message']);
            return false;
        }
    }
}