<?php
require_once('db_connection.php');

class Message {
    private $db;

    function __construct($dbconn) {
        $this->db = $dbconn;
    }

    // Function to create a new message
    public function createMessage($sender, $receiver, $message) {
        $query = "INSERT INTO `messages` (`id`, `sender_id`, `receiver_id`, `message`, `sendtime`) VALUES (NULL, '$sender', '$receiver', '$message', current_timestamp())";
        $result = mysqli_query($this->db, $query);
       
        if ($result){
            return true; // Message created successfully
        } else {
            return false; // Failed to create message
        }
    }

    // Function to update a message by its ID
    public function updateMessage($id, $message) {
        $query = "UPDATE messages SET message = ? WHERE id = ?";
        $stmt = mysqli_prepare($this->db, $query);
        mysqli_stmt_bind_param($stmt, "si", $message, $id);

        return mysqli_stmt_execute($stmt);
    }

    // Function to delete a message by its ID
    public function deleteMessage($id) {
        $query = "DELETE FROM messages WHERE id = ?";
        $stmt = mysqli_prepare($this->db, $query);
        mysqli_stmt_bind_param($stmt, "i", $id);

        return mysqli_stmt_execute($stmt);
    }

    // Function to get all messages
    public function getAllMessages() {
        $query = "SELECT * FROM messages";
        $result = mysqli_query($this->db, $query);

        return mysqli_fetch_all($result, MYSQLI_ASSOC); // Fetch all messages as associative array
    }
      // Function to get all messages
    public function getAllReceivedMessages($receiver) {
        $query = "SELECT * FROM messages JOIN users ON users.id = messages.sender_id  WHERE receiver_id ='$receiver' ORDER BY sendtime DESC";
        $result = mysqli_query($this->db, $query);

        return mysqli_fetch_all($result, MYSQLI_ASSOC); // Fetch all messages as associative array
    }
    public function getAllSentMessages($sender) {
        $query = "SELECT * FROM messages JOIN users ON users.id = messages.receiver_id  WHERE sender_id ='$sender' ORDER BY sendtime DESC";
        $result = mysqli_query($this->db, $query);

        return mysqli_fetch_all($result, MYSQLI_ASSOC); // Fetch all messages as associative array
    }

    // Function to get a message by ID
    public function getMessageById($id) {
        $query = "SELECT * FROM messages WHERE id = ?";
        $stmt = mysqli_prepare($this->db, $query);
        mysqli_stmt_bind_param($stmt, "i", $id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);

        return mysqli_fetch_assoc($result); // Fetch single message as associative array
    }
}
