#!/usr/bin/env python
"""
Production Check Missing M-Pesa Payment
Run this script on your cPanel production server to investigate the missing payment
"""
import os
import sys
import django

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

from loans.models import MpesaTransaction
from users.models import CustomUser as User
from payments.models import MpesaConfiguration, MpesaCallback
from datetime import datetime, timedelta

def check_production_missing_payment():
    """Check production M-Pesa payment status"""
    print("PRODUCTION M-Pesa Payment Investigation")
    print("=" * 50)
    
    # Transaction details from your SMS
    transaction_id = "TJ8016VP0B"
    account_number = "40178864"
    phone_number = "+254700000100"  # From your user details
    
    print(f"Transaction ID: {transaction_id}")
    print(f"Account Number: {account_number}")
    print(f"Phone Number: {phone_number}")
    print()
    
    # 1. Check if transaction exists in production database
    print("1. Checking if transaction exists in production database...")
    transaction = MpesaTransaction.objects.filter(trans_id=transaction_id).first()
    if transaction:
        print(f"FOUND transaction in production database:")
        print(f"   ID: {transaction.id}")
        print(f"   Status: {transaction.status}")
        print(f"   Amount: {transaction.amount}")
        print(f"   Phone: {transaction.phone_number}")
        print(f"   Account: {transaction.bill_ref_number}")
        print(f"   Borrower: {transaction.borrower}")
        print(f"   Created: {transaction.created_at}")
        print(f"   Processing Notes: {transaction.processing_notes}")
    else:
        print("❌ Transaction NOT found in production database")
        print("   This means M-Pesa callbacks are NOT reaching your production system")
    
    print()
    
    # 2. Check if user exists in production
    print("2. Checking if user exists in production...")
    user = User.objects.filter(id_number=account_number).first()
    if user:
        print(f"FOUND user in production:")
        print(f"   Name: {user.get_full_name()}")
        print(f"   Phone: {user.phone_number}")
        print(f"   ID: {user.id_number}")
        print(f"   Email: {user.email}")
        print(f"   Status: {user.status}")
        print(f"   Role: {user.role}")
    else:
        print("❌ User NOT found in production database")
    
    print()
    
    # 3. Check recent M-Pesa transactions in production
    print("3. Recent M-Pesa transactions in production (last 24 hours):")
    recent_time = datetime.now() - timedelta(hours=24)
    recent_transactions = MpesaTransaction.objects.filter(
        created_at__gte=recent_time
    ).order_by('-created_at')
    
    print(f"Total recent transactions: {recent_transactions.count()}")
    for t in recent_transactions[:10]:
        print(f"   {t.trans_id} - {t.amount} - {t.status} - {t.created_at}")
    
    print()
    
    # 4. Check M-Pesa callbacks in production
    print("4. Recent M-Pesa callbacks in production:")
    recent_callbacks = MpesaCallback.objects.filter(
        created_at__gte=recent_time
    ).order_by('-created_at')
    
    print(f"Total recent callbacks: {recent_callbacks.count()}")
    for c in recent_callbacks[:5]:
        print(f"   {c.callback_type} - {c.created_at} - {c.status}")
    
    print()
    
    # 5. Check production M-Pesa configuration
    print("5. Production M-Pesa configuration:")
    configs = MpesaConfiguration.objects.all()
    for config in configs:
        print(f"   Shortcode: {config.business_short_code}")
        print(f"   Environment: {config.environment}")
        print(f"   Validation URL: {config.validation_url}")
        print(f"   Confirmation URL: {config.confirmation_url}")
        print(f"   Is Active: {config.is_active}")
        print()
    
    # 6. Check user's loans in production
    if user:
        print("6. User's loans in production:")
        loans = user.loans.all()
        print(f"Total loans: {loans.count()}")
        for loan in loans:
            print(f"   {loan.loan_number} - {loan.total_amount} - {loan.status} - Outstanding: {loan.outstanding_amount}")
    
    print()
    print("SUMMARY:")
    print("-" * 30)
    if not transaction:
        print("❌ MAIN ISSUE: Transaction TJ8016VP0B not found in production database")
        print("🔧 ACTION NEEDED: Check M-Pesa callback URL registration")
        print("🔧 ACTION NEEDED: Verify callback URLs are accessible from internet")
    else:
        print("✅ Transaction found in production database")
        print(f"   Status: {transaction.status}")
        if transaction.status == 'failed':
            print("🔧 ACTION NEEDED: Create active loan for user to process payment")
        elif transaction.status == 'processed':
            print("✅ Payment successfully processed")

if __name__ == "__main__":
    check_production_missing_payment()
