<?php

namespace App\Models;

use App\Core\Model;

class Message extends Model
{
    protected string $table = 'private_messages';

    public function getConversation(int $userId1, int $userId2): array
    {
        $stmt = $this->db->prepare(
            "SELECT m.*, u.username, u.avatar FROM private_messages m
             JOIN users u ON u.id = m.sender_id
             WHERE (m.sender_id = ? AND m.receiver_id = ?)
                OR (m.sender_id = ? AND m.receiver_id = ?)
             ORDER BY m.created_at ASC"
        );
        $stmt->execute([$userId1, $userId2, $userId2, $userId1]);
        return $stmt->fetchAll();
    }

    public function getInbox(int $userId): array
    {
        $stmt = $this->db->prepare(
            "SELECT m.*, u.username, u.avatar FROM private_messages m
             JOIN (
                SELECT MAX(id) as max_id
                FROM private_messages
                WHERE sender_id = ? OR receiver_id = ?
                GROUP BY LEAST(sender_id, receiver_id), GREATEST(sender_id, receiver_id)
             ) latest ON m.id = latest.max_id
             JOIN users u ON u.id = CASE WHEN m.sender_id = ? THEN m.receiver_id ELSE m.sender_id END
             ORDER BY m.created_at DESC"
        );
        $stmt->execute([$userId, $userId, $userId]);
        return $stmt->fetchAll();
    }

    public function send(int $senderId, int $receiverId, string $message): int
    {
        $stmt = $this->db->prepare(
            "INSERT INTO private_messages (sender_id, receiver_id, message) VALUES (?, ?, ?)"
        );
        $stmt->execute([$senderId, $receiverId, $message]);
        return (int)$this->db->lastInsertId();
    }

    public function markRead(int $senderId, int $receiverId): void
    {
        $stmt = $this->db->prepare(
            "UPDATE private_messages SET is_read = 1 WHERE sender_id = ? AND receiver_id = ?"
        );
        $stmt->execute([$senderId, $receiverId]);
    }
    public function deleteConversation(int $userId, int $otherId): void
    {
        $stmt = $this->db->prepare(
            "DELETE FROM private_messages 
             WHERE (sender_id = ? AND receiver_id = ?) 
                OR (sender_id = ? AND receiver_id = ?)"
        );
        $stmt->execute([$userId, $otherId, $otherId, $userId]);
    }
}
