# Special Access Links - Implementation Guide

## 🎯 Overview

The Special Access Links feature allows administrators to create custom URLs that provide exclusive access to hidden products in the registration system. This is perfect for:

- **VIP Access**: Special pricing or exclusive products for sponsors
- **Partner Programs**: Custom registration options for partner organizations
- **Time-Limited Offers**: Temporary access to special products
- **Targeted Marketing**: Different product offerings for different audiences

## 📋 Features

### ✅ Admin Features
- Create unlimited special access links
- Select specific products to show (including normally hidden products)
- Choose whether to also show regular visible products
- Set optional expiration dates
- Track access analytics (views, conversions, conversion rates)
- Enable/disable links without deleting them
- Auto-generate or create custom link codes
- View detailed statistics and usage history

### ✅ Frontend Features
- Clean URL structure: `https://yourdomain.com/index.html?access=CODE`
- Visual indicator when accessing via special link
- Seamless integration with existing registration flow
- Products automatically filtered based on access link
- Session persistence across page navigation

### ✅ Tracking & Analytics
- Access count tracking
- Conversion tracking (completed registrations)
- Conversion rate calculation
- Last accessed timestamp
- Full audit trail with creator information

## 🚀 Installation Steps

### Step 1: Run Database Migrations

Execute these SQL files in order:

```bash
# 1. Create special access links table
sql/create_special_access_links.sql

# 2. Add referral code tracking to registrations
sql/add_referral_code_to_registrations.sql
```

### Step 2: Verify Files Created

Ensure these files exist:

**Admin Files:**
- `admin/special-access-links.php` - Main admin page
- `admin/special-access-links.css` - Page styling
- `admin/special-access-links.js` - Frontend JavaScript
- `admin/special_access_links_api.php` - Backend API

**Core Files Modified:**
- `api.php` - Added access parameter handling
- `registration.js` - Added access code detection
- `admin/includes/admin_nav.php` - Added navigation link

### Step 3: Verify Navigation

1. Log into admin panel
2. Navigate to **Pages → Special Access Links**
3. You should see the Special Access Links management page

## 📖 Usage Guide

### Creating a Special Access Link

1. **Navigate**: Go to **Pages → Special Access Links** in admin
2. **Click**: "Create New Link" button
3. **Fill Form**:
   - **Link Name**: Internal identifier (e.g., "VIP Sponsors 2025")
   - **Link Code**: URL code (e.g., "VIP2025") - or click Generate
   - **Description**: Optional notes about purpose/audience
   - **Select Products**: Choose which products to make accessible
   - **Include Visible Products**: Toggle to also show normal products
   - **Is Active**: Enable/disable the link
   - **Expiration Date**: Optional expiration (leave empty for no expiration)
4. **Save**: Click "Create Link"

### Using a Special Access Link

**Generated URL Format:**
```
https://yourdomain.com/index.html?access=VIP2025
```

**Sharing the Link:**
- Copy the full URL from the admin panel
- Share via email, social media, or embed in marketing materials
- Users clicking the link will see exclusive products

### Managing Links

**View Details:**
- Click the eye icon to see full link information
- View products included, access stats, and configuration

**Edit Link:**
- Click the edit icon to modify settings
- Change products, expiration, or other settings

**Toggle Status:**
- Click the toggle icon to enable/disable instantly
- Disabled links show "Link expired or invalid" message

**Delete Link:**
- Click the trash icon to permanently delete
- Confirmation required - action cannot be undone

### Tracking Performance

The admin dashboard shows:
- **Total Links**: Number of access links created
- **Active Links**: Currently enabled links
- **Total Accesses**: Number of times links were accessed
- **Conversions**: Completed registrations from special links

Individual link statistics:
- **Access Count**: Times the link was accessed
- **Conversions**: Registrations completed
- **Conversion Rate**: Percentage of accesses that converted
- **Last Accessed**: Most recent usage timestamp

## 🔧 Technical Details

### Database Schema

**special_access_links table:**
```sql
- id: Primary key
- link_code: Unique code for URL (e.g., VIP2025)
- link_name: Admin-friendly name
- description: Optional notes
- product_ids: JSON array of product IDs
- include_visible_products: Boolean (1=yes, 0=no)
- is_active: Boolean (1=active, 0=inactive)
- expires_at: Optional expiration datetime
- access_count: Number of accesses
- last_accessed_at: Last access timestamp
- conversion_count: Number of conversions
- created_by: Admin user ID
- created_at, updated_at: Timestamps
```

**registrations table modification:**
```sql
- referral_code: Special access link code used (nullable)
```

### API Flow

1. **User accesses special URL**: `?access=CODE`
2. **Frontend detects parameter**: Stored in sessionStorage
3. **API call includes access code**: `api.php?action=get_config&access=CODE`
4. **Backend validates link**:
   - Checks if link exists and is active
   - Checks if not expired
   - Tracks access (increments counter)
5. **Products filtered**:
   - Special products from link included
   - Normal visible products included if configured
6. **Registration stores referral code**: For conversion tracking

### Frontend Integration

**URL Parameter Detection:**
```javascript
const urlParams = new URLSearchParams(window.location.search);
const accessCode = urlParams.get('access');
```

**Session Persistence:**
```javascript
sessionStorage.setItem('xchange_access_code', accessCode);
```

**API Integration:**
```javascript
let apiUrl = 'api.php?action=get_config';
if (accessCode) {
    apiUrl += '&access=' + encodeURIComponent(accessCode);
}
```

**Visual Indicator:**
A purple gradient badge appears at the top when accessing via special link.

### Security Considerations

✅ **Implemented:**
- Server-side validation of access codes
- Expiration date checking
- Active status verification
- SQL injection protection (parameterized queries)
- XSS protection (HTML escaping)
- CSRF protection via admin authentication
- Permission-based access control

⚠️ **Considerations:**
- Link codes should be unique and non-guessable
- Consider rate limiting for production use
- Monitor for abuse via analytics
- Regularly review expired/inactive links

## 🎨 Customization

### Styling the Special Access Indicator

Edit `registration.js` → `showSpecialAccessIndicator()` method:

```javascript
indicator.innerHTML = `
    <div style="...your custom styles...">
        Your custom message
    </div>
`;
```

### Changing Link Code Format

Auto-generated codes use format: `SAL-XXXXXXXX`

To customize, edit `admin/special-access-links.js` → `generateLinkCode()`:

```javascript
function generateLinkCode() {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    let code = 'YOUR-PREFIX-'; // Customize prefix
    for (let i = 0; i < 8; i++) { // Customize length
        code += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    // ...
}
```

## 📊 Analytics & Reporting

### Available Metrics

1. **Access Analytics:**
   - Total accesses per link
   - Last accessed timestamp
   - Access patterns over time

2. **Conversion Analytics:**
   - Registrations completed
   - Conversion rate percentage
   - Revenue attribution (via total_amount)

### Custom Reports

Query example to get top-performing links:

```sql
SELECT 
    link_name,
    link_code,
    access_count,
    conversion_count,
    ROUND((conversion_count / access_count * 100), 2) as conversion_rate,
    SUM(r.total_amount) as total_revenue
FROM special_access_links sal
LEFT JOIN registrations r ON r.referral_code = sal.link_code
WHERE sal.access_count > 0
GROUP BY sal.id
ORDER BY conversion_count DESC
LIMIT 10;
```

## 🐛 Troubleshooting

### Issue: Link showing "Invalid or Expired"

**Possible causes:**
1. Link is inactive - Check and enable in admin
2. Link has expired - Update or remove expiration date
3. Link code typo - Verify exact code in URL
4. Database not updated - Run migration scripts

**Solution:**
```sql
-- Check link status
SELECT * FROM special_access_links WHERE link_code = 'YOUR_CODE';

-- Activate link
UPDATE special_access_links 
SET is_active = 1, expires_at = NULL 
WHERE link_code = 'YOUR_CODE';
```

### Issue: Products not showing

**Possible causes:**
1. Products not selected in link configuration
2. Products are inactive
3. Cache issue

**Solution:**
- Edit link and verify product selection
- Check products are active in Product Catalog
- Clear browser cache and try again

### Issue: Access count not incrementing

**Possible causes:**
1. Database connection issues
2. Permissions problem

**Solution:**
```sql
-- Verify table exists
SHOW TABLES LIKE 'special_access_links';

-- Check update permissions
-- User should have UPDATE privilege on special_access_links table
```

### Issue: Navigation link not appearing

**Possible causes:**
1. User doesn't have 'registrations' permission
2. Page variable not set correctly

**Solution:**
- Verify user role has 'registrations' permission
- Check `$currentPage` variable is set in page file

## 🔄 Upgrade Path

### From Basic Product Visibility

If migrating from basic `show_in_frontend` only:

1. Run database migrations
2. Existing hidden products remain hidden by default
3. Create special access links for exclusive access
4. Products can be visible normally AND in special links

### Future Enhancements

Potential additions:
- Password-protected links
- Usage limits (max number of uses)
- Geographic restrictions
- A/B testing capabilities
- Advanced analytics dashboard
- Bulk link creation
- Link templates

## 💡 Best Practices

### Link Code Naming

✅ **Good Examples:**
- `VIP2025` - Year-specific VIP access
- `SPONSOR-GOLD` - Sponsor tier identification
- `EARLYBIRD-DEC` - Time-limited early bird
- `PARTNER-ACME` - Partner-specific

❌ **Avoid:**
- `test` - Too generic
- `123` - Not descriptive
- `link1`, `link2` - Not meaningful

### Product Configuration

**Option A: Exclusive Access**
- Select only special products
- Uncheck "Include visible products"
- Use for: VIP-only offerings, exclusive deals

**Option B: Enhanced Access**
- Select special products
- Check "Include visible products"
- Use for: Standard + bonus options, tiered access

### Expiration Strategy

**Use expiration for:**
- Time-limited campaigns
- Seasonal offerings
- Early bird specials
- Event-specific registrations

**Don't use expiration for:**
- Permanent partner programs
- Ongoing VIP access
- Evergreen special offerings

### Monitoring

**Regular maintenance:**
- Review expired links monthly
- Archive or delete unused links
- Monitor conversion rates
- Analyze performance metrics
- Update product selections as needed

## 📞 Support & Documentation

### Related Documentation
- `NEW_PRODUCT_INTEGRATION_GUIDE.md` - Adding products
- `CONNECTED_PRODUCTS_GUIDE.md` - Product relationships
- `README.md` - General system documentation

### Activity Logs

All special access link operations are logged:
- Creation: `create_special_link`
- Updates: `update_special_link`
- Deletion: `delete_special_link`
- Status changes: `toggle_special_link`

View in admin activity logs.

---

## ✅ Quick Reference

**Admin URL:** `/admin/special-access-links.php`

**Frontend URL Format:** `/index.html?access=CODE`

**Required Permission:** `registrations`

**Database Tables:**
- `special_access_links`
- `registrations` (referral_code column)

**Key Files:**
- Admin: `special-access-links.php`, `.css`, `.js`, `_api.php`
- Core: `api.php`, `registration.js`

**Version:** 1.0.0
**Last Updated:** October 2025


