from django.contrib import admin
from crm.models import CollectionData, Lead, Campaign, Quote, Invoice, Payment, ActivateCustomer, ItemTemplate

class CollectionDataAdmin(admin.ModelAdmin):
    list_display = ('company_name', 'client_name', 'contact_no', 'interested', 'created_at')
    list_filter = ('interested', 'place', 'created_at')
    search_fields = ('company_name', 'client_name', 'contact_no')
    actions = ['convert_to_lead']
    
    def convert_to_lead(self, request, queryset):
        for collection in queryset:
            if not collection.leads.exists():
                collection.convert_to_lead()
        self.message_user(request, f"Converted {queryset.count()} collections to leads")
    convert_to_lead.short_description = "Convert selected collections to leads"

class LeadAdmin(admin.ModelAdmin):
    list_display = ('company', 'first_name', 'last_name', 'lead_status', 'is_converted', 'created_at')
    list_filter = ('lead_status', 'is_converted', 'lead_source', 'created_at')
    search_fields = ('company', 'first_name', 'last_name', 'phone')
    raw_id_fields = ('collections',)
    actions = ['convert_to_customer']
    
    def convert_to_customer(self, request, queryset):
        count = 0
        for lead in queryset:
            if not lead.is_converted and lead.convert_to_customer():
                count += 1
        self.message_user(request, f"Converted {count} leads to customers")
    convert_to_customer.short_description = "Convert selected leads to customers"

class ItemTemplateAdmin(admin.ModelAdmin):
    list_display = ('name', 'rate', 'is_active', 'created_at')
    list_filter = ('is_active', 'created_at')
    search_fields = ('name', 'description')
    list_editable = ('rate', 'is_active')

admin.site.register(CollectionData, CollectionDataAdmin)
admin.site.register(Lead, LeadAdmin)
admin.site.register(Campaign)
admin.site.register(Quote)
admin.site.register(Invoice)
admin.site.register(Payment)
admin.site.register(ActivateCustomer)
admin.site.register(ItemTemplate, ItemTemplateAdmin)