<h2>Manage Contact Assignments</h2>


<!-- ✅ ADD SEARCH UI HERE -->
<form method="GET" action="<?= BASE_URL ?>/contacts/manageAssignments" style="margin-bottom: 1rem;">
    <input type="text" name="q" placeholder="Search name/email" value="<?= htmlspecialchars($_GET['q'] ?? '') ?>">
    
    <select name="agent">
        <option value="">All agents</option>
        <?php foreach ($agents as $agent): ?>
            <option value="<?= $agent['id'] ?>" <?= ($_GET['agent'] ?? '') == $agent['id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($agent['name']) ?>
            </option>
        <?php endforeach; ?>
    </select>

    <button type="submit">Search</button>
</form>

<table border="1" cellpadding="8" cellspacing="0">
    <thead>
        <tr>
            <th>Name</th>
            <th>Email</th>
            <th>Current Agent</th>
            <th>Reassign / Unassign</th>
        </tr>
    </thead>
    <tbody>
        <?php foreach ($contacts as $contact): ?>
        <tr>
            <td><?= htmlspecialchars($contact['name']) ?></td>
            <td><?= htmlspecialchars($contact['email']) ?></td>
            <td><?= htmlspecialchars($contact['assigned_name'] ?? '—') ?></td>
            <td>
                <form method="POST" action="<?= BASE_URL ?>/contacts/manageAssignments">
                    <input type="hidden" name="contact_id" value="<?= $contact['id'] ?>">
                    <select name="agent_id">
                        <option value="">-- Unassign --</option>
                        <?php foreach ($agents as $agent): ?>
                            <option value="<?= $agent['id'] ?>" <?= $contact['assigned_user_id'] == $agent['id'] ? 'selected' : '' ?>>
                                <?= htmlspecialchars($agent['name']) ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <button type="submit">Update</button>
                </form>
            </td>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>

<p><a href="<?= BASE_URL ?>/DashboardController/admin">Back to Dashboard</a></p>

