#!/usr/bin/env python
"""
Production Fix Receipt Number Conflict
Run this script on your cPanel production server to fix the receipt number conflict
"""
import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import MpesaTransaction, Repayment
from users.models import CustomUser as User

def fix_receipt_conflict():
    """Fix the receipt number conflict for the missing transaction"""
    print("Fixing Receipt Number Conflict")
    print("=" * 40)
    
    transaction_id = "TJ8016VP0B"
    
    # Find the transaction
    transaction = MpesaTransaction.objects.filter(trans_id=transaction_id).first()
    if not transaction:
        print(f"❌ Transaction {transaction_id} not found!")
        return
    
    print(f"Found transaction: {transaction.id}")
    print(f"Status: {transaction.status}")
    print(f"Amount: {transaction.amount}")
    print(f"Borrower: {transaction.borrower.get_full_name()}")
    
    # Check if there's a repayment with receipt conflict
    print("\nChecking for repayment conflicts...")
    
    # Find repayments for this user with similar amounts
    user = transaction.borrower
    recent_repayments = Repayment.objects.filter(
        loan__borrower=user,
        amount=transaction.amount,
        payment_date__gte=transaction.created_at
    ).order_by('-created_at')
    
    print(f"Recent repayments for this user: {recent_repayments.count()}")
    for repayment in recent_repayments[:5]:
        print(f"  {repayment.receipt_number} - {repayment.amount} - {repayment.payment_date}")
    
    # Check if transaction has a repayment
    try:
        if hasattr(transaction, 'repayment') and transaction.repayment:
            repayment = transaction.repayment
            print(f"\n✅ Transaction has repayment: {repayment.receipt_number}")
            print(f"   Amount: {repayment.amount}")
            print(f"   Payment method: {repayment.payment_method}")
            print(f"   Payment source: {repayment.payment_source}")
            print(f"   Loan: {repayment.loan.loan_number}")
        else:
            print("\n⚠️  Transaction has no repayment (due to receipt conflict)")
            
            # Try to create a repayment manually
            print("Attempting to create repayment manually...")
            
            # Get user's active loan
            active_loans = user.loans.filter(status='active')
            if active_loans.exists():
                loan = active_loans.first()
                print(f"Using loan: {loan.loan_number}")
                
                # Create repayment with unique receipt number
                from datetime import datetime
                timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
                receipt_number = f"RCP-{timestamp}"
                
                try:
                    repayment = Repayment.objects.create(
                        loan=loan,
                        amount=transaction.amount,
                        payment_method='mpesa',
                        payment_source='automatic',
                        mpesa_transaction_id=transaction.trans_id,
                        mpesa_phone_number=transaction.phone_number,
                        payment_date=transaction.created_at,
                        receipt_number=receipt_number
                    )
                    
                    # Link transaction to repayment
                    transaction.repayment = repayment
                    transaction.save()
                    
                    print(f"✅ Created repayment: {repayment.receipt_number}")
                    print(f"   Amount: {repayment.amount}")
                    print(f"   Loan: {repayment.loan.loan_number}")
                    
                except Exception as e:
                    print(f"❌ Error creating repayment: {e}")
            else:
                print("❌ No active loans found for user")
                
    except Exception as e:
        print(f"❌ Error checking repayment: {e}")
    
    print("\nSUMMARY:")
    print("-" * 30)
    print(f"Transaction: {transaction_id}")
    print(f"Status: {transaction.status}")
    print(f"Amount: {transaction.amount}")
    try:
        if hasattr(transaction, 'repayment') and transaction.repayment:
            print(f"Repayment: {transaction.repayment.receipt_number}")
        else:
            print("Repayment: None (conflict resolved)")
    except:
        print("Repayment: None")

if __name__ == "__main__":
    fix_receipt_conflict()
