<?php
$db = getDB();
$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['update_status'])) {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $message = 'Invalid security token.';
    } else {
        $reg_id = $_POST['reg_id'] ?? '';
        $status = $_POST['status'] ?? 'pending';
        $stmt = $db->prepare("UPDATE workshop_registrations SET status=? WHERE id=?");
        $stmt->execute([$status, $reg_id]);
        $message = 'Registration status updated successfully.';
    }
}

$registrations = $db->query("SELECT wr.*, w.title as workshop_title FROM workshop_registrations wr LEFT JOIN workshops w ON wr.workshop_id = w.id ORDER BY wr.created_at DESC")->fetchAll();

include __DIR__ . '/admin_header.php';
?>

<div class="admin-topbar">
    <h2>Workshop Registrations</h2>
</div>

<?php if ($message): ?>
<div class="alert alert-success"><?= htmlspecialchars($message) ?></div>
<?php endif; ?>

<div class="admin-card">
    <h3>All Registrations</h3>
    <table>
        <thead>
            <tr><th>Workshop</th><th>Name</th><th>Email</th><th>Phone</th><th>Organization</th><th>Status</th><th>Date</th><th>Actions</th></tr>
        </thead>
        <tbody>
        <?php foreach ($registrations as $r): ?>
            <tr>
                <td><?= htmlspecialchars($r['workshop_title'] ?? 'N/A') ?></td>
                <td><?= htmlspecialchars($r['name']) ?></td>
                <td><?= htmlspecialchars($r['email']) ?></td>
                <td><?= htmlspecialchars($r['phone'] ?? '') ?></td>
                <td><?= htmlspecialchars($r['organization'] ?? '') ?></td>
                <td><?= htmlspecialchars($r['status']) ?></td>
                <td><?= htmlspecialchars($r['created_at']) ?></td>
                <td>
                    <form method="post" style="display:inline">
                        <?= csrfField() ?>
                        <input type="hidden" name="update_status" value="1">
                        <input type="hidden" name="reg_id" value="<?= $r['id'] ?>">
                        <select name="status" onchange="this.form.submit()" style="padding:4px;border-radius:4px;border:1px solid #ccc;">
                            <option value="pending" <?= $r['status'] === 'pending' ? 'selected' : '' ?>>Pending</option>
                            <option value="confirmed" <?= $r['status'] === 'confirmed' ? 'selected' : '' ?>>Confirmed</option>
                            <option value="cancelled" <?= $r['status'] === 'cancelled' ? 'selected' : '' ?>>Cancelled</option>
                        </select>
                    </form>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

<?php include __DIR__ . '/admin_footer.php'; ?>
