import uuid
from django.db import models
from django.contrib.auth import get_user_model
from django.db.models import Sum
from decimal import Decimal
from django.utils import timezone


User = get_user_model()


class Location(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200)
    is_truck = models.BooleanField(default=False)

    def __str__(self):
        return self.name

    
class Product(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    sku = models.CharField(max_length=64, unique=True)
    name = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    unit_price = models.DecimalField(max_digits=12, decimal_places=2)
    buying_price = models.DecimalField(max_digits=12, decimal_places=2, default=0)
    image = models.ImageField(upload_to='products/', blank=True, null=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.name} ({self.sku})"


class UserProfile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, blank=True)

    def __str__(self):
        return f"{self.user.username} - {self.location}"


class StockLevel(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name='stock_levels')
    location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='stock_levels')
    quantity = models.IntegerField(default=0)
    updated_at = models.DateTimeField(auto_now=True)

    class Meta:
        unique_together = ('product', 'location')

    def __str__(self):
        return f"{self.product.name} @ {self.location.name}: {self.quantity}"

    def update_total_quantity(self):
        """Accurately recalculate total quantity from StockLevelSize rows."""
        from django.db.models import Sum
        total = (
            self.sizes.aggregate(total=Sum('quantity')).get('total') or 0
        )
        if self.quantity != total:
            self.quantity = total
            self.save(update_fields=['quantity', 'updated_at'])


class Size(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=10, unique=True)

    def __str__(self):
        return self.name


class StockLevelSize(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    stock_level = models.ForeignKey(StockLevel, on_delete=models.CASCADE, related_name="sizes")
    size = models.ForeignKey(Size, on_delete=models.CASCADE)
    quantity = models.PositiveIntegerField(default=0)

    class Meta:
        unique_together = ('stock_level', 'size')

    def __str__(self):
        return f"{self.stock_level.product.name} - {self.size.name}: {self.quantity}"

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        # Auto-update total quantity in StockLevel
        self.stock_level.update_total_quantity()


class Device(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200)
    assigned_to = models.CharField(max_length=200, blank=True)
    location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, blank=True)
    last_seen = models.DateTimeField(null=True, blank=True)

    def __str__(self):
        return self.name


# ✅ NEW: Enhanced Transaction model with payment tracking
class Transaction(models.Model):
    PAYMENT_METHODS = [
        ('cash', 'Cash'),
        ('mpesa_paybill', 'M-Pesa Paybill'),
        ('mpesa_till', 'M-Pesa Till'),
        ('bank_transfer', 'Bank Transfer'),
        ('on_credit', 'On Credit'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    device = models.ForeignKey(Device, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField()
    total_amount = models.DecimalField(max_digits=12, decimal_places=2)
    payment_method = models.CharField(max_length=50, choices=PAYMENT_METHODS, default='cash')
    
    # ✅ NEW: Additional payment tracking fields
    mpesa_reference = models.CharField(max_length=100, blank=True, null=True, 
                                      help_text="M-Pesa transaction code (e.g., QGH7X9Y2)")
    payment_phone = models.CharField(max_length=20, blank=True, null=True,
                                    help_text="Customer phone number for M-Pesa")
    
    synced = models.BooleanField(default=False)
    raw = models.JSONField(null=True, blank=True)
    server_receipt_number = models.BigIntegerField(null=True, blank=True)

    def __str__(self):
        return f"TX {self.id} ({self.created_at})"
    
    def get_location(self):
        """Helper method to get transaction location"""
        if self.device and self.device.location:
            return self.device.location
        return None
    
class CreditSale(models.Model):
    """
    Tracks credit (buy-now-pay-later) sales.
    Linked 1-to-1 with a Transaction whose payment_method='on_credit'.
 
    IMPORTANT: LocationCashBalance is NOT updated when the sale is made.
    It is only updated when the admin marks this record as paid.
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    transaction = models.OneToOneField(
        Transaction,
        on_delete=models.CASCADE,
        related_name='credit_sale'
    )
 
    # ── Customer info (required at sale time) ──────────────────────────────
    customer_name  = models.CharField(max_length=255)
    customer_phone = models.CharField(max_length=20)
    due_date       = models.DateField(help_text="Date by which payment is expected")
 
    # ── Payment confirmation (filled by admin when paid) ───────────────────
    is_paid = models.BooleanField(default=False)
    paid_at = models.DateTimeField(null=True, blank=True)
    paid_payment_method = models.CharField(
        max_length=50,
        choices=Transaction.PAYMENT_METHODS,
        null=True, blank=True,
        help_text="How did the customer eventually settle the debt?"
    )
    confirmed_by = models.ForeignKey(
        User,
        on_delete=models.SET_NULL,
        null=True, blank=True,
        related_name='confirmed_credits',
        help_text="Admin who confirmed the payment"
    )
 
    notes      = models.TextField(blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
 
    class Meta:
        ordering   = ['is_paid', 'due_date']
        verbose_name = 'Credit Sale'
        verbose_name_plural = 'Credit Sales'
 
    # ── Computed helpers ───────────────────────────────────────────────────
    @property
    def is_overdue(self):
        if self.is_paid:
            return False
        return timezone.now().date() > self.due_date
 
    @property
    def days_overdue(self):
        if self.is_paid:
            return 0
        return max(0, (timezone.now().date() - self.due_date).days)
 
    @property
    def days_until_due(self):
        if self.is_paid:
            return 0
        return (self.due_date - timezone.now().date()).days
 
    def __str__(self):
        amount = self.transaction.total_amount
        if self.is_paid:
            status = "PAID"
        elif self.is_overdue:
            status = f"OVERDUE {self.days_overdue}d"
        else:
            status = f"DUE IN {self.days_until_due}d"
        return (
            f"{self.customer_name} ({self.customer_phone})"
            f" — KES {amount:,.0f} [{status}]"
        )


class TransactionItem(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    transaction = models.ForeignKey('Transaction', related_name='items', on_delete=models.CASCADE)
    product = models.ForeignKey('Product', on_delete=models.CASCADE)
    size = models.ForeignKey('Size', on_delete=models.SET_NULL, null=True, blank=True)
    quantity = models.IntegerField(default=0)
    unit_price = models.DecimalField(max_digits=10, decimal_places=2)
    line_total = models.DecimalField(max_digits=10, decimal_places=2)


class StockMovement(models.Model):
    MOVEMENT_TYPES = [
        ('sale', 'Sale'),
        ('purchase', 'Purchase'),
        ('transfer', 'Transfer'),
        ('adjustment', 'Adjustment'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    delta = models.IntegerField()
    reason = models.CharField(max_length=100, choices=MOVEMENT_TYPES, default='sale')
    purchase = models.ForeignKey('Purchase', on_delete=models.CASCADE, related_name='items', null=True, blank=True)
    transaction = models.ForeignKey(Transaction, on_delete=models.SET_NULL, null=True, blank=True)
    location = models.ForeignKey(Location, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"{self.product.name} | {self.reason} ({self.delta})"


class ProfitRecord(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    product = models.ForeignKey(Product, on_delete=models.CASCADE)
    stock_movement = models.OneToOneField(StockMovement, on_delete=models.CASCADE)
    profit = models.DecimalField(max_digits=12, decimal_places=2)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        sign = "Profit" if self.profit >= 0 else "Loss"
        return f"{self.product.name} | {sign}: {self.profit}"


# ✅ NEW: Bank/Cash Management Model
class LocationCashBalance(models.Model):
    """
    Tracks cash balance for each location and payment method.
    This acts like a "bank account" for each location.
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='cash_balances')
    payment_method = models.CharField(max_length=50, choices=Transaction.PAYMENT_METHODS)
    
    # Current balance
    balance = models.DecimalField(max_digits=15, decimal_places=2, default=0)
    
    # Totals for reporting
    total_sales = models.DecimalField(max_digits=15, decimal_places=2, default=0)
    total_purchases = models.DecimalField(max_digits=15, decimal_places=2, default=0)
    
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        unique_together = ('location', 'payment_method')
        ordering = ['location', 'payment_method']
    
    def __str__(self):
        return f"{self.location.name} - {self.get_payment_method_display()}: KES {self.balance}"


# ✅ NEW: Detailed transaction log for bank operations
class CashTransaction(models.Model):
    """
    Logs every cash/payment movement (sales, purchases, withdrawals, deposits)
    This gives you a complete audit trail.
    """
    TRANSACTION_TYPES = [
        ('sale', 'Sale Income'),
        ('purchase', 'Stock Purchase'),
        ('withdrawal', 'Cash Withdrawal'),
        ('deposit', 'Cash Deposit'),
        ('transfer', 'Transfer Between Locations'),
        ('adjustment', 'Balance Adjustment'),
        ('transfer_out', 'Transfer Out'),  # ✅ NEW
        ('transfer_in', 'Transfer In'),    # ✅ NEW
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='cash_transactions')
    payment_method = models.CharField(max_length=50, choices=Transaction.PAYMENT_METHODS)
    
    transaction_type = models.CharField(max_length=50, choices=TRANSACTION_TYPES)
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    
    # Link to sale transaction if applicable
    sale_transaction = models.ForeignKey(Transaction, on_delete=models.SET_NULL, 
                                        null=True, blank=True, related_name='cash_entries')
    
    # For other types of transactions
    description = models.TextField(blank=True)
    reference_number = models.CharField(max_length=100, blank=True, null=True)
    
    # Balance after this transaction
    balance_after = models.DecimalField(max_digits=15, decimal_places=2)
    
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.location.name} - {self.transaction_type}: KES {self.amount}"

# ✅ NEW MODEL 1: Purchase
class Purchase(models.Model):
    """
    Purchase record - buying stock from suppliers.
    Stock can go to any location (Main Store or Truck).
    Payment deducted from global bank (tracked by location for accounting).
    """
    PAYMENT_METHODS = Transaction.PAYMENT_METHODS  # Reuse existing choices
    
    PAYMENT_STATUS_CHOICES = [
        ('paid', 'Paid in Full'),
        ('credit', 'On Credit (Pay Later)'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    # Supplier
    supplier_name = models.CharField(max_length=255, help_text="Who are we buying from?")
    
    # Locations
    destination_location = models.ForeignKey(
        Location, 
        on_delete=models.CASCADE,
        related_name='purchases_received',
        help_text="Where should stock be delivered? (Main Store or Truck)"
    )
    
    paid_from_location = models.ForeignKey(
        Location,
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        related_name='purchases_paid',
        help_text="Which location's cash segment to deduct from (for accounting)"
    )
    
    # Money
    purchase_date = models.DateTimeField()
    total_amount = models.DecimalField(max_digits=12, decimal_places=2)
    payment_method = models.CharField(max_length=50, choices=PAYMENT_METHODS, default='cash')
    payment_status = models.CharField(max_length=20, choices=PAYMENT_STATUS_CHOICES, default='paid')
    
    # Optional
    reference_number = models.CharField(
        max_length=100, 
        blank=True, 
        null=True,
        help_text="Supplier invoice/receipt number"
    )
    notes = models.TextField(blank=True)
    
    # Tracking
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-purchase_date']
        verbose_name = 'Purchase'
        verbose_name_plural = 'Purchases'
    
    def __str__(self):
        return f"Purchase from {self.supplier_name} → {self.destination_location.name} (KES {self.total_amount:,.2f})"
    
    def get_items(self):
        return self.items.all()
    
    def item_count(self):
        return self.items.count()

    def total_units(self):
        return sum(abs(i.delta) for i in self.items.all())

# ✅ NEW MODEL 2: Cash Transfer
class CashTransfer(models.Model):
    """
    Transfer cash between locations and/or payment methods.
    Examples:
    - Main Store Cash → Truck Cash (give float)
    - Truck M-Pesa → Main Store Bank (consolidation)
    - Main Store Cash → Main Store M-Pesa (deposit cash to M-Pesa)
    """
    TRANSFER_TYPES = [
        ('method_change', 'Payment Method Change'),      # Same location, different method
        ('location_transfer', 'Location Transfer'),      # Different location, same method
        ('consolidation', 'Consolidation/Banking'),      # Moving to main bank
        ('float', 'Float Allocation'),                   # Giving working capital
        ('other', 'Other'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    # FROM (Source)
    from_location = models.ForeignKey(
        Location, 
        related_name='transfers_out', 
        on_delete=models.CASCADE,
        help_text="Location losing money"
    )
    from_payment_method = models.CharField(
        max_length=50, 
        choices=Transaction.PAYMENT_METHODS,
        help_text="Payment method losing money"
    )
    
    # TO (Destination)
    to_location = models.ForeignKey(
        Location, 
        related_name='transfers_in', 
        on_delete=models.CASCADE,
        help_text="Location receiving money"
    )
    to_payment_method = models.CharField(
        max_length=50,
        choices=Transaction.PAYMENT_METHODS,
        help_text="Payment method receiving money"
    )
    
    # Amount & Type
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    transfer_type = models.CharField(max_length=50, choices=TRANSFER_TYPES)
    notes = models.TextField(blank=True)
    
    # Linking (for audit trail)
    reference_number = models.CharField(max_length=100, unique=True, editable=False)
    
    # Tracking
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-created_at']
        verbose_name = 'Cash Transfer'
        verbose_name_plural = 'Cash Transfers'
    
    def __str__(self):
        amount_str = f"{self.amount:,.2f}"
        return (
            f"{self.from_location.name} ({self.get_from_payment_method_display()}) → "
            f"{self.to_location.name} ({self.get_to_payment_method_display()}): "
            f"KES {self.amount}"
        )
    
    def save(self, *args, **kwargs):
        # Auto-generate reference number
        if not self.reference_number:
            from datetime import datetime
            timestamp = datetime.now().strftime('%Y%m%d%H%M%S')
            self.reference_number = f"TRF-{timestamp}-{str(self.id)[:8]}"
        super().save(*args, **kwargs)


# ===== EXPENSE TRACKING MODELS =====

class ExpenseCategory(models.Model):
    """
    Categories for expenses (Rent, Salaries, Fuel, Lending, etc.)
    Can be Business or Personal type
    """
    CATEGORY_TYPES = [
        ('business', 'Business Expense'),
        ('personal', 'Personal Expense'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=100, unique=True)
    category_type = models.CharField(max_length=20, choices=CATEGORY_TYPES, default='business')
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        verbose_name = 'Expense Category'
        verbose_name_plural = 'Expense Categories'
        ordering = ['category_type', 'name']
    
    def __str__(self):
        type_icon = '💼' if self.category_type == 'business' else '👤'
        return f"{type_icon} {self.name}"


class Expense(models.Model):
    """
    Records all expenses - business and personal
    Always deducts from MainStore Bank Transfer account
    """
    EXPENSE_TYPES = [
        ('business', 'Business Expense'),
        ('personal', 'Personal Expense'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    
    # When & How Much
    date = models.DateField(help_text="When was this expense incurred?")
    amount = models.DecimalField(max_digits=12, decimal_places=2)
    
    # Categorization
    expense_type = models.CharField(max_length=20, choices=EXPENSE_TYPES)
    category = models.ForeignKey(
        ExpenseCategory, 
        on_delete=models.PROTECT,
        related_name='expenses',
        help_text="What type of expense is this?"
    )
    
    # Details
    description = models.TextField(
        help_text="Describe this expense (e.g., 'Lent John for medical emergency')"
    )
    reference_number = models.CharField(
        max_length=100, 
        blank=True, 
        null=True,
        help_text="Receipt number, invoice number, etc."
    )
    
    # Always paid from MainStore Bank
    paid_from_location = models.ForeignKey(
        Location,
        on_delete=models.PROTECT,
        related_name='expenses_paid',
        help_text="Location that paid (usually MainStore)"
    )
    payment_method = models.CharField(
        max_length=50,
        choices=Transaction.PAYMENT_METHODS,
        default='bank_transfer',
        help_text="Payment method used"
    )
    
    # Tracking
    created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ['-date', '-created_at']
        verbose_name = 'Expense'
        verbose_name_plural = 'Expenses'
    
    def __str__(self):
        type_emoji = '💼' if self.expense_type == 'business' else '👤'
        return f"{type_emoji} {self.category.name} - KES {self.amount:,.0f} ({self.date})"
    
    def save(self, *args, **kwargs):
        """
        Override save to automatically:
        1. Deduct from MainStore Bank balance
        2. Create CashTransaction log entry
        """
        is_new = self._state.adding
        
        if is_new:
            # Get or create MainStore Bank balance
            from decimal import Decimal
            
            cash_balance, created = LocationCashBalance.objects.get_or_create(
                location=self.paid_from_location,
                payment_method=self.payment_method,
                defaults={
                    'balance': Decimal('0.00'),
                    'total_sales': Decimal('0.00'),
                    'total_purchases': Decimal('0.00')
                }
            )
            
            # Deduct expense from balance
            cash_balance.balance -= self.amount
            cash_balance.save()
            
            # Create audit trail
            CashTransaction.objects.create(
                location=self.paid_from_location,
                payment_method=self.payment_method,
                transaction_type='adjustment',  # Using existing type
                amount=self.amount,
                description=f"{self.get_expense_type_display()}: {self.category.name} - {self.description}",
                reference_number=self.reference_number or '',
                balance_after=cash_balance.balance,
                created_by=self.created_by
            )
        
        super().save(*args, **kwargs)

# Add this to your existing models.py

class SalesTarget(models.Model):
    """
    Sales targets for locations with bonus tracking
    """
    PERIOD_CHOICES = [
        ('daily', 'Daily'),
        ('weekly', 'Weekly'),
        ('monthly', 'Monthly'),
        ('quarterly', 'Quarterly'),
        ('yearly', 'Yearly'),
    ]
    
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    location = models.ForeignKey(Location, on_delete=models.CASCADE, related_name='sales_targets')
    target_amount = models.DecimalField(max_digits=12, decimal_places=2)
    bonus_percentage = models.DecimalField(max_digits=5, decimal_places=2, default=2.00, 
                                          help_text="Bonus percentage (e.g., 2.00 for 2%)")
    period = models.CharField(max_length=20, choices=PERIOD_CHOICES, default='monthly')
    
    # Optional: specific date range
    start_date = models.DateField(null=True, blank=True)
    end_date = models.DateField(null=True, blank=True)
    
    is_active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    class Meta:
        ordering = ['-created_at']
        verbose_name = 'Sales Target'
        verbose_name_plural = 'Sales Targets'
    
    def __str__(self):
        return f"{self.location.name} - {self.get_period_display()} Target: KES {self.target_amount:,.0f}"
    
    def get_current_sales(self):
        """Calculate current sales for this target's period"""
        from django.utils import timezone
        from datetime import timedelta
        
        now = timezone.now()
        
        # Determine date range
        if self.start_date and self.end_date:
            start = timezone.make_aware(
                timezone.datetime.combine(self.start_date, timezone.datetime.min.time())
            )
            end = timezone.make_aware(
                timezone.datetime.combine(self.end_date, timezone.datetime.max.time())
            )
        else:
            # Calculate based on period
            if self.period == 'daily':
                start = now.replace(hour=0, minute=0, second=0, microsecond=0)
                end = start + timedelta(days=1)
            elif self.period == 'weekly':
                days_since_monday = now.weekday()
                start = (now - timedelta(days=days_since_monday)).replace(hour=0, minute=0, second=0)
                end = start + timedelta(days=7)
            elif self.period == 'monthly':
                start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
                if now.month == 12:
                    end = now.replace(year=now.year + 1, month=1, day=1, hour=0, minute=0, second=0)
                else:
                    end = now.replace(month=now.month + 1, day=1, hour=0, minute=0, second=0)
            elif self.period == 'quarterly':
                quarter = (now.month - 1) // 3 + 1
                first_month = (quarter - 1) * 3 + 1
                start = now.replace(month=first_month, day=1, hour=0, minute=0, second=0)
                if quarter == 4:
                    end = now.replace(year=now.year + 1, month=1, day=1, hour=0, minute=0, second=0)
                else:
                    end = now.replace(month=first_month + 3, day=1, hour=0, minute=0, second=0)
            else:  # yearly
                start = now.replace(month=1, day=1, hour=0, minute=0, second=0)
                end = now.replace(year=now.year + 1, month=1, day=1, hour=0, minute=0, second=0)
        
        # Get sales for this location in the period
        sales = Transaction.objects.filter(
            device__location=self.location,
            created_at__gte=start,
            created_at__lt=end
        ).aggregate(total=Sum('total_amount'))['total'] or Decimal('0.00')
        
        return sales
    
    def calculate_bonus(self):
        """Calculate bonus if target is met"""
        sales = self.get_current_sales()
        if sales >= self.target_amount:
            return sales * (self.bonus_percentage / 100)
        return Decimal('0.00')
    
    def get_progress_percentage(self):
        """Get progress toward target as percentage"""
        sales = self.get_current_sales()
        if self.target_amount > 0:
            return min((sales / self.target_amount) * 100, 100)
        return 0


class BonusRecord(models.Model):
    """
    Historical record of bonuses earned
    """
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    sales_target = models.ForeignKey(SalesTarget, on_delete=models.CASCADE, related_name='bonus_records')
    location = models.ForeignKey(Location, on_delete=models.CASCADE)
    
    period_start = models.DateField()
    period_end = models.DateField()
    
    target_amount = models.DecimalField(max_digits=12, decimal_places=2)
    actual_sales = models.DecimalField(max_digits=12, decimal_places=2)
    bonus_amount = models.DecimalField(max_digits=12, decimal_places=2)
    
    paid = models.BooleanField(default=False)
    paid_at = models.DateTimeField(null=True, blank=True)
    
    created_at = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.location.name} - Bonus: KES {self.bonus_amount:,.0f} ({self.period_start} to {self.period_end})"


# Update Purchase model to add credit interest
# Modify the existing Purchase model's save method:

# In Purchase model, update the save method:
def save(self, *args, **kwargs):
    # Apply 1% interest for credit purchases
    if self.payment_status == 'credit' and self.total_amount:
        # Check if this is a new record or if payment status changed to credit
        if not self.pk or self._state.adding:
            # Apply 1% interest
            self.total_amount = self.total_amount * Decimal('1.01')
    
    super().save(*args, **kwargs)

#matatu models 

class MatatuIncome(models.Model):
    id          = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    date        = models.DateField()
    amount      = models.DecimalField(max_digits=12, decimal_places=2)
    description = models.TextField(blank=True, help_text="e.g. Monday collections, weekend run")
    collected_by = models.CharField(max_length=255, blank=True, help_text="Driver or conductor name")
    created_by  = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    created_at  = models.DateTimeField(auto_now_add=True)
 
    class Meta:
        ordering = ['-date']
        verbose_name = 'Matatu Income'
        verbose_name_plural = 'Matatu Income'
 
    def __str__(self):
        return f"Income {self.date} — KES {self.amount:,.0f}"
 
 
class MatatuExpense(models.Model):
    CATEGORY_CHOICES = [
        ('fuel',        'Fuel'),
        ('repair',      'Repair / Spare Parts'),
        ('police',      'Police / Fines'),
        ('parking',     'Parking / Stage Fee'),
        ('insurance',   'Insurance'),
        ('sacco',       'SACCO Fees'),
        ('driver',      'Driver / Conductor Pay'),
        ('service',     'Routine Service'),
        ('other',       'Other'),
    ]
 
    id          = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    date        = models.DateField()
    amount      = models.DecimalField(max_digits=12, decimal_places=2)
    category    = models.CharField(max_length=50, choices=CATEGORY_CHOICES)
    description = models.TextField(blank=True)
    created_by  = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    created_at  = models.DateTimeField(auto_now_add=True)
 
    class Meta:
        ordering = ['-date']
        verbose_name = 'Matatu Expense'
        verbose_name_plural = 'Matatu Expenses'
 
    def __str__(self):
        return f"{self.get_category_display()} {self.date} — KES {self.amount:,.0f}"