from django.contrib import admin
from .models import (
    POSOrder, POSOrderItem, POSReceiptSettings, PaymentTransaction,
    DailySalesSummary, UnusualTransaction, CashReconciliation, Customer
)

class POSOrderItemInline(admin.TabularInline):
    model = POSOrderItem
    extra = 0
    readonly_fields = ('product_name', 'quantity', 'unit_price', 'total_price')

class POSReceiptSettingsInline(admin.StackedInline):
    model = POSReceiptSettings
    can_delete = False

@admin.register(POSOrder)
class POSOrderAdmin(admin.ModelAdmin):
    list_display = ('order_number', 'company', 'branch', 'total_amount', 'discount_amount', 'final_amount', 'status', 'payment_method', 'payment_status', 'created_at')
    list_filter = ('company', 'status', 'payment_method', 'payment_status', 'created_at')
    search_fields = ('order_number', 'customer_name', 'customer_phone', 'cashier')
    inlines = [POSOrderItemInline, POSReceiptSettingsInline]
    readonly_fields = ('created_at', 'updated_at')
    ordering = ('company', '-created_at')

@admin.register(PaymentTransaction)
class PaymentTransactionAdmin(admin.ModelAdmin):
    list_display = ('order', 'get_company', 'payment_method', 'amount', 'reference_number', 'status', 'created_at')
    list_filter = ('order__company', 'payment_method', 'status', 'created_at')
    search_fields = ('order__order_number', 'reference_number', 'transaction_id')
    ordering = ('order__company', '-created_at')

    def get_company(self, obj):
        return obj.order.company
    get_company.short_description = 'Company'
    get_company.admin_order_field = 'order__company'

@admin.register(DailySalesSummary)
class DailySalesSummaryAdmin(admin.ModelAdmin):
    list_display = ('date', 'company', 'total_revenue', 'total_profit', 'total_transactions')
    list_filter = ('company', 'date')
    search_fields = ('company__name',)
    ordering = ('company', '-date')

@admin.register(UnusualTransaction)
class UnusualTransactionAdmin(admin.ModelAdmin):
    list_display = ('order', 'company', 'reason', 'flagged_by', 'resolved', 'flagged_at')
    list_filter = ('company', 'resolved', 'flagged_at')
    search_fields = ('order__order_number', 'reason', 'flagged_by')
    ordering = ('company', '-flagged_at')

@admin.register(CashReconciliation)
class CashReconciliationAdmin(admin.ModelAdmin):
    list_display = ('date', 'company', 'expected', 'actual', 'variance', 'cashier')
    list_filter = ('company', 'date')
    search_fields = ('company__name', 'cashier')
    ordering = ('company', '-date')

@admin.register(Customer)
class CustomerAdmin(admin.ModelAdmin):
    list_display = ('name', 'company', 'phone', 'email', 'created_at')
    list_filter = ('company', 'created_at')
    search_fields = ('name', 'phone', 'email', 'company__name')
    ordering = ('company', 'name')
