<?php

namespace App\Models;

use CodeIgniter\Model;

class MessageModel extends Model
{
    protected $table = 'messages';
    protected $primaryKey = 'id';
    protected $allowedFields = ['thread_id', 'sender_id', 'message', 'status', 'created_at'];

    public function getMessagesByThread($threadId)
    {
        return $this->where('thread_id', $threadId)
            ->orderBy('created_at', 'ASC')
            ->findAll();
    }

    public function get_messages_count_from_sellers($userId){
        return $this->join('threads', 'threads.id = messages.thread_id')
            ->join('users', 'users.id = messages.sender_id')
            ->where('messages.status', 'unread')
            ->where('messages.sender_id !=', $userId)
            ->where('users.seller', 1)
            ->where('(threads.sender_id = ' . $userId . ' OR threads.receiver_id = ' . $userId . ')')
            ->countAllResults();
    }

    public function get_messages_count_from_buyers($userId) {
        return $this->join('threads', 'threads.id = messages.thread_id')
        ->join('users', 'users.id = messages.sender_id')
        ->where('messages.status', 'unread')
        ->where('messages.sender_id !=', $userId)
        ->where('users.buyer', 1)
        ->where('(threads.sender_id = ' . $userId . ' OR threads.receiver_id = ' . $userId . ')')
        ->countAllResults();
    }
    public function markAllAsRead($threadId, $userId)
    {
        return $this->where('thread_id', $threadId)
            ->where('sender_id !=', $userId) // Mark messages sent by others as read
            ->set(['status' => 'read'])
            ->update();
    }
}
