#!/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 URL routing and page permissions...")

conn = pymysql.connect(**DB)
try:
    with conn.cursor() as cursor:
        # Check if there's a page_permissions table blocking the URL
        cursor.execute("SHOW TABLES LIKE 'page_permissions'")
        if cursor.fetchone():
            print("\n📋 Found page_permissions table")
            
            # Check for /loans/new or new_application restrictions
            cursor.execute("""
                SELECT * FROM page_permissions 
                WHERE url_pattern LIKE '%new%' OR url_pattern LIKE '%application%'
            """)
            perms = cursor.fetchall()
            
            if perms:
                print("\n⚠️  FOUND PAGE RESTRICTIONS:")
                for perm in perms:
                    print(f"\n   URL Pattern: {perm.get('url_pattern')}")
                    print(f"   Required Permissions: {perm.get('required_permissions')}")
                    print(f"   Is Active: {perm.get('is_active')}")
            else:
                print("   No restrictions on new application URLs")
        
        # Check user_page_permissions
        cursor.execute("SHOW TABLES LIKE 'user_page_permissions'")
        if cursor.fetchone():
            cursor.execute("""
                SELECT upp.*, u.username 
                FROM user_page_permissions upp
                JOIN users u ON upp.user_id = u.id
                WHERE u.username = 'admin'
            """)
            user_perms = cursor.fetchall()
            
            if user_perms:
                print(f"\n📋 Admin user has {len(user_perms)} page-level permissions")
            else:
                print("\n   Admin has no custom page permissions")
        
        print("\n" + "=" * 60)
        print("🔍 REAL ISSUE CHECK:")
        print("=" * 60)
        print("The button works locally but not in production...")
        print("Possible causes:")
        print("1. ❌ URL routing - Check loans/urls.py")
        print("2. ❌ Middleware blocking - Check MIDDLEWARE in settings")
        print("3. ❌ JavaScript intercepting - Check browser console")
        print("4. ❌ CSRF token issue - Form submission failing")
        
finally:
    conn.close()

print("\n💡 NEXT: Check the ACTUAL button HTML")
print("Does the button:")
print("  - Use <a href> or <form>?")
print("  - Have JavaScript onclick?")
print("  - Submit via AJAX?")
