<section class="grid two">
    <div class="card">
        <h2><?= !empty($editTemplate) ? 'Edit Template' : 'Create Template' ?></h2>
        <form method="post" action="index.php?route=templates/save" enctype="multipart/form-data">
            <?= csrf_input() ?>
            <div class="form-grid">
                <input type="hidden" name="id" value="<?= (int)($editTemplate['id'] ?? 0) ?>">
                <input name="name" placeholder="Template Name" value="<?= e($editTemplate['name'] ?? '') ?>" required>
                <select name="type" required>
                    <option value="sms" <?= (($editTemplate['type'] ?? '') === 'sms') ? 'selected' : '' ?>>SMS/MMS</option>
                    <option value="email" <?= (($editTemplate['type'] ?? '') === 'email') ? 'selected' : '' ?>>Email</option>
                </select>
                <input name="subject" placeholder="Email Subject (optional for SMS)" value="<?= e($editTemplate['subject'] ?? '') ?>">
            </div>
            <textarea name="body" rows="10" placeholder="Use variables like {{first_name}}, {{company}}, {{unsubscribe_url}}" required><?= e($editTemplate['body'] ?? '') ?></textarea>
            <label class="mt-12">Optional media or attachment</label>
            <input type="file" name="media_file">
            <div class="actions-cell">
                <button class="btn primary"><?= !empty($editTemplate) ? 'Update Template' : 'Save Template' ?></button>
                <?php if (!empty($editTemplate)): ?><a class="btn secondary" href="index.php?route=templates/index">Cancel Edit</a><?php endif; ?>
            </div>
        </form>
    </div>
    <div class="card">
        <h2>Saved Templates</h2>
        <table>
            <thead><tr><th>Name</th><th>Type</th><th>Subject</th><th>Media</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($templates as $template): ?>
                <tr>
                    <td><?= e($template['name']) ?></td>
                    <td><?= e(strtoupper($template['type'])) ?></td>
                    <td><?= e($template['subject']) ?></td>
                    <td><?= e($template['media_path']) ?></td>
                    <td class="actions-cell"><a class="btn secondary small" href="index.php?route=templates/index&edit=<?= (int)$template['id'] ?>">Edit</a> <a class="btn danger small" href="index.php?route=templates/delete&id=<?= (int)$template['id'] ?>" onclick="return confirm('Delete template?')">Delete</a></td>
                </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</section>
