<?php
/**
 * Generate Invitation Token
 * Admin interface to create secure invitation tokens for instructors/admins
 */

session_start();
require_once '../config/database.php';

// Check if user is admin
if (!isset($_SESSION['user_id']) || $_SESSION['user_type'] !== 'admin') {
    header('Location: ../index.php');
    exit();
}

$conn = getDBConnection();

// Handle token generation
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['generate_token'])) {
    $user_type = $_POST['user_type'];
    $expires_hours = intval($_POST['expires_hours']);
    $max_uses = intval($_POST['max_uses']);
    $notes = trim($_POST['notes']);

    // Generate secure random token
    $token = bin2hex(random_bytes(32));

    // Calculate expiration
    $expires_at = null;
    if ($expires_hours > 0) {
        $expires_at = date('Y-m-d H:i:s', time() + ($expires_hours * 3600));
    }

    $stmt = $conn->prepare("INSERT INTO invitation_tokens (token, user_type, created_by, expires_at, max_uses, notes) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->bind_param("ssisss", $token, $user_type, $_SESSION['user_id'], $expires_at, $max_uses, $notes);

    if ($stmt->execute()) {
        $success_message = "Token generated successfully!";
        $generated_token = $token;
    } else {
        $error_message = "Error generating token: " . $stmt->error;
    }

    $stmt->close();
}

// Fetch existing tokens
$tokens_query = "SELECT t.*, u.username as created_by_username, uu.username as used_by_username
                 FROM invitation_tokens t
                 LEFT JOIN users u ON t.created_by = u.id
                 LEFT JOIN users uu ON t.used_by = uu.id
                 ORDER BY t.created_at DESC";
$tokens_result = $conn->query($tokens_query);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Generate Invitation Token - Admin Panel</title>
    <link rel="stylesheet" href="../assets/css/style.css">
    <style>
        .token-container {
            max-width: 1200px;
            margin: 20px auto;
            padding: 20px;
        }
        .token-form {
            background: white;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 30px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .form-group {
            margin-bottom: 15px;
        }
        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group input, .form-group select, .form-group textarea {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        .generated-token {
            background: #f0f8ff;
            padding: 15px;
            border-radius: 4px;
            margin: 15px 0;
            border: 2px solid #4CAF50;
        }
        .token-code {
            font-family: monospace;
            background: #333;
            color: #0f0;
            padding: 10px;
            border-radius: 4px;
            word-break: break-all;
            margin: 10px 0;
        }
        .tokens-table {
            width: 100%;
            background: white;
            border-collapse: collapse;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .tokens-table th, .tokens-table td {
            padding: 12px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .tokens-table th {
            background: #4CAF50;
            color: white;
        }
        .status-active { color: #4CAF50; }
        .status-used { color: #ff9800; }
        .status-expired { color: #f44336; }
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }
        .btn-primary {
            background: #4CAF50;
            color: white;
        }
        .btn-secondary {
            background: #666;
            color: white;
        }
        .alert {
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 4px;
        }
        .alert-success {
            background: #d4edda;
            color: #155724;
            border: 1px solid #c3e6cb;
        }
        .alert-error {
            background: #f8d7da;
            color: #721c24;
            border: 1px solid #f5c6cb;
        }
    </style>
</head>
<body>
    <div class="token-container">
        <h1>Generate Invitation Token</h1>
        <p><a href="dashboard.php">← Back to Dashboard</a></p>

        <?php if (isset($success_message)): ?>
            <div class="alert alert-success">
                <?php echo htmlspecialchars($success_message); ?>
            </div>
            <div class="generated-token">
                <h3>Your New Invitation Token:</h3>
                <div class="token-code"><?php echo htmlspecialchars($generated_token); ?></div>
                <p><strong>Share this token with the person you want to invite.</strong></p>
                <p>They should use this token instead of the access code during registration.</p>
                <button class="btn btn-secondary" onclick="copyToken()">Copy Token</button>
            </div>
            <script>
                function copyToken() {
                    const token = '<?php echo $generated_token; ?>';
                    navigator.clipboard.writeText(token).then(() => {
                        alert('Token copied to clipboard!');
                    });
                }
            </script>
        <?php endif; ?>

        <?php if (isset($error_message)): ?>
            <div class="alert alert-error">
                <?php echo htmlspecialchars($error_message); ?>
            </div>
        <?php endif; ?>

        <div class="token-form">
            <h2>Generate New Token</h2>
            <form method="POST">
                <div class="form-group">
                    <label for="user_type">User Type:</label>
                    <select name="user_type" id="user_type" required>
                        <option value="instructor">Instructor</option>
                        <option value="admin">Admin</option>
                    </select>
                </div>

                <div class="form-group">
                    <label for="expires_hours">Expires After (hours):</label>
                    <input type="number" name="expires_hours" id="expires_hours" value="168" min="0" placeholder="0 = never expires">
                    <small>Default: 168 hours (7 days). Set to 0 for no expiration.</small>
                </div>

                <div class="form-group">
                    <label for="max_uses">Maximum Uses:</label>
                    <input type="number" name="max_uses" id="max_uses" value="1" min="1" required>
                    <small>How many times this token can be used (1 = single use)</small>
                </div>

                <div class="form-group">
                    <label for="notes">Notes (optional):</label>
                    <textarea name="notes" id="notes" rows="3" placeholder="E.g., 'Token for John Smith - Math Department'"></textarea>
                </div>

                <button type="submit" name="generate_token" class="btn btn-primary">Generate Token</button>
            </form>
        </div>

        <h2>Existing Tokens</h2>
        <table class="tokens-table">
            <thead>
                <tr>
                    <th>Token</th>
                    <th>Type</th>
                    <th>Created By</th>
                    <th>Created</th>
                    <th>Expires</th>
                    <th>Uses</th>
                    <th>Status</th>
                    <th>Notes</th>
                </tr>
            </thead>
            <tbody>
                <?php while ($token = $tokens_result->fetch_assoc()):
                    $is_expired = $token['expires_at'] && strtotime($token['expires_at']) < time();
                    $is_used_up = $token['use_count'] >= $token['max_uses'];
                    $status = 'Active';
                    $status_class = 'status-active';

                    if (!$token['is_active']) {
                        $status = 'Inactive';
                        $status_class = 'status-expired';
                    } elseif ($is_expired) {
                        $status = 'Expired';
                        $status_class = 'status-expired';
                    } elseif ($is_used_up) {
                        $status = 'Used';
                        $status_class = 'status-used';
                    }
                ?>
                <tr>
                    <td><code><?php echo substr(htmlspecialchars($token['token']), 0, 16); ?>...</code></td>
                    <td><?php echo htmlspecialchars($token['user_type']); ?></td>
                    <td><?php echo htmlspecialchars($token['created_by_username'] ?? 'System'); ?></td>
                    <td><?php echo date('Y-m-d H:i', strtotime($token['created_at'])); ?></td>
                    <td><?php echo $token['expires_at'] ? date('Y-m-d H:i', strtotime($token['expires_at'])) : 'Never'; ?></td>
                    <td><?php echo $token['use_count'] . '/' . $token['max_uses']; ?></td>
                    <td class="<?php echo $status_class; ?>"><?php echo $status; ?></td>
                    <td><?php echo htmlspecialchars($token['notes'] ?? ''); ?></td>
                </tr>
                <?php endwhile; ?>
            </tbody>
        </table>
    </div>
</body>
</html>

<?php $conn->close(); ?>
