import os
import platform
from django import get_version as django_version
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from .models import Job, Agreement
from django.contrib.auth.decorators import login_required

def home(request):
    """Modern Dashboard Landing Page"""
    jobs_count = Job.objects.count()
    active_jobs = Job.objects.filter(status='active').count()
    recent_jobs = Job.objects.order_by('-created_at')[:5]
    
    context = {
        "project_name": "Aitken Spence Industrial Solutions",
        "jobs_count": jobs_count,
        "active_jobs": active_jobs,
        "recent_jobs": recent_jobs,
        "django_version": django_version(),
        "python_version": platform.python_version(),
    }
    return render(request, "core/index.html", context)

def job_list(request):
    jobs = Job.objects.all().order_by('-created_at')
    return render(request, "core/job_list.html", {"jobs": jobs})

def job_create(request):
    if request.method == "POST":
        client_name = request.POST.get("client_name")
        description = request.POST.get("description")
        job = Job.objects.create(client_name=client_name, description=description)
        # Automatically create an empty agreement
        Agreement.objects.create(job=job, terms="Standard Terms Apply", scope_of_work=description)
        return redirect('job_detail', pk=job.pk)
    return render(request, "core/job_form.html")

def job_detail(request, pk):
    job = get_object_or_404(Job, pk=pk)
    return render(request, "core/job_detail.html", {"job": job})

def agreement_print(request, pk):
    agreement = get_object_or_404(Agreement, job__pk=pk)
    return render(request, "core/agreement_print.html", {"agreement": agreement})