from django import template
from django.utils.safestring import mark_safe

register = template.Library()
from django.utils.safestring import mark_safe
from django.conf import settings
from django.template.defaulttags import register

@register.simple_tag
def text_section(key1, value1):
    file_extensions = ('.jpg', '.jpeg', '.png', '.gif', '.pdf', '.doc', '.docx', '.zip', '.xlsx', '.txt')

    # بررسی مقدار و تبدیل به رشته‌ی مسیر فایل
    file_url = None
    if value1 and value1 != "-":
        if hasattr(value1, 'url'):  # بررسی آیا مقدار `ImageFieldFile` است و URL دارد
            file_url = value1.url  # مقدار نهایی برای دانلود
        elif isinstance(value1, str):  # اگر مقدار مستقیماً رشته باشد
            file_url = f"{settings.MEDIA_URL}{value1}"

    if file_url and file_url.lower().endswith(file_extensions):
        html = f"""
            <div class="col-md-3 col-sm-6 col-12 mb-3">
                <div class="p-3">
                    <label class="col-form-label text-right">{key1}</label>
                    <a class="btn btn-primary w-100" href="{file_url}" download>دانلود فایل</a>
                </div>
            </div>
        """
    else:
        html = f"""
            <div class="col-md-3 col-sm-6 col-12 mb-3">
                <div class="p-3">
                    <label class="col-form-label text-right">{key1}</label>
                    <input class="form-control form-control-lg form-control-solid" type="text"
                        name="{key1.lower().replace(' ', '_')}" value="{value1}" readonly>
                </div>
            </div>
        """

    return mark_safe(html)

@register.simple_tag
def editable_text_section(key1, value1, name=""):
    """
    A reusable template tag to generate an editable form field.
    - key1: Label text
    - value1: Initial value
    - name: Form field name
    """
    html = f"""
        <div class="col-md-3 col-sm-6 col-12 mb-3">
            <div class="p-3">
                <label class="col-form-label text-right">{key1}</label>
                <input class="form-control form-control-lg form-control-solid" type="text"
                    name="{name or key1.lower().replace(' ', '_')}" value="{value1}">
            </div>
        </div>
    """
    return mark_safe(html)
