from django.shortcuts import render, redirect, get_object_or_404
from .models import Lead, Call
from .forms import LeadForm, CallForm

def index(request):
    if request.method == 'POST':
        form = LeadForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = LeadForm()
    
    leads = Lead.objects.all()
    return render(request, 'core/index.html', {'form': form, 'leads': leads})

def lead_detail(request, lead_id):
    lead = get_object_or_404(Lead, pk=lead_id)
    if request.method == 'POST':
        form = CallForm(request.POST)
        if form.is_valid():
            call = form.save(commit=False)
            call.lead = lead
            call.sales_rep = request.user
            call.save()
            return redirect('lead_detail', lead_id=lead.id)
    else:
        form = CallForm()
    return render(request, 'core/lead_detail.html', {'lead': lead, 'form': form})