# Production 500 Error Fix Guide

## Problem Identified
Your production database is missing critical tables:
- `users_customuser`
- `loans_loan`
- `loans_client` (model doesn't exist - this is OK)
- `loans_repayment`

The migrations show as applied but tables don't exist (migration state out of sync).

## Solution: Run on Production Server

### Step 1: Upload Scripts to Production
Upload these files to your production server via cPanel File Manager or FTP:
- `create_tables_directly.py`
- `fix_migration_conflict.py`

### Step 2: SSH into Production Server
```bash
ssh your_username@your_server
cd ~/public_html/branchbusinessadvance.co.ke
```

### Step 3: Activate Virtual Environment
```bash
source ~/virtualenv/public_html/branchbusinessadvance.co.ke/3.13/bin/activate
```

### Step 4: Run the Fix Script
```bash
python create_tables_directly.py
```

If that doesn't work, try this alternative:

### Alternative: Create Tables Manually via SQL

1. **Access cPanel phpMyAdmin**
2. **Select database**: `acbptxvs_branch_system`
3. **Run this SQL**:

```sql
-- Check what tables exist
SHOW TABLES LIKE '%customuser%';
SHOW TABLES LIKE '%loan%';

-- If users_customuser is missing, we need to create it
-- But first, let's see what migrations think exist
SELECT * FROM django_migrations WHERE app = 'users' ORDER BY id DESC LIMIT 5;
SELECT * FROM django_migrations WHERE app = 'loans' ORDER BY id DESC LIMIT 5;
```

### Step 5: Force Recreate Tables Using Django

SSH into production and run:

```bash
cd ~/public_html/branchbusinessadvance.co.ke
source ~/virtualenv/public_html/branchbusinessadvance.co.ke/3.13/bin/activate

# Reset migration state for problematic apps
python manage.py migrate users zero --fake
python manage.py migrate loans zero --fake

# Now reapply all migrations
python manage.py migrate users
python manage.py migrate loans
python manage.py migrate --run-syncdb
```

### Step 6: Quick Fix - If Above Doesn't Work

Create this script on production: `emergency_fix.py`

```python
import os
import sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'branch_system.settings')
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

import django
django.setup()

from django.core.management import call_command

print("Resetting migrations...")
call_command('migrate', 'users', 'zero', '--fake')
call_command('migrate', 'loans', 'zero', '--fake')

print("Reapplying migrations...")
call_command('migrate', 'users')
call_command('migrate', 'loans')
call_command('migrate')

print("Done!")
```

Run it:
```bash
python emergency_fix.py
```

### Step 7: Update Settings

Edit `branch_system/settings.py` or create `.env` file:

```bash
DEBUG=False
```

### Step 8: Restart Application

In cPanel:
1. Go to **Setup Python App**
2. Click **Restart** button for your application

Or via SSH:
```bash
touch ~/public_html/branchbusinessadvance.co.ke/tmp/restart.txt
```

Or restart Apache:
```bash
/scripts/restartsrv_httpd
```

### Step 9: Test

Visit your site: https://branchbusinessadvance.co.ke

If still getting 500 error, check logs:
```bash
tail -f ~/logs/error_log
```

## Why This Happened

1. Models changed but migrations weren't created/applied properly
2. Migration state in `django_migrations` table doesn't match actual database
3. Some migrations tried to delete tables that never existed

## Prevention

1. Always run `python manage.py makemigrations` after model changes
2. Always run `python manage.py migrate` before deploying
3. Test migrations on staging before production
4. Keep migration files in version control

## If Nothing Works

Last resort - manually create the CustomUser table:

```sql
-- This is a simplified version - adjust based on your actual model
CREATE TABLE users_customuser (
    id BIGINT AUTO_INCREMENT PRIMARY KEY,
    password VARCHAR(128) NOT NULL,
    last_login DATETIME(6),
    is_superuser TINYINT(1) NOT NULL,
    username VARCHAR(150) NOT NULL UNIQUE,
    first_name VARCHAR(150) NOT NULL,
    last_name VARCHAR(150) NOT NULL,
    email VARCHAR(254) NOT NULL,
    is_staff TINYINT(1) NOT NULL,
    is_active TINYINT(1) NOT NULL,
    date_joined DATETIME(6) NOT NULL,
    -- Add your custom fields here
    phone_number VARCHAR(20),
    role VARCHAR(20),
    branch_id CHAR(32)
);
```

Then fake the migrations:
```bash
python manage.py migrate users --fake
python manage.py migrate loans --fake
```
