from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from .models import Notification, NotificationType, UserNotificationPreference

# Create your views here.
# views.py
# @login_required
# def notification_preferences(request):
#     # Show checkboxes per type
#     ...
# views.py
# @login_required
# def notification_list(request):
#     notifs = Notification.objects.filter(user=request.user).order_by('-created_at')
#     return render(request, 'notifications/inbox.html', {'notifications': notifs})

from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from .models import Notification

@login_required
def notification_list(request):
    notifications = Notification.objects.filter(user=request.user, is_read=False).order_by('-created_at')
    return render(request, 'notifications/list.html', {
        'notifications': notifications,
        'pagetitle': '🔔 Notifications',
        'breadcrumbs': [
            {'label': 'Dashboard', 'url': 'dashboard'},
            {'label': 'Notifications'}
        ]
    })

from django.http import JsonResponse
from django.shortcuts import get_object_or_404
from .models import Notification

@login_required
def view_notification(request, note_id):
    note = get_object_or_404(Notification, id=note_id, user=request.user)
    if not note.is_read:
        note.is_read = True
        note.save()
    return JsonResponse({
        "message": note.message,
        "created_at": note.created_at.strftime("%d %b %Y, %I:%M %p"),
        "type": note.type.key
    })


@login_required
def notification_inbox(request):
    notifications = Notification.objects.filter(user=request.user).order_by('-created_at')
    return render(request, 'notifications/inbox.html', {'notifications': notifications})

@login_required
def notification_preferences(request):
    types = NotificationType.objects.filter(is_active=True)
    if request.method == 'POST':
        for ntype in types:
            pref, _ = UserNotificationPreference.objects.get_or_create(user=request.user, notification_type=ntype)
            pref.inapp = f'inapp_{ntype.id}' in request.POST
            pref.email = f'email_{ntype.id}' in request.POST
            pref.sms = f'sms_{ntype.id}' in request.POST
            pref.whatsapp = f'whatsapp_{ntype.id}' in request.POST
            pref.save()
        return redirect('notification_preferences')

    prefs = {
        pref.notification_type_id: pref
        for pref in UserNotificationPreference.objects.filter(user=request.user)
    }
    return render(request, 'notifications/preferences.html', {
        'types': types,
        'prefs': prefs
    })

