# Special Access Links - Deployment Guide

## 🚀 Automatic Migration System

The Special Access Links feature includes an automatic migration system that creates the necessary database tables when the feature is first accessed.

## 📋 Prerequisites

- PHP 7.4 or higher
- MySQL 5.7 or higher
- Database user with CREATE, ALTER, and DROP permissions
- Existing Xchange_Admin database

## 🔧 Installation Methods

### Method 1: Automatic Setup (Recommended)

1. **Upload Files**: Upload all the special access links files to your server
2. **Access Feature**: Navigate to `admin/special-access-links.php`
3. **Auto-Migration**: The system will automatically create required tables

### Method 2: Manual Setup

1. **Run Setup Script**:
   ```bash
   php admin/setup_special_access_links.php
   ```

2. **Verify Installation**:
   ```bash
   php admin/migrations/migration_runner.php check special_access_links
   ```

### Method 3: CLI Migration

1. **Run Specific Migration**:
   ```bash
   php admin/migrations/special_access_links_migration.php up
   ```

2. **Check Status**:
   ```bash
   php admin/migrations/special_access_links_migration.php status
   ```

## 📁 Files to Deploy

### Core Files
- `admin/special-access-links.php` - Main feature page
- `admin/special-access-links.css` - Styling
- `admin/special-access-links.js` - JavaScript functionality
- `admin/special_access_links_api.php` - API endpoints

### Migration System
- `admin/migrations/special_access_links_migration.php` - Database migration
- `admin/migrations/migration_runner.php` - Migration runner
- `admin/auto_migrate.php` - Auto-migration system
- `admin/setup_special_access_links.php` - Setup script

### SQL Files (Optional - for manual setup)
- `sql/create_special_access_links.sql`
- `sql/add_referral_code_to_registrations.sql`
- `sql/add_custom_message_to_special_access_links.sql`

## 🗄️ Database Changes

The migration will create/modify:

### New Tables
- `special_access_links` - Stores special access link configurations
- `migrations` - Tracks applied migrations

### Modified Tables
- `registrations` - Adds `referral_code` column

### Indexes Created
- `idx_link_code` - Fast lookup by access code
- `idx_is_active` - Filter active links
- `idx_expires_at` - Filter by expiration
- `idx_referral_code` - Track referrals
- `idx_sal_active_expires` - Combined active/expired filter

## 🔍 Verification

### Check Tables Exist
```sql
SHOW TABLES LIKE 'special_access_links';
SHOW COLUMNS FROM registrations LIKE 'referral_code';
```

### Check Migration Status
```bash
php admin/migrations/migration_runner.php check special_access_links
```

### Test Feature
1. Navigate to `admin/special-access-links.php`
2. Create a test link
3. Verify link works with test URL

## 🛠️ Troubleshooting

### Common Issues

#### 1. Permission Denied
**Error**: `Access denied for user 'username'@'localhost'`
**Solution**: Grant CREATE, ALTER, DROP permissions to database user

#### 2. Table Already Exists
**Error**: `Table 'special_access_links' already exists`
**Solution**: This is normal if feature was previously installed

#### 3. Migration Failed
**Error**: Migration fails during execution
**Solution**: Check database logs and run rollback if needed

### Rollback Migration
```bash
php admin/migrations/special_access_links_migration.php down
```

### Manual Table Creation
If automatic migration fails, run the SQL files manually:
```bash
mysql -u username -p database_name < sql/create_special_access_links.sql
mysql -u username -p database_name < sql/add_referral_code_to_registrations.sql
```

## 🔄 Updates and Maintenance

### Adding New Migrations
1. Create new migration file: `admin/migrations/YYYY_MM_DD_feature_migration.php`
2. Follow the migration class structure
3. Run: `php admin/migrations/migration_runner.php run`

### Checking Migration History
```sql
SELECT * FROM migrations ORDER BY applied_at DESC;
```

## 📊 Monitoring

### Check Feature Status
```php
<?php
require_once 'admin/auto_migrate.php';

$status = AutoMigrate::getFeatureStatus('special_access_links');
echo "Tables exist: " . ($status['all_exist'] ? 'Yes' : 'No');
?>
```

### Database Health
```sql
-- Check table sizes
SELECT 
    table_name,
    ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'Size (MB)'
FROM information_schema.tables 
WHERE table_schema = 'your_database_name'
AND table_name IN ('special_access_links', 'registrations');
```

## 🚨 Troubleshooting

### Common Issues

#### Collation Mismatch Error
**Error**: `Illegal mix of collations (utf8mb4_general_ci,IMPLICIT) and (utf8mb4_unicode_ci,IMPLICIT)`

**Cause**: Database tables have different collations than expected.

**Solutions**:

1. **Run PHP Fix Script** (Recommended):
   ```bash
   php fix_sal_collation.php
   ```

2. **Run SQL Commands** (If no PHP CLI access):
   ```sql
   ALTER TABLE special_access_links CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
   ALTER TABLE migrations CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
   ```

3. **Full Database Fix** (If multiple tables affected):
   ```bash
   php fix_live_collation.php
   ```

## 🚨 Security Considerations

1. **Database Permissions**: Use minimal required permissions
2. **Migration Logs**: Monitor migration table for unauthorized changes
3. **Backup**: Always backup before running migrations
4. **Testing**: Test migrations on staging environment first

## 📞 Support

If you encounter issues:

1. Check error logs: `tail -f /var/log/apache2/error.log`
2. Verify database connection: `php admin/diagnose_env.php`
3. Check file permissions: `ls -la admin/migrations/`
4. Review migration status: `php admin/migrations/migration_runner.php check special_access_links`

## ✅ Post-Deployment Checklist

- [ ] Tables created successfully
- [ ] Feature page loads without errors
- [ ] Can create special access links
- [ ] Generated URLs work correctly
- [ ] Search functionality works
- [ ] Mobile responsive design
- [ ] Admin permissions working
- [ ] Error logging enabled
