#!/usr/bin/env python3
import os
import sys
import django

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings_production')
django.setup()

from django.db import connection

print("Fixing receipts table...")

with connection.cursor() as cursor:
    # Add missing columns to receipts table
    columns = [
        'repayment_id CHAR(32) NULL',
        'loan_id CHAR(32) NULL', 
        'borrower_id CHAR(32) NULL',
        'amount_paid DECIMAL(12,2) NULL',
        'payment_method VARCHAR(20) NULL',
        'payment_date DATETIME(6) NULL',
        'previous_balance DECIMAL(12,2) NULL',
        'new_balance DECIMAL(12,2) NULL',
        'pdf_file VARCHAR(100) NULL',
        'created_at DATETIME(6) NULL'
    ]
    
    for col in columns:
        try:
            cursor.execute(f"ALTER TABLE receipts ADD COLUMN {col}")
            print(f"Added: {col.split()[0]}")
        except:
            print(f"OK: {col.split()[0]} exists")
    
    # Create repayments table
    try:
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS repayments (
                id CHAR(32) NOT NULL PRIMARY KEY,
                loan_id CHAR(32) NOT NULL,
                amount DECIMAL(12,2) NOT NULL,
                payment_method VARCHAR(20) NOT NULL DEFAULT 'mpesa',
                mpesa_transaction_id VARCHAR(50) NULL,
                mpesa_phone_number VARCHAR(17) NULL,
                receipt_number VARCHAR(20) NOT NULL UNIQUE,
                payment_date DATETIME(6) NOT NULL,
                created_at DATETIME(6) DEFAULT CURRENT_TIMESTAMP(6)
            )
        """)
        print("Repayments table ready")
    except Exception as e:
        print(f"Repayments: {e}")

print("Fix completed!")