<?php

namespace App\Models;

use CodeIgniter\Model;

class ThreadModel extends Model
{
    protected $table = 'threads';
    protected $primaryKey = 'id';
    protected $allowedFields = ['sender_id', 'receiver_id', 'created_at'];

    
    public function getThread($user1, $user2)
    {
        return $this->where('sender_id', $user1)
            ->where('receiver_id', $user2)
            ->orWhere('sender_id', $user2)
            ->where('receiver_id', $user1)
            ->first();
    }


    public function getOtherUserId(int $threadId, int $currentUserId): ?int
    {
        
        $thread = $this->find($threadId);
        if ($thread) {
            return $thread['sender_id'] == $currentUserId ? $thread['receiver_id'] : $thread['sender_id'];
        }
        return null;


    }

    public function isParticipant(int $threadId, int $userId): bool
    {
        $thread = $this->find($threadId);
        if ($thread) {
            return $thread['sender_id'] == $userId || $thread['receiver_id'] == $userId;
        }
        return false;
    }
}
