<?php

namespace App\Models;

use CodeIgniter\Model;

class MessageModel extends Model
{
    protected $table         = 'messages';
    protected $useTimestamps = false;
    protected $allowedFields = ['conversation_id', 'sender_id', 'body', 'is_read', 'read_at', 'created_at'];

    public function forConversation(int $conversationId, int $page = 1, int $perPage = 30): array
    {
        $offset = ($page - 1) * $perPage;
        return $this->where('conversation_id', $conversationId)->orderBy('created_at', 'DESC')->findAll($perPage, $offset);
    }

    public function markConversationRead(int $conversationId, int $readerUserId): void
    {
        $this->where('conversation_id', $conversationId)
            ->where('sender_id !=', $readerUserId)
            ->where('is_read', 0)
            ->set(['is_read' => 1, 'read_at' => date('Y-m-d H:i:s')])
            ->update();
    }

    public function unreadCountFor(int $userId): int
    {
        return \Config\Database::connect()->table('messages m')
            ->join('conversation_participants cp', 'cp.conversation_id = m.conversation_id')
            ->where('cp.user_id', $userId)
            ->where('m.sender_id !=', $userId)
            ->where('m.is_read', 0)
            ->countAllResults();
    }
}
