#!/bin/bash

# Quick fix script for cPanel production database schema issue
# This script is non-interactive and handles the unassigned_date column issue

echo "🔧 Fixing database schema for cPanel production..."
echo "=================================================="

# Navigate to project directory (adjust path as needed)
cd /home/yourusername/public_html/branch-system  # Replace 'yourusername' with actual username

# Check if we're in the right directory
if [ ! -f "manage.py" ]; then
    echo "❌ Error: manage.py not found. Please check the project path."
    exit 1
fi

echo "✅ Found Django project"

# Check if unassigned_date column exists
echo "Checking database schema..."
python3 -c "
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
django.setup()

from django.db import connection
with connection.cursor() as cursor:
    cursor.execute(\"\"\"
        SELECT COLUMN_NAME 
        FROM INFORMATION_SCHEMA.COLUMNS 
        WHERE TABLE_SCHEMA = DATABASE() 
        AND TABLE_NAME = 'portfolio_assignments' 
        AND COLUMN_NAME = 'unassigned_date'
    \"\"\")
    result = cursor.fetchone()
    if result:
        print('✅ unassigned_date column already exists')
    else:
        print('Adding unassigned_date column...')
        cursor.execute(\"\"\"
            ALTER TABLE portfolio_assignments 
            ADD COLUMN unassigned_date DATETIME NULL
        \"\"\")
        print('✅ Column added successfully!')
"

# Mark migration as applied
echo "Marking migration as applied..."
python3 manage.py migrate users 0018 --fake --noinput

echo ""
echo "🎉 Database schema fix completed successfully!"
echo "The client assignment interface should now work properly."
