<?php
/**
 * ============================================================================
 * classes/Message.php - Message Management Class
 * ============================================================================
 */

namespace App;

use PDO;
use PDOException;

class Message {
    private $db;
    private $table = 'messages';
    
    public function __construct($db) {
        $this->db = $db;
    }
    
    /**
     * Send message
     */
    public function send($chatId, $senderId, $content, $messageType = 'text', $mediaUrl = null) {
        try {
            $sql = "INSERT INTO {$this->table} 
                    (chat_id, sender_id, message_type, content, media_url)
                    VALUES (?, ?, ?, ?, ?)";
            
            $stmt = $this->db->prepare($sql);
            $result = $stmt->execute([$chatId, $senderId, $messageType, $content, $mediaUrl]);
            
            if ($result) {
                $messageId = $this->db->lastInsertId();
                
                // Update chat timestamp
                $sql = "UPDATE chats SET updated_at = CURRENT_TIMESTAMP WHERE id = ?";
                $stmt = $this->db->prepare($sql);
                $stmt->execute([$chatId]);
                
                return [
                    'success' => true,
                    'message' => 'Message sent',
                    'message_id' => $messageId
                ];
            }
            
            return ['success' => false, 'message' => 'Failed to send message'];
            
        } catch (PDOException $e) {
            error_log("Message send error: " . $e->getMessage());
            return ['success' => false, 'message' => 'Database error occurred'];
        }
    }
    
    /**
     * Get chat messages
     */
    public function getChatMessages($chatId, $limit = 50, $beforeId = null) {
        $sql = "SELECT m.*, u.full_name as sender_name, u.profile_picture as sender_avatar
                FROM {$this->table} m
                JOIN users u ON m.sender_id = u.id
                WHERE m.chat_id = ?";
        
        $params = [$chatId];
        
        if ($beforeId) {
            $sql .= " AND m.id < ?";
            $params[] = $beforeId;
        }
        
        $sql .= " ORDER BY m.created_at DESC LIMIT ?";
        $params[] = $limit;
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute($params);
        $messages = $stmt->fetchAll(PDO::FETCH_ASSOC);
        
        return array_reverse($messages);
    }
    
    /**
     * Get latest messages
     */
    public function getLatestMessages($chatId, $afterId = 0) {
        $sql = "SELECT m.*, u.full_name as sender_name, u.profile_picture as sender_avatar
                FROM {$this->table} m
                JOIN users u ON m.sender_id = u.id
                WHERE m.chat_id = ? AND m.id > ?
                ORDER BY m.created_at ASC";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$chatId, $afterId]);
        return $stmt->fetchAll(PDO::FETCH_ASSOC);
    }
    
    /**
     * Delete message
     */
    public function delete($messageId, $userId) {
        // Check if user is the sender
        $sql = "SELECT sender_id FROM {$this->table} WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$messageId]);
        $message = $stmt->fetch(PDO::FETCH_ASSOC);
        
        if (!$message || $message['sender_id'] != $userId) {
            return ['success' => false, 'message' => 'Unauthorized'];
        }
        
        $sql = "DELETE FROM {$this->table} WHERE id = ?";
        $stmt = $this->db->prepare($sql);
        
        if ($stmt->execute([$messageId])) {
            return ['success' => true, 'message' => 'Message deleted'];
        }
        
        return ['success' => false, 'message' => 'Failed to delete message'];
    }
    
    /**
     * Get unread message count for user
     */
    public function getUnreadCount($userId) {
        $sql = "SELECT COUNT(*) as unread_count
                FROM {$this->table} m
                JOIN chat_members cm ON m.chat_id = cm.chat_id
                WHERE cm.user_id = ?
                AND m.sender_id != ?
                AND m.created_at > COALESCE(cm.last_read_at, '1970-01-01')";
        
        $stmt = $this->db->prepare($sql);
        $stmt->execute([$userId, $userId]);
        $result = $stmt->fetch(PDO::FETCH_ASSOC);
        
        return $result['unread_count'] ?? 0;
    }
}
?>
