<?php
/**
 * Model Message
 * mySupport - Plateforme de Service Client Intelligent
 */

namespace App\Models;

use Core\Model;

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

    public function getByConversation(int $conversationId): array
    {
        $sql = "SELECT m.*, 
                       CASE WHEN m.sender_type = 'agent' THEN u.nom ELSE NULL END as sender_name
                FROM {$this->table} m
                LEFT JOIN users u ON m.sender_id = u.id AND m.sender_type = 'agent'
                WHERE m.conversation_id = :conversation_id
                ORDER BY m.created_at ASC";
        
        return $this->db->fetchAll($sql, ['conversation_id' => $conversationId]);
    }

    public function addMessage(int $conversationId, string $senderType, ?int $senderId, string $contenu, array $options = []): int
    {
        $data = [
            'conversation_id' => $conversationId,
            'sender_type' => $senderType,
            'sender_id' => $senderId,
            'contenu' => $contenu,
            'type_message' => $options['type_message'] ?? 'text',
            'langue' => $options['langue'] ?? 'fr',
            'contenu_original' => $options['contenu_original'] ?? null,
            'fichier_url' => $options['fichier_url'] ?? null,
            'metadata' => isset($options['metadata']) ? json_encode($options['metadata']) : null
        ];
        
        $messageId = $this->create($data);
        
        $this->db->query(
            "UPDATE conversations SET updated_at = NOW() WHERE id = :id",
            ['id' => $conversationId]
        );
        
        return $messageId;
    }

    public function markAsRead(int $conversationId, string $readerType): int
    {
        $senderType = $readerType === 'agent' ? 'client' : 'agent';
        
        $sql = "UPDATE {$this->table} 
                SET is_read = TRUE 
                WHERE conversation_id = :conversation_id 
                AND sender_type = :sender_type 
                AND is_read = FALSE";
        
        return $this->db->query($sql, [
            'conversation_id' => $conversationId,
            'sender_type' => $senderType
        ])->rowCount();
    }

    public function getUnreadCount(int $conversationId, string $forType): int
    {
        $senderType = $forType === 'agent' ? 'client' : 'agent';
        
        $sql = "SELECT COUNT(*) as count 
                FROM {$this->table} 
                WHERE conversation_id = :conversation_id 
                AND sender_type = :sender_type 
                AND is_read = FALSE";
        
        $result = $this->db->fetch($sql, [
            'conversation_id' => $conversationId,
            'sender_type' => $senderType
        ]);
        
        return (int) ($result['count'] ?? 0);
    }

    public function getLastMessage(int $conversationId): ?array
    {
        $sql = "SELECT * FROM {$this->table} 
                WHERE conversation_id = :conversation_id 
                ORDER BY created_at DESC 
                LIMIT 1";
        
        return $this->db->fetch($sql, ['conversation_id' => $conversationId]);
    }
}
