import pymysql
from decimal import Decimal

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

conn = pymysql.connect(**DB)
cur  = conn.cursor()

print("\n=== WHAT IS THE ACTUAL TOTAL DISBURSED IN GL? ===")
cur.execute("""
    SELECT COALESCE(SUM(l.debit_amount),0) total_disb
    FROM accounting_journal_entries e
    JOIN accounting_journal_entry_lines l ON l.journal_entry_id=e.id
    JOIN accounting_accounts a ON a.id=l.account_id
    WHERE e.reference_number LIKE 'DISB-%' AND a.code='1020'
""")
print(f"  GL DISB- debits to 1020: {Decimal(str(cur.fetchone()['total_disb'])):,.2f}")

print("\n=== TOTAL REPAYMENTS IN GL vs LOANS TABLE ===")
cur.execute("""
    SELECT COALESCE(SUM(l.credit_amount),0) total_rep
    FROM accounting_journal_entries e
    JOIN accounting_journal_entry_lines l ON l.journal_entry_id=e.id
    JOIN accounting_accounts a ON a.id=l.account_id
    WHERE e.reference_number LIKE 'REP-%' AND a.code='1020'
""")
gl_rep = Decimal(str(cur.fetchone()['total_rep']))
print(f"  GL REP- credits to 1020: {gl_rep:,.2f}")

cur.execute("SELECT COALESCE(SUM(amount),0) t FROM repayments")
actual_rep = Decimal(str(cur.fetchone()['t']))
print(f"  Actual repayments total: {actual_rep:,.2f}")
print(f"  Difference             : {abs(gl_rep - actual_rep):,.2f}")

print("\n=== REPAYMENTS WITH NO GL ENTRY ===")
cur.execute("""
    SELECT r.receipt_number, r.amount, r.payment_date
    FROM repayments r
    LEFT JOIN accounting_journal_entries e ON e.reference_number=CONCAT('REP-', r.receipt_number)
    WHERE e.id IS NULL
    ORDER BY r.payment_date DESC
    LIMIT 20
""")
rows = cur.fetchall()
print(f"  Count: {len(rows)}")
for r in rows:
    print(f"  {r['receipt_number']:30s}  KES {Decimal(str(r['amount'])):>10,.0f}  {str(r['payment_date'])[:10]}")

print("\n=== OLD INCOME ACCOUNTS WITH BALANCES (401xxx, 402xxx etc) ===")
cur.execute("""
    SELECT a.code, a.name,
           COALESCE(SUM(l.credit_amount),0)-COALESCE(SUM(l.debit_amount),0) balance
    FROM accounting_accounts a
    LEFT JOIN accounting_general_ledger l ON l.account_id=a.id
    WHERE a.account_type='income' AND a.code NOT LIKE '4%'
       OR (a.account_type='income' AND a.code LIKE '4%'
           AND (COALESCE((SELECT SUM(cr.credit_amount) FROM accounting_general_ledger cr WHERE cr.account_id=a.id),0) > 0))
    GROUP BY a.id, a.code, a.name
    HAVING balance != 0
    ORDER BY a.code
""")
for r in cur.fetchall():
    print(f"  {r['code']:10s}  {r['name'][:40]:40s}  KES {Decimal(str(r['balance'])):>12,.2f}")

print("\n=== ALL ACCOUNTS WITH NON-ZERO BALANCES ===")
cur.execute("""
    SELECT a.code, a.name, a.account_type,
           CASE WHEN a.account_type IN ('asset','expense')
                THEN COALESCE(SUM(l.debit_amount),0)-COALESCE(SUM(l.credit_amount),0)
                ELSE COALESCE(SUM(l.credit_amount),0)-COALESCE(SUM(l.debit_amount),0)
           END AS balance
    FROM accounting_accounts a
    LEFT JOIN accounting_general_ledger l ON l.account_id=a.id
    GROUP BY a.id, a.code, a.name, a.account_type
    HAVING ABS(balance) > 0.01
    ORDER BY a.account_type, a.code
""")
for r in cur.fetchall():
    print(f"  {r['code']:10s}  {r['account_type']:10s}  {r['name'][:38]:38s}  KES {Decimal(str(r['balance'])):>12,.2f}")

conn.close()
