from django.shortcuts import render, redirect
from django.utils import timezone
from .models import Worker, Project, WorkLog, Team
from .forms import AttendanceLogForm
from django.contrib import messages
from django.contrib.auth.decorators import login_required

# Home view for the dashboard
@login_required
def index(request):
    total_workers = Worker.objects.filter(active=True).count()
    total_projects = Project.objects.filter(active=True).count()
    today_attendance = WorkLog.objects.filter(date=timezone.now().date()).count()
    
    context = {
        'total_workers': total_workers,
        'total_projects': total_projects,
        'today_attendance': today_attendance,
    }
    return render(request, 'core/index.html', context)

# View for logging attendance
@login_required
def attendance_log(request):
    if request.method == 'POST':
        form = AttendanceLogForm(request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, 'Attendance logged successfully!')
            return redirect('home')
    else:
        form = AttendanceLogForm(initial={'date': timezone.now().date()})
        
    return render(request, 'core/attendance_log.html', {'form': form})
