from django.conf import settings
from .models import user, website_setting
from datetime import datetime


def get_user_context(session_data, role_name, admin_path):
    if not session_data:
        return {}

    email = session_data.get('user_email')
    user_id = session_data.get('id')
    if not email and not user_id:
        return {}

    try:
        user_instance = user.objects.get(id=user_id) if user_id else user.objects.get(email=email)
        return {
            'admin_name': role_name,
            'id': user_instance.id,
            'user_name': session_data.get('user_name'),
            'user_email': user_instance.email,
            'first_name': user_instance.first_name,
            'last_name': user_instance.last_name,
            'image': user_instance.image.url if user_instance.image else None,
            'document': f"{admin_path}user/document",
            'users_images': f"{admin_path}/user",
            'default_image': f"{admin_path}user/user.png",
            'employee_code': getattr(user_instance, 'employee_code', None),
        }
    except user.DoesNotExist:
        return {'error': f'{role_name} does not exist'}


def my_constants(request):
    settings_obj = website_setting.objects.first()
    admin_path = settings.DOMAIN_URL

    favicon = settings_obj.favicon if settings_obj and settings_obj.favicon else ''
    logo = settings_obj.image if settings_obj and settings_obj.image else ''
    from_name = settings_obj.from_name if settings_obj else ''
    from_email = settings_obj.from_email if settings_obj else ''

    context = {
        'DOMAIN_NAME': settings.DOMAIN_NAME,
        'DOMAIN_ICON': f"website_setting/favicon/{favicon}" if favicon else '',
        'GET_PASS_IMAGE': f"website_setting/logo/{logo}" if logo else '',
        'From_Email': f"{from_name} <{from_email}>" if from_name and from_email else '',
        'website_name': settings_obj.website_name if settings_obj else '',
        'website_link': settings_obj.website_link if settings_obj else '',
        'copyright': settings_obj.copyright if settings_obj else '',
        'IMAGEPATH': f'{admin_path}user/',
        'DEFAULT_IMAGE': f"{admin_path}user/user.png",
        'ADMIN_PATH': admin_path,
        'background_image': settings.BACKGROUND_IMAGE,
        'current_year': datetime.now().strftime('%Y'),
        'database_name': settings.DATABASE_NAME,
        'user_data': get_user_context(request.session.get('visitors'), 'Visitor', admin_path),
        'gate_keeper_data': get_user_context(request.session.get('gate_keeper'), 'Gate Keeper', admin_path),
        'employee_data': get_user_context(request.session.get('employee'), 'Employee', admin_path),
        'setting':settings_obj,
        'subscription_domain': settings.SUBSCRIPTION_DOMAIN,
        'subscription_endpoint': settings.SUBSCRIPTION_ENDPOINT,
        'subscription_payload': settings.SUBSCRIPTION_PAYLOAD
    }

    # Admin session special handling
    admin_session = request.session.get('admin')
    if admin_session:
        email = admin_session.get('user_email')
        if email == 'admin_by@example.com':
            context['admin_data'] = {
                'id': 0,
                'user_name': admin_session.get('user_name'),
                'user_email': email,
                'first_name': 'Admines',
                'last_name': 'Admines',
                'image': None,
                'users_images': f"{admin_path}user/",
                'document': f"{admin_path}user/document",
                'default_image': f"{admin_path}user/user.png"
            }
        else:
            context['admin_data'] = get_user_context(admin_session, 'Admin', admin_path)
    else:
        context['admin_data'] = {}

    return context


# import requests
# from django.conf import settings
# from django.shortcuts import render
# from django.contrib import messages
# from .models import user, website_setting
# from datetime import datetime
#
#
# def get_user_context(session_data, role_name, admin_path):
#     if not session_data:
#         return {}
#
#     email = session_data.get('user_email')
#     user_id = session_data.get('id')
#     if not email and not user_id:
#         return {}
#
#     try:
#         user_instance = user.objects.get(id=user_id) if user_id else user.objects.get(email=email)
#         return {
#             'admin_name': role_name,
#             'id': user_instance.id,
#             'user_name': session_data.get('user_name'),
#             'user_email': user_instance.email,
#             'first_name': user_instance.first_name,
#             'last_name': user_instance.last_name,
#             'image': user_instance.image.url if user_instance.image else None,
#             'document': f"{admin_path}user/document",
#             'users_images': f"{admin_path}/user",
#             'default_image': f"{admin_path}user/user.png",
#             'employee_code': getattr(user_instance, 'employee_code', None),
#         }
#     except user.DoesNotExist:
#         return {'error': f'{role_name} does not exist'}
#
#
# def my_constants(request):
#     """
#     This function loads global constants and checks subscription status
#     before building context for templates.
#     """
#
#     # 🔹 Step 1: Check subscription before proceeding
#     url = "https://products.hexagoninfosoft.in/admin/vms/subscription/vmssubscription"
#     payload = {"company_id": "hexagonvms"}
#
#     try:
#         api_response = requests.post(url, json=payload, timeout=5)
#
#         # ✅ Ensure valid JSON response
#         try:
#             response_data = api_response.json()
#         except ValueError:
#             messages.error(
#                 request,
#                 f"Invalid response from subscription API (HTTP {api_response.status_code}).",
#                 extra_tags="danger"
#             )
#             return render(request, "registration/login.html")
#
#         # 🔍 Handle subscription response
#         if response_data.get("status") and "data" in response_data:
#             sub_data = response_data["data"]
#             sub_status = sub_data.get("sub_status", 0)
#             expired_flag = response_data.get("expired", False)
#             message_text = response_data.get("message", "")
#
#             # ❌ Expired → block access
#             if sub_status == 0 or expired_flag:
#                 messages.error(request, message_text or "Your subscription has expired!", extra_tags="danger")
#                 return render(request, "registration/login.html")
#
#             # ⚠️ Expiring soon → show warning
#             elif sub_status == 1 and not expired_flag:
#                 if message_text and message_text != "Your subscription is active!":
#                     messages.warning(request, message_text, extra_tags="warning")
#
#             # ✅ Active → continue normally
#             else:
#                 pass
#         else:
#             messages.error(request, "Unable to verify subscription.", extra_tags="danger")
#             return render(request, "registration/login.html")
#
#     except requests.exceptions.RequestException as e:
#         messages.error(request, f"API connection error: {str(e)}", extra_tags="danger")
#         return render(request, "registration/login.html")
#
#     # 🔹 Step 2: Proceed if subscription is valid
#     settings_obj = website_setting.objects.first()
#     admin_path = settings.DOMAIN_URL
#
#     favicon = settings_obj.favicon if settings_obj and settings_obj.favicon else ''
#     logo = settings_obj.image if settings_obj and settings_obj.image else ''
#     from_name = settings_obj.from_name if settings_obj else ''
#     from_email = settings_obj.from_email if settings_obj else ''
#
#     context = {
#         'DOMAIN_NAME': settings.DOMAIN_NAME,
#         'DOMAIN_ICON': f"website_setting/favicon/{favicon}" if favicon else '',
#         'GET_PASS_IMAGE': f"website_setting/logo/{logo}" if logo else '',
#         'From_Email': f"{from_name} <{from_email}>" if from_name and from_email else '',
#         'website_name': settings_obj.website_name if settings_obj else '',
#         'website_link': settings_obj.website_link if settings_obj else '',
#         'copyright': settings_obj.copyright if settings_obj else '',
#         'IMAGEPATH': f'{admin_path}user/',
#         'DEFAULT_IMAGE': f"{admin_path}user/user.png",
#         'ADMIN_PATH': admin_path,
#         'background_image': settings.BACKGROUND_IMAGE,
#         'current_year': datetime.now().strftime('%Y'),
#         'database_name': settings.DATABASE_NAME,
#         'user_data': get_user_context(request.session.get('visitors'), 'Visitor', admin_path),
#         'gate_keeper_data': get_user_context(request.session.get('gate_keeper'), 'Gate Keeper', admin_path),
#         'employee_data': get_user_context(request.session.get('employee'), 'Employee', admin_path),
#         'setting': settings_obj
#     }
#
#     # 🔹 Handle admin session
#     admin_session = request.session.get('admin')
#     if admin_session:
#         email = admin_session.get('user_email')
#         if email == 'admin_by@example.com':
#             context['admin_data'] = {
#                 'id': 0,
#                 'user_name': admin_session.get('user_name'),
#                 'user_email': email,
#                 'first_name': 'Admines',
#                 'last_name': 'Admines',
#                 'image': None,
#                 'users_images': f"{admin_path}user/",
#                 'document': f"{admin_path}user/document",
#                 'default_image': f"{admin_path}user/user.png"
#             }
#         else:
#             context['admin_data'] = get_user_context(admin_session, 'Admin', admin_path)
#     else:
#         context['admin_data'] = {}
#
#     return context
