from django.shortcuts import render, redirect
from .models import Client, Brand

def index(request):
    if request.method == 'POST':
        if 'client_name' in request.POST:
            client_name = request.POST.get('client_name')
            if client_name:
                Client.objects.create(name=client_name)
            return redirect('index')
        
        if 'brand_name' in request.POST and 'client_id' in request.POST:
            brand_name = request.POST.get('brand_name')
            client_id = request.POST.get('client_id')
            if brand_name and client_id:
                client = Client.objects.get(id=client_id)
                Brand.objects.create(name=brand_name, client=client)
            return redirect('index')

    clients = Client.objects.prefetch_related('brands').all().order_by('-created_at')
    context = {
        'clients': clients,
    }
    return render(request, 'core/index.html', context)