#!/usr/bin/env python
"""
Production Fix Missing M-Pesa Payment
Run this script on your cPanel production server to fix the missing payment
"""
import os
import sys
import django
from decimal import Decimal
from datetime import datetime

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from loans.models import MpesaTransaction, Loan, LoanApplication, LoanProduct
from users.models import CustomUser as User

def fix_production_missing_payment():
    """Fix the missing M-Pesa payment in production"""
    print("Fixing Production Missing M-Pesa Payment")
    print("=" * 50)
    
    # Transaction details
    transaction_id = "TJ8016VP0B"
    account_number = "40178864"
    phone_number = "+254700000100"
    
    print(f"Transaction ID: {transaction_id}")
    print(f"Account Number: {account_number}")
    print(f"Phone Number: {phone_number}")
    print()
    
    # 1. Find the user
    print("1. Finding user in production...")
    user = User.objects.filter(id_number=account_number).first()
    if not user:
        print("❌ User not found in production!")
        return
    
    print(f"✅ Found user: {user.get_full_name()}")
    print(f"   Phone: {user.phone_number}")
    print(f"   ID: {user.id_number}")
    print(f"   Status: {user.status}")
    
    # 2. Check existing loans
    print("\n2. Checking user's loans...")
    active_loans = user.loans.filter(status='active')
    print(f"Active loans: {active_loans.count()}")
    
    if not active_loans.exists():
        print("❌ No active loans found. Creating a test loan...")
        
        # Get loan product
        loan_product = LoanProduct.objects.first()
        if not loan_product:
            print("❌ No loan products found!")
            return
        
        # Create loan application
        application = LoanApplication.objects.create(
            borrower=user,
            loan_product=loan_product,
            requested_amount=Decimal("10000.00"),
            requested_duration=365,
            purpose="Test loan for M-Pesa payment processing",
            status='approved'
        )
        
        # Create loan
        from django.utils import timezone
        from datetime import timedelta
        
        disbursement_date = timezone.now()
        due_date = disbursement_date + timedelta(days=365)
        
        loan = Loan.objects.create(
            application=application,
            borrower=user,
            loan_number=f"LOAN-{account_number}",
            principal_amount=Decimal("10000.00"),
            interest_amount=Decimal("1500.00"),
            processing_fee=Decimal("500.00"),
            total_amount=Decimal("12000.00"),
            disbursement_date=disbursement_date,
            due_date=due_date,
            duration_days=365,
            status='active'
        )
        
        print(f"✅ Created loan: {loan.loan_number}")
        print(f"   Amount: {loan.total_amount}")
        print(f"   Outstanding: {loan.outstanding_amount}")
    else:
        print("✅ User has active loans:")
        for loan in active_loans:
            print(f"   {loan.loan_number} - {loan.total_amount} - Outstanding: {loan.outstanding_amount}")
    
    # 3. Check if transaction exists
    print("\n3. Checking transaction in production...")
    transaction = MpesaTransaction.objects.filter(trans_id=transaction_id).first()
    
    if not transaction:
        print("❌ Transaction not found. Creating it...")
        
        # Create the transaction
        transaction = MpesaTransaction.objects.create(
            trans_id=transaction_id,
            transaction_type='c2b',
            amount=Decimal("1.00"),
            phone_number=phone_number,
            msisdn=phone_number,
            bill_ref_number=account_number,
            status='confirmed',
            borrower=user,
            is_automatic=True,
            payment_source='automatic',
            processing_notes=f"Manually created for production - account {account_number}",
            raw_confirmation_data={
                'TransID': transaction_id,
                'TransAmount': '1.00',
                'MSISDN': phone_number,
                'BillRefNumber': account_number,
                'TransTime': '20251008062200',
            }
        )
        print(f"✅ Created transaction: {transaction.id}")
    else:
        print(f"✅ Found existing transaction: {transaction.id}")
        print(f"   Status: {transaction.status}")
        print(f"   Amount: {transaction.amount}")
    
    # 4. Process the payment
    print("\n4. Processing payment...")
    if transaction.status == 'failed' or transaction.status == 'confirmed':
        print("Attempting to process payment...")
        success = transaction.process_payment()
        
        if success:
            print("✅ Payment processed successfully!")
            transaction.refresh_from_db()
            print(f"   New status: {transaction.status}")
            print(f"   Processing notes: {transaction.processing_notes}")
            
            # Check if repayment was created
            try:
                if hasattr(transaction, 'repayment') and transaction.repayment:
                    print(f"✅ Repayment created: {transaction.repayment.receipt_number}")
                    print(f"   Loan: {transaction.repayment.loan.loan_number}")
                    print(f"   Amount: {transaction.repayment.amount}")
                    print(f"   Payment method: {transaction.repayment.payment_method}")
                    print(f"   Payment source: {transaction.repayment.payment_source}")
                else:
                    print("⚠️  No repayment created (check for errors)")
            except Exception as e:
                print(f"⚠️  Error checking repayment: {e}")
        else:
            print("❌ Payment processing failed")
            transaction.refresh_from_db()
            print(f"   Status: {transaction.status}")
            print(f"   Processing notes: {transaction.processing_notes}")
    else:
        print(f"Transaction already processed: {transaction.status}")
    
    print("\nSUMMARY:")
    print("-" * 30)
    print(f"User: {user.get_full_name()}")
    print(f"Active loans: {user.loans.filter(status='active').count()}")
    print(f"Transaction status: {transaction.status}")
    print(f"Transaction amount: {transaction.amount}")

if __name__ == "__main__":
    fix_production_missing_payment()
