#!/usr/bin/env python3
import pymysql

DB = dict(host='localhost', port=3306, database='xygbfpsg_loans',
          user='xygbfpsg_graz', password='j.ez-xy6##y.rllB',
          charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

print("Checking New Loan Application button issues...")
print("="*60)

conn = pymysql.connect(**DB)
try:
    with conn.cursor() as cursor:
        # Check if there are any borrowers
        cursor.execute("SELECT COUNT(*) as count FROM users_customuser WHERE role = 'borrower'")
        borrower_count = cursor.fetchone()['count']
        print(f"\n1. Borrowers in system: {borrower_count}")
        
        if borrower_count == 0:
            print("   ⚠️  NO BORROWERS FOUND!")
            print("   The new loan form needs at least one borrower to work")
        
        # Check if there are loan products
        cursor.execute("SELECT COUNT(*) as count FROM loans_loanproduct")
        product_count = cursor.fetchone()['count']
        print(f"\n2. Loan products: {product_count}")
        
        if product_count == 0:
            print("   ⚠️  NO LOAN PRODUCTS FOUND!")
            print("   The new loan form needs at least one loan product")
        
        # Check if there are branches
        cursor.execute("SELECT COUNT(*) as count FROM users_branch")
        branch_count = cursor.fetchone()['count']
        print(f"\n3. Branches: {branch_count}")
        
        if branch_count == 0:
            print("   ⚠️  NO BRANCHES FOUND!")
            print("   The system might require a branch")
        
        # Show sample borrowers
        if borrower_count > 0:
            cursor.execute("""
                SELECT id, first_name, last_name, phone_number 
                FROM users_customuser 
                WHERE role = 'borrower' 
                LIMIT 3
            """)
            borrowers = cursor.fetchall()
            print("\n4. Sample borrowers:")
            for b in borrowers:
                print(f"   - {b['first_name']} {b['last_name']} ({b['phone_number']})")
        
        # Show sample loan products
        if product_count > 0:
            cursor.execute("SELECT id, name, interest_rate FROM loans_loanproduct LIMIT 3")
            products = cursor.fetchall()
            print("\n5. Sample loan products:")
            for p in products:
                print(f"   - {p['name']} ({p['interest_rate']}%)")
    
    print("\n" + "="*60)
    print("DIAGNOSIS:")
    print("="*60)
    
    issues = []
    if borrower_count == 0:
        issues.append("❌ No borrowers - create borrowers first")
    if product_count == 0:
        issues.append("❌ No loan products - create products first")
    
    if issues:
        print("\n".join(issues))
        print("\nThe button probably fails because the form can't load")
        print("without borrowers or loan products.")
    else:
        print("✅ System has borrowers and products")
        print("\nIf button still doesn't work, check:")
        print("1. Browser console for JavaScript errors (F12)")
        print("2. Django error logs")
        print("3. Check if user has permission to create loans")
    
finally:
    conn.close()
