<?php
namespace App\Models;

use App\Core\Model;
use PDO;

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

    public static function getByConversation(int $conversationId, int $limit = 100): array {
        $stmt = self::db()->prepare("
            SELECT m.*, u.name as user_name 
            FROM messages m
            LEFT JOIN users u ON m.user_id = u.id
            WHERE m.conversation_id = ?
            ORDER BY m.created_at ASC
            LIMIT ?
        ");
        $stmt->bindValue(1, $conversationId, PDO::PARAM_INT);
        $stmt->bindValue(2, $limit, PDO::PARAM_INT);
        $stmt->execute();
        return $stmt->fetchAll();
    }

    public static function updateStatusByMetaId(string $metaId, string $status): bool {
        $stmt = self::db()->prepare("UPDATE messages SET status = ? WHERE meta_message_id = ?");
        return $stmt->execute([$status, $metaId]);
    }

    public static function getMetrics(): array {
        $totalSent = self::count("direction = 'outbound'");
        $totalReceived = self::count("direction = 'inbound'");

        $today = date('Y-m-d 00:00:00');
        $todaySent = self::count("direction = 'outbound' AND created_at >= ?", [$today]);
        $todayReceived = self::count("direction = 'inbound' AND created_at >= ?", [$today]);

        return [
            'total_sent'      => $totalSent,
            'total_received'  => $totalReceived,
            'today_sent'      => $todaySent,
            'today_received'  => $todayReceived,
            'total_all'       => $totalSent + $totalReceived
        ];
    }
}
