from django import template
from datetime import datetime, timedelta

register = template.Library()

@register.filter
def div(value, divisor):
    """Division de deux nombres."""
    try:
        return float(value) / float(divisor)
    except (ValueError, ZeroDivisionError, TypeError):
        return 0

@register.filter
def mul(value, multiplicator):
    """Multiplication de deux nombres."""
    try:
        return float(value) * float(multiplicator)
    except (ValueError, TypeError):
        return 0

@register.filter
def add_days(value, days):
    """Ajoute un nombre de jours à une date."""
    try:
        if isinstance(value, datetime):
            return value + timedelta(days=int(days))
        return value
    except (ValueError, TypeError):
        return value

@register.filter
def floatformat_zero_if_none(value, decimal_places=0):
    """Formate un nombre flottant, retourne 0 si None."""
    try:
        if value is None:
            return "0"
        return format(float(value), f".{decimal_places}f")
    except (ValueError, TypeError):
        return "0"
