# inventory/forms.py
from django import forms
from .models import Product, ProductCategory

class ProductCategoryForm(forms.ModelForm):
    class Meta:
        model = ProductCategory
        fields = ['name', 'description', 'color_code', 'icon']
        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control gradient-input', 'placeholder': 'Category name'}),
            'description': forms.Textarea(attrs={'class': 'form-control gradient-input', 'rows': 3, 'placeholder': 'Description'}),
            'color_code': forms.TextInput(attrs={'type': 'color', 'class': 'form-control form-control-color'}),
            'icon': forms.TextInput(attrs={'class': 'form-control gradient-input', 'placeholder': 'Font Awesome icon class'}),
        }

    def __init__(self, *args, **kwargs):
        self.company = kwargs.pop('company', None)
        super().__init__(*args, **kwargs)

    def clean_name(self):
        name = self.cleaned_data.get('name')
        if name and self.company:
            qs = ProductCategory.objects.filter(company=self.company, name__iexact=name)
            if self.instance.pk:
                qs = qs.exclude(pk=self.instance.pk)
            if qs.exists():
                raise forms.ValidationError("A category with this name already exists.")
        return name

class ProductForm(forms.ModelForm):
    UNIT_OF_MEASURE_CHOICES = [
        ('pcs', 'Pieces'),
        ('kg', 'Kilograms'),
        ('g', 'Grams'),
        ('l', 'Liters'),
        ('ml', 'Milliliters'),
        ('m', 'Meters'),
        ('cm', 'Centimeters'),
        ('box', 'Box'),
        ('pack', 'Pack'),
        ('carton', 'Carton'),
        ('dozen', 'Dozen'),
        ('pair', 'Pair'),
        ('set', 'Set'),
        ('unit', 'Unit'),
        ('bundle', 'Bundle'),
        ('roll', 'Roll'),
        ('sheet', 'Sheet'),
        ('tablet', 'Tablet'),
        ('capsule', 'Capsule'),
        ('bottle', 'Bottle'),
    ]
    
    unit_of_measure = forms.ChoiceField(
        choices=UNIT_OF_MEASURE_CHOICES,
        widget=forms.Select(attrs={'class': 'form-control gradient-select'})
    )
    
    class Meta:
        model = Product
        fields = [
            'name', 'sku', 'barcode', 'description', 'category',
            'price', 'wholesale_price', 'wholesale_min_quantity', 'cost_price',
            'stock_quantity', 'minimum_stock', 'unit_of_measure', 'image', 'supplier',
            'expiry_date', 'weight', 'dimensions', 'status'
        ]

        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control gradient-input', 'placeholder': 'Product name'}),
            'sku': forms.TextInput(attrs={'class': 'form-control gradient-input', 'placeholder': 'SKU/Code'}),
            'barcode': forms.TextInput(attrs={'class': 'form-control gradient-input', 'placeholder': 'Barcode (optional)'}),
            'description': forms.Textarea(attrs={'class': 'form-control gradient-input', 'rows': 3, 'placeholder': 'Description'}),
            'category': forms.Select(attrs={'class': 'form-control gradient-select'}),
            'price': forms.NumberInput(attrs={
                'class': 'form-control gradient-input',
                'step': '0.01',
                'placeholder': 'Retail selling price'
            }),
            'wholesale_price': forms.NumberInput(attrs={
                'class': 'form-control gradient-input',
                'step': '0.01',
                'placeholder': 'Wholesale price (optional)'
            }),
            'wholesale_min_quantity': forms.NumberInput(attrs={
                'class': 'form-control gradient-input',
                'placeholder': 'Min qty for wholesale price (e.g., 10)'
            }),
            'cost_price': forms.NumberInput(attrs={
                'class': 'form-control gradient-input',
                'step': '0.01',
                'placeholder': 'Cost price (optional)'
            }),

            'stock_quantity': forms.NumberInput(attrs={'class': 'form-control gradient-input', 'placeholder': 'Current stock'}),
            'minimum_stock': forms.NumberInput(attrs={'class': 'form-control gradient-input', 'placeholder': 'Min stock level'}),
            'image': forms.FileInput(attrs={'class': 'form-control'}),
            'supplier': forms.TextInput(attrs={'class': 'form-control gradient-input', 'placeholder': 'Supplier name'}),
            'expiry_date': forms.DateInput(attrs={'type': 'date', 'class': 'form-control gradient-input'}),
            'weight': forms.NumberInput(attrs={'class': 'form-control gradient-input', 'step': '0.01', 'placeholder': 'Weight in kg'}),
            'dimensions': forms.TextInput(attrs={'class': 'form-control gradient-input', 'placeholder': 'LxWxH in cm'}),
            'status': forms.Select(attrs={'class': 'form-control gradient-select'}),
        }
    
    def __init__(self, *args, **kwargs):
        self.company = kwargs.pop('company', None)
        super().__init__(*args, **kwargs)
        # ── FILTER FOREIGN KEYS BY COMPANY ──────────────────────────
        if self.company:
            self.fields['category'].queryset = ProductCategory.objects.filter(company=self.company)

        # Set the choices for unit_of_measure field
        self.fields['unit_of_measure'].choices = self.UNIT_OF_MEASURE_CHOICES
        # Set default value
        self.fields['unit_of_measure'].initial = 'pcs'

    def clean_sku(self):
        sku = self.cleaned_data.get('sku')
        if sku and self.company:
            qs = Product.objects.filter(company=self.company, sku__iexact=sku)
            if self.instance.pk:
                qs = qs.exclude(pk=self.instance.pk)
            if qs.exists():
                raise forms.ValidationError("A product with this SKU already exists.")
        return sku

from .models import Supplier, PurchaseOrder, PurchaseOrderItem

class SupplierForm(forms.ModelForm):
    class Meta:
        model = Supplier
        fields = ["name", "phone", "email", "address", "notes"]
        widgets = {
            "name": forms.TextInput(attrs={"class": "form-control gradient-input", "placeholder": "Supplier name"}),
            "phone": forms.TextInput(attrs={"class": "form-control gradient-input", "placeholder": "Phone number"}),
            "email": forms.EmailInput(attrs={"class": "form-control gradient-input", "placeholder": "Email (optional)"}),
            "address": forms.Textarea(attrs={"class": "form-control gradient-input", "rows": 2, "placeholder": "Address"}),
            "notes": forms.Textarea(attrs={"class": "form-control gradient-input", "rows": 2, "placeholder": "Notes"}),
        }

    def __init__(self, *args, **kwargs):
        self.company = kwargs.pop('company', None)
        super().__init__(*args, **kwargs)


from django import forms
from .models import PurchaseOrder, PurchaseOrderItem
from django.forms import inlineformset_factory

class PurchaseOrderForm(forms.ModelForm):
    class Meta:
        model = PurchaseOrder
        fields = [
            "supplier",
            "reference_number",
            "status",
            "date_ordered",
            "date_received",
            "notes"
        ]
        widgets = {
            "supplier": forms.Select(attrs={"class": "form-control"}),
            "reference_number": forms.TextInput(attrs={"class": "form-control"}),
            "status": forms.Select(attrs={"class": "form-control"}),
            "date_ordered": forms.DateInput(attrs={"class": "form-control", "type": "date"}),
            "date_received": forms.DateInput(attrs={"class": "form-control", "type": "date"}),
            "notes": forms.Textarea(attrs={"class": "form-control", "rows": 3}),
        }

    def __init__(self, *args, **kwargs):
        self.company = kwargs.pop('company', None)
        super().__init__(*args, **kwargs)
        if self.company:
            self.fields['supplier'].queryset = Supplier.objects.filter(company=self.company)



class PurchaseOrderItemForm(forms.ModelForm):
    class Meta:
        model = PurchaseOrderItem
        fields = ["product", "quantity", "unit_cost"]
        widgets = {
            "product": forms.Select(attrs={"class": "form-control"}),
            "quantity": forms.NumberInput(attrs={"class": "form-control"}),
            "unit_cost": forms.NumberInput(attrs={"class": "form-control"}),
        }

    def __init__(self, *args, **kwargs):
        self.company = kwargs.pop('company', None)
        super().__init__(*args, **kwargs)
        if self.company:
            self.fields['product'].queryset = Product.objects.filter(company=self.company)


from django.forms import inlineformset_factory

PurchaseOrderItemFormSet = inlineformset_factory(
    PurchaseOrder,
    PurchaseOrderItem,
    form=PurchaseOrderItemForm,
    extra=1,
    can_delete=True
)

