# Media File Troubleshooting Guide

## Issue: Client Files Not Displaying on Website

### 🔍 Quick Diagnosis

1. **Check if media files exist:**
   - Visit: `https://branchbusinessadvance.co.ke/media/kyc/`
   - If you get a 404 error, the issue is with file serving
   - If you get a 403 error, the issue is with permissions

2. **Test media access:**
   - Visit: `https://branchbusinessadvance.co.ke/utils/test-media/`
   - This will show if Django can access media files

### 🛠️ Step-by-Step Fix

#### Step 1: Check File Structure
```bash
# In cPanel File Manager, navigate to your domain directory
# Check if these directories exist:
/media/
/media/kyc/
/media/kyc/bank_statements/
/media/kyc/id_documents/
/media/kyc/selfies/
/media/kyc/utility_bills/
```

#### Step 2: Check File Permissions
```bash
# In cPanel Terminal or SSH:
chmod 755 media/
chmod 755 media/kyc/
chmod 755 media/kyc/bank_statements/
chmod 755 media/kyc/id_documents/
chmod 755 media/kyc/selfies/
chmod 755 media/kyc/utility_bills/
chmod 644 media/kyc/**/*
```

#### Step 3: Update .htaccess
Make sure your `.htaccess` file contains:
```apache
# Handle media files - serve directly if file exists
RewriteCond %{REQUEST_URI} ^/media/
RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^media/(.*)$ media/$1 [L]

# Handle media files - fallback to Django if file doesn't exist
RewriteCond %{REQUEST_URI} ^/media/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^media/(.*)$ /passenger_wsgi.py/media/$1 [QSA,L]
```

#### Step 4: Check Django Settings
Ensure `settings_production.py` has:
```python
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
```

#### Step 5: Restart Web Server
In cPanel:
1. Go to "Software" → "Select PHP Version"
2. Click "Restart" or "Reload"
3. Or contact your hosting provider to restart Apache

### 🔧 Alternative Solutions

#### Solution 1: Use Django to Serve Media Files
If Apache isn't serving files, Django can handle it:

1. **Check if MediaFileMiddleware is enabled:**
   ```python
   # In settings_production.py
   MIDDLEWARE = [
       # ... other middleware
       'utils.middleware.MediaFileMiddleware',
   ]
   ```

2. **Test the middleware:**
   - Visit: `https://branchbusinessadvance.co.ke/utils/test-media/`
   - If it shows "SUCCESS", Django is serving files correctly

#### Solution 2: Create Symbolic Links
If files are in a different location:
```bash
# In cPanel Terminal
ln -s /path/to/actual/media /home/username/public_html/media
```

#### Solution 3: Use CDN or External Storage
For better performance, consider:
- AWS S3 for file storage
- CloudFlare for CDN
- Local file system with proper caching

### 🐛 Common Issues and Solutions

#### Issue 1: 404 Errors
**Cause:** Files don't exist or wrong path
**Solution:**
```bash
# Check if files exist
ls -la media/kyc/
# If empty, upload files or check upload functionality
```

#### Issue 2: 403 Forbidden
**Cause:** Wrong permissions
**Solution:**
```bash
# Set correct permissions
find media/ -type d -exec chmod 755 {} \;
find media/ -type f -exec chmod 644 {} \;
```

#### Issue 3: 500 Internal Server Error
**Cause:** Django error or middleware issue
**Solution:**
1. Check Django logs: `logs/django.log`
2. Temporarily disable MediaFileMiddleware
3. Check if passenger_wsgi.py is correct

#### Issue 4: Files Show as Text
**Cause:** Wrong MIME type
**Solution:**
```apache
# Add to .htaccess
<FilesMatch "\.(jpg|jpeg|png|gif|pdf)$">
    Header set Content-Type "image/jpeg"
</FilesMatch>
```

### 📋 Testing Checklist

- [ ] Media directory exists: `/media/`
- [ ] Subdirectories exist: `/media/kyc/`, `/media/kyc/bank_statements/`, etc.
- [ ] Files exist in directories
- [ ] File permissions are correct (755 for dirs, 644 for files)
- [ ] .htaccess is in root directory
- [ ] .htaccess has correct rewrite rules
- [ ] Web server is restarted
- [ ] Django settings are correct
- [ ] MediaFileMiddleware is working (test at `/utils/test-media/`)

### 🚨 Emergency Fix

If nothing else works, use this temporary solution:

1. **Create a simple media view:**
```python
# Add to utils/views.py
from django.http import FileResponse
import os

def serve_media_file(request, file_path):
    """Serve media files directly"""
    full_path = os.path.join(settings.MEDIA_ROOT, file_path)
    if os.path.exists(full_path):
        return FileResponse(open(full_path, 'rb'))
    else:
        from django.http import Http404
        raise Http404("File not found")
```

2. **Add URL pattern:**
```python
# In utils/urls.py
path('media/<path:file_path>/', views.serve_media_file, name='serve_media_file'),
```

3. **Update templates to use this URL:**
```html
<!-- Instead of {{ MEDIA_URL }}{{ file.name }} -->
{% url 'utils:serve_media_file' file_path=file.name %}
```

### 📞 Support

If you're still having issues:
1. Check cPanel error logs
2. Contact your hosting provider
3. Verify SSL certificate is working
4. Test with a simple HTML file first

### 🔄 Deployment Script

Run this script to automatically fix most issues:
```bash
# Upload and run the deployment script
chmod +x deploy_media_fix.sh
./deploy_media_fix.sh
```

This will:
- Create missing directories
- Set correct permissions
- Update .htaccess
- Test media access
- Collect static files
- Run migrations 