<?php
/**
 * Database Migration: Create invitation tokens table
 * This provides a more secure alternative to simple access codes
 */

require_once __DIR__ . '/../config/database.php';

$conn = getDBConnection();

echo "<h2>Creating Invitation Tokens System</h2>";

// Create invitation_tokens table
$create_table = "CREATE TABLE IF NOT EXISTS invitation_tokens (
    id INT AUTO_INCREMENT PRIMARY KEY,
    token VARCHAR(64) UNIQUE NOT NULL,
    user_type ENUM('instructor', 'admin') NOT NULL,
    created_by INT DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    expires_at TIMESTAMP NULL,
    used_by INT DEFAULT NULL,
    used_at TIMESTAMP NULL,
    is_active BOOLEAN DEFAULT TRUE,
    max_uses INT DEFAULT 1,
    use_count INT DEFAULT 0,
    notes TEXT,
    INDEX idx_token (token),
    INDEX idx_user_type (user_type),
    INDEX idx_is_active (is_active),
    FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL,
    FOREIGN KEY (used_by) REFERENCES users(id) ON DELETE SET NULL
)";

if ($conn->query($create_table)) {
    echo "<p style='color: green;'>✓ invitation_tokens table created successfully</p>";
} else {
    echo "<p style='color: red;'>✗ Error creating table: " . $conn->error . "</p>";
}

// Create function to generate invitation tokens
echo "<p>Creating helper functions...</p>";

echo "<h3>Usage Instructions:</h3>";
echo "<ul>";
echo "<li>Use <code>generate_invitation_token.php</code> to create new invitation tokens</li>";
echo "<li>Tokens are more secure than simple access codes</li>";
echo "<li>Tokens can expire and have usage limits</li>";
echo "<li>Track who used which token</li>";
echo "</ul>";

echo "<p><a href='../index.php'>Back to Home</a></p>";

$conn->close();
?>
