from django import forms
from django.utils import timezone
from .models import Report

class ReportSubmissionForm(forms.ModelForm):
    """Form for submitting reports."""
    class Meta:
        model = Report
        fields = ['title', 'report_type', 'period_start', 'period_end', 'content', 'file']
        widgets = {
            'period_start': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'period_end': forms.DateInput(attrs={'type': 'date', 'class': 'form-control'}),
            'content': forms.Textarea(attrs={'class': 'form-control', 'rows': 5}),
            'file': forms.FileInput(attrs={'class': 'form-control'})
        }
    
    def __init__(self, *args, **kwargs):
        self.user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)
        
        # Set default dates
        today = timezone.now().date()
        self.fields['period_start'].initial = today.replace(day=1)  # First day of current month
        self.fields['period_end'].initial = today  # Today
        
        # Add Bootstrap classes to all fields
        for field_name, field in self.fields.items():
            if field_name not in ['period_start', 'period_end', 'content', 'file']:
                field.widget.attrs.update({'class': 'form-select' if field_name == 'report_type' else 'form-control'})
    
    def clean(self):
        cleaned_data = super().clean()
        period_start = cleaned_data.get('period_start')
        period_end = cleaned_data.get('period_end')
        
        if period_start and period_end and period_start > period_end:
            self.add_error('period_end', 'End date must be after start date')
        
        return cleaned_data
