#!/usr/bin/env python
"""
Fix is_phone_verified Field
========================

This script adds the missing 'is_phone_verified' field to the users table
to fix the error: "Unable to create client: (1364, "Field 'is_phone_verified' doesn't have a default value")"
"""

import os
import sys
import django
from django.db import connection

def run_sql(sql, description=""):
    """Run SQL command directly"""
    print(f"\n{'='*60}")
    print(f"EXECUTING SQL: {description}")
    print(f"{'='*60}")
    print(f"SQL: {sql}")
    
    try:
        with connection.cursor() as cursor:
            cursor.execute(sql)
            if cursor.description:
                results = cursor.fetchall()
                for row in results:
                    print(row)
                return True, results
            else:
                print("SQL executed successfully")
                return True, None
    except Exception as e:
        print(f"ERROR: {e}")
        return False, str(e)

def main():
    print("""
    ╔══════════════════════════════════════════════════════════════╗
    ║                FIX IS_PHONE_VERIFIED FIELD                  ║
    ║                                                              ║
    ║  This script adds the missing 'is_phone_verified' field      ║
    ║  to the users table with a default value of False.          ║
    ╚══════════════════════════════════════════════════════════════╝
    
    """)
    
    # Check if we're in the right directory
    if not os.path.exists('manage.py'):
        print("ERROR: This script must be run from the Django project root directory")
        sys.exit(1)
    
    print("✓ Django project detected")
    
    # Setup Django
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
    django.setup()
    
    # Step 1: Check if the field exists
    print("\n" + "="*60)
    print("STEP 1: CHECKING IF is_phone_verified FIELD EXISTS")
    print("="*60)
    
    check_field_sql = """
    SELECT COLUMN_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
    AND TABLE_NAME = 'users' 
    AND COLUMN_NAME = 'is_phone_verified';
    """
    
    success, results = run_sql(check_field_sql, "Checking if is_phone_verified field exists")
    
    if success and results and len(results) > 0:
        print("✓ is_phone_verified field already exists")
        sys.exit(0)
    
    # Step 2: Add the missing field
    print("\n" + "="*60)
    print("STEP 2: ADDING is_phone_verified FIELD")
    print("="*60)
    
    add_field_sql = """
    ALTER TABLE users 
    ADD COLUMN is_phone_verified TINYINT(1) NOT NULL DEFAULT 0;
    """
    
    success, _ = run_sql(add_field_sql, "Adding is_phone_verified field with default value of 0 (False)")
    
    if success:
        print("✓ is_phone_verified field added successfully")
    else:
        print("✗ Failed to add is_phone_verified field")
        sys.exit(1)
    
    # Step 3: Verify the field was added
    print("\n" + "="*60)
    print("STEP 3: VERIFYING is_phone_verified FIELD")
    print("="*60)
    
    verify_field_sql = """
    SELECT COLUMN_NAME, COLUMN_DEFAULT, IS_NULLABLE, DATA_TYPE 
    FROM INFORMATION_SCHEMA.COLUMNS 
    WHERE TABLE_SCHEMA = DATABASE() 
    AND TABLE_NAME = 'users' 
    AND COLUMN_NAME = 'is_phone_verified';
    """
    
    success, results = run_sql(verify_field_sql, "Verifying is_phone_verified field")
    
    if success and results and len(results) > 0:
        print("✓ is_phone_verified field verified")
        print("\n🎉 FIX SUCCESSFUL! 🎉")
        print("\nThe 'is_phone_verified' field has been added to the users table with a default value of False.")
        print("You should now be able to create clients without the error.")
    else:
        print("✗ Failed to verify is_phone_verified field")
        sys.exit(1)

if __name__ == "__main__":
    main()