<?php

namespace App\Models;

use App\Core\Model;

class Message extends Model
{
    protected $table = 'messages';
    protected $primaryKey = 'id';

    public function getInbox($userId, $limit = 20)
    {
        $stmt = $this->db->prepare("SELECT m.*, mr.is_read, mr.read_at, u.name as sender_name FROM {$this->table} m JOIN message_recipients mr ON m.id = mr.message_id LEFT JOIN users u ON m.sender_id = u.id WHERE mr.recipient_id = ? AND mr.is_archived = 0 ORDER BY m.created_at DESC LIMIT ?");
        $stmt->execute([$userId, $limit]);
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function getSent($userId, $limit = 20)
    {
        $stmt = $this->db->prepare("SELECT m.*, (SELECT COUNT(*) FROM message_recipients WHERE message_id = m.id) as recipient_count FROM {$this->table} m WHERE m.sender_id = ? ORDER BY m.created_at DESC LIMIT ?");
        $stmt->execute([$userId, $limit]);
        return $stmt->fetchAll(\PDO::FETCH_OBJ);
    }

    public function getUnreadCount($userId)
    {
        $stmt = $this->db->prepare("SELECT COUNT(*) as count FROM message_recipients WHERE recipient_id = ? AND is_read = 0 AND is_archived = 0");
        $stmt->execute([$userId]);
        return $stmt->fetch(\PDO::FETCH_OBJ)->count;
    }
}
