from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from .models import SiteSetting, Gallery, News

@login_required
def website_management(request):

    # ---------- CREATE ----------
    if request.method == "POST":
        action = request.POST.get("action")

        if action == "add_gallery":
            Gallery.objects.create(
                title=request.POST["title"],
                description=request.POST.get("description", ""),
                image=request.FILES["image"],
            )

        elif action == "add_news":
            News.objects.create(
                title=request.POST["title"],
                content=request.POST["content"],
            )

        elif action == "update_site":
            site, _ = SiteSetting.objects.get_or_create(id=1)
            site.site_name = request.POST["site_name"]
            site.about = request.POST["about"]
            if "logo" in request.FILES:
                site.logo = request.FILES["logo"]
            site.save()

        elif action == "toggle_gallery":
            g = get_object_or_404(Gallery, id=request.POST["id"])
            g.is_active = not g.is_active
            g.save()

        elif action == "toggle_news":
            n = get_object_or_404(News, id=request.POST["id"])
            n.is_active = not n.is_active
            n.save()

        return redirect("exams:website_management")

    # ---------- DISPLAY ----------
    return render(request, "admin/website_management.html", {
        "site": SiteSetting.objects.first(),
        "gallery": Gallery.objects.all().order_by("-created_at"),
        "news": News.objects.all().order_by("-created_at"),
    })
