<?php
if (!defined('ABSPATH')) exit;

$types = get_option('ipm_support_types', []);

if ($_SERVER['REQUEST_METHOD'] === 'POST' && check_admin_referer('ipm_save_support_types')) {
    $types = array_values($_POST['types'] ?? []);
    update_option('ipm_support_types', $types);
    echo '<div class="notice notice-success"><p>Saved</p></div>';
}
?>

<div class="wrap">
<h1>Support Types</h1>

<form method="post">
<?php wp_nonce_field('ipm_save_support_types'); ?>

<table class="widefat">
<thead>
<tr><th>Name</th><th>Status</th></tr>
</thead>
<tbody>
<?php foreach ($types as $i => $t): ?>
<tr>
<td><input name="types[<?= $i ?>][name]" value="<?= esc_attr($t['name']) ?>" required></td>
<td>
<select name="types[<?= $i ?>][status]">
<option value="active" <?= selected($t['status'], 'active') ?>>Active</option>
<option value="draft" <?= selected($t['status'], 'draft') ?>>Draft</option>
</select>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<p><button type="button" onclick="addRow()">+ Add</button></p>
<?php submit_button(); ?>
</form>
</div>

<script>
function addRow() {
    const tbody = document.querySelector('tbody');
    const i = tbody.children.length;
    tbody.insertAdjacentHTML('beforeend', `
        <tr>
            <td><input name="types[${i}][name]" required></td>
            <td>
                <select name="types[${i}][status]">
                    <option value="active">Active</option>
                    <option value="draft">Draft</option>
                </select>
            </td>
        </tr>
    `);
}
</script>
