<?php
class Message extends Database {
    
    // 1. ZiyaretÃ§i MesajÄ±nÄ± Kaydet
    public function addMessage($data) {
        $this->query("INSERT INTO messages (property_id, sender_name, sender_email, sender_phone, message_content) VALUES (:property_id, :sender_name, :sender_email, :sender_phone, :message_content)");
        
        $this->bind(':property_id', $data['property_id']);
        $this->bind(':sender_name', $data['sender_name']);
        $this->bind(':sender_email', $data['sender_email']);
        $this->bind(':sender_phone', $data['sender_phone']);
        $this->bind(':message_content', $data['message_content']);
        
        return $this->execute();
    }

    // 2. Admin Ä°Ã§in: MesajlarÄ± Ä°lan Bilgisiyle Getir (JOIN Ä°ÅŸlemi)
    public function getAllMessagesWithProperty() {
        // messages tablosunu properties tablosu ile birleÅŸtiriyoruz
        $this->query("
            SELECT messages.*, 
                   properties.title as property_title, 
                   properties.image as property_image,
                   properties.id as real_property_id
            FROM messages 
            JOIN properties ON messages.property_id = properties.id 
            ORDER BY messages.created_at DESC
        ");
        return $this->resultSet();
    }

    // 3. OkunmadÄ± SayÄ±sÄ±nÄ± Getir (Sidebar rozeti iÃ§in)
    public function getUnreadCount() {
        $this->query("SELECT COUNT(*) as count FROM messages WHERE is_read = 0");
        $row = $this->single();
        return $row->count;
    }
    // Sadece belirli bir danÄ±ÅŸmana (user_id) ait mesajlarÄ± getir
    public function getMessagesByUserId($user_id) {
        $this->query("
            SELECT messages.*, 
                   properties.title as property_title, 
                   properties.image as property_image,
                   properties.id as real_property_id
            FROM messages 
            JOIN properties ON messages.property_id = properties.id 
            WHERE properties.user_id = :user_id  -- KRÄ°TÄ°K NOKTA BURASI
            ORDER BY messages.created_at DESC
        ");
        $this->bind(':user_id', $user_id);
        return $this->resultSet();
    }
    
    // DanÄ±ÅŸman iÃ§in okunmamÄ±ÅŸ mesaj sayÄ±sÄ±
    public function getUnreadCountByUser($user_id) {
        $this->query("
            SELECT COUNT(*) as count 
            FROM messages 
            JOIN properties ON messages.property_id = properties.id
            WHERE messages.is_read = 0 AND properties.user_id = :user_id
        ");
        $this->bind(':user_id', $user_id);
        $row = $this->single();
        return $row->count;
    }
    // Mesaj etiketi ve notu güncelle
    public function updateTagNote($id, $tag, $note) {
        $this->query("UPDATE messages SET tag = :tag, note = :note, is_read = 1 WHERE id = :id");
        $this->bind(':id', $id);
        $this->bind(':tag', $tag);
        $this->bind(':note', $note);
        return $this->execute();
    }
}
