<?php
// api/generate_token.php
require_once '../config/database.php';
require_once '../includes/functions.php';

session_start();
requireRole('roster_manager'); // Or admin

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = $_POST['type']; // 'registration' or 'update'
    $member_id = isset($_POST['member_id']) ? (int)$_POST['member_id'] : null;
    $expires_in = 48; // hours

    if ($type === 'update' && !$member_id) {
        die("Member ID required for update token");
    }

    $token = bin2hex(random_bytes(32));
    $expires_at = date('Y-m-d H:i:s', strtotime("+$expires_in hours"));
    
    $stmt = $pdo->prepare("INSERT INTO access_tokens (token, type, member_id, created_by, expires_at) VALUES (?, ?, ?, ?, ?)");
    if ($stmt->execute([$token, $type, $member_id, $_SESSION['user_id'] ?? null, $expires_at])) {
        // Return the URL
        $base_url = "http://" . $_SERVER['HTTP_HOST'] . dirname(dirname($_SERVER['PHP_SELF']));
        // Assuming public pages are in root or pages/
        // User wants "One-time-use URL". 
        // Let's route them to `public_form.php?token=...`
        $url = $base_url . "/pages/public_form.php?token=" . $token;
        
        echo json_encode(['success' => true, 'url' => $url]);
    } else {
        echo json_encode(['success' => false, 'message' => 'Failed to generate token']);
    }
}
?>
