import os
import platform
from django.shortcuts import render, redirect
from django.utils import timezone
from .models import Department, ProcurementProposal, Document
from .forms import ProcurementProposalForm
from django.db.models import Sum, Count

def home(request):
    """Render the Qosh Tepa Central Management Dashboard."""
    departments = Department.objects.all()
    proposals = ProcurementProposal.objects.all().order_by('-created_at')[:5]
    
    total_budget = ProcurementProposal.objects.aggregate(Sum('estimated_cost'))['estimated_cost__sum'] or 0
    active_proposals = ProcurementProposal.objects.exclude(status='rejected').count()
    pending_documents = Document.objects.count()
    
    context = {
        "project_name": "Qosh Tepa Finance & Admin",
        "departments": departments,
        "proposals": proposals,
        "total_budget": total_budget,
        "active_proposals": active_proposals,
        "pending_documents": pending_documents,
        "current_time": timezone.now(),
    }
    return render(request, "core/index.html", context)

def proposal_create(request):
    """View to create a new M-7 Procurement Proposal."""
    if request.method == 'POST':
        form = ProcurementProposalForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('home')
    else:
        form = ProcurementProposalForm()
    
    return render(request, "core/proposal_form.html", {"form": form})
