from django import forms
from .models import ServiceRequest
from global_settings.models import GlobalSetting

class ServiceRequestForm(forms.ModelForm):
    class Meta:
        model = ServiceRequest
        fields = ['service_date', 'service_time', 'contact_name', 'contact_mobile', 'notes', 'status', 'total_price']
        widgets = {
            'service_date': forms.DateInput(attrs={'class': 'form-control', 'type': 'date'}),
            'contact_name': forms.TextInput(attrs={'class': 'form-control'}),
            'contact_mobile': forms.TextInput(attrs={'class': 'form-control'}),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'status': forms.Select(attrs={'class': 'form-select'}),
            'total_price': forms.NumberInput(attrs={'class': 'form-control', 'step': '0.01'}),
        }

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        
        # Fetch global settings for time slots
        global_setting = GlobalSetting.objects.first()
        time_slot_choices = []
        if global_setting and global_setting.time_slots:
            time_slot_choices = [(slot, slot) for slot in global_setting.time_slots]
        
        # Ensure current value is in choices if it exists (to avoid it disappearing on edit)
        if self.instance and self.instance.pk and self.instance.service_time:
             if not any(self.instance.service_time == choice[0] for choice in time_slot_choices):
                 time_slot_choices.append((self.instance.service_time, self.instance.service_time))
        
        self.fields['service_time'].widget = forms.Select(choices=time_slot_choices, attrs={'class': 'form-select'})
