<?php $title = 'Dynamic Forms'; ?>
<style>
.form-tabs { display: flex; gap: 0.5rem; margin-bottom: 1.5rem; border-bottom: 1px solid rgba(255,255,255,0.08); padding-bottom: 0; }
.form-tabs .tab-btn { padding: 0.6rem 1.5rem; border-radius: 10px 10px 0 0; cursor: pointer; border: none; background: transparent; color: rgba(255,255,255,0.5); font-weight: 600; transition: all 0.3s; border-bottom: 2px solid transparent; }
.form-tabs .tab-btn:hover { color: rgba(255,255,255,0.8); background: rgba(255,255,255,0.03); }
.form-tabs .tab-btn.active { color: #4e73df; border-bottom-color: #4e73df; background: rgba(78,115,223,0.08); }
.tab-content { display: none; }
.tab-content.active { display: block; }
.copy-btn { cursor: pointer; transition: color 0.2s; }
.copy-btn:hover { color: #1cc88a; }
</style>
<div class="d-sm-flex align-items-center justify-content-between mb-3">
    <h1 class="h3 mb-0 text-white font-weight-bold"><i class="fas fa-wpforms mr-2"></i>Forms</h1>
    <?php if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin'): ?>
    <div>
        <a href="<?= $baseUrl ?>/forms/create" class="glass-btn glass-btn-primary"><i class="fas fa-plus mr-1"></i>Create Form</a>
    </div>
    <?php endif; ?>
</div>

<div class="form-tabs">
    <button class="tab-btn active" data-tab="forms-tab"><i class="fas fa-wpforms mr-1"></i>Forms <span class="glass-badge ml-1" style="font-size: 0.7rem;"><?= count($forms) ?></span></button>
    <button class="tab-btn" data-tab="templates-tab"><i class="fas fa-file-alt mr-1"></i>Templates <span class="glass-badge ml-1" style="font-size: 0.7rem;"><?= count($templates) ?></span></button>
    <button class="tab-btn" data-tab="field-templates-tab"><i class="fas fa-cube mr-1"></i>Field Templates <span class="glass-badge ml-1" style="font-size: 0.7rem;"><?= count($fieldTemplates) ?></span></button>
</div>

<div id="forms-tab" class="tab-content active">
    <div class="row">
        <?php if (!empty($forms)): ?>
            <?php foreach ($forms as $form): ?>
            <div class="col-lg-4 col-md-6 mb-4">
                <div class="glass-card h-100">
                    <div class="text-center mb-3">
                        <i class="fas fa-wpforms fa-3x" style="color: #4e73df;"></i>
                    </div>
                    <h5 class="font-weight-bold text-center"><?= htmlspecialchars($form->title) ?></h5>
                    <?php if ($form->description): ?><p style="color: rgba(255,255,255,0.6); font-size: 0.9rem; text-align: center;"><?= htmlspecialchars($form->description) ?></p><?php endif; ?>
                    <div class="text-center mb-3">
                        <span class="glass-badge"><?= $form->submission_count ?? 0 ?> submissions</span>
                        <span class="glass-badge" style="background: <?= $form->is_active ? 'rgba(28,200,138,0.2)' : 'rgba(255,255,255,0.05)' ?>; color: <?= $form->is_active ? '#1cc88a' : 'rgba(255,255,255,0.4)' ?>;">
                            <?= $form->is_active ? 'Active' : 'Inactive' ?>
                        </span>
                    </div>
                    <div class="d-flex justify-content-center flex-wrap">
                        <a href="<?= $baseUrl ?>/forms/<?= $form->id ?>" class="glass-btn btn-sm mr-1 mb-1"><i class="fas fa-eye mr-1"></i>View</a>
                        <?php if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin'): ?>
                        <a href="<?= $baseUrl ?>/forms/<?= $form->id ?>/submissions" class="glass-btn btn-sm mr-1 mb-1"><i class="fas fa-list mr-1"></i>Data</a>
                        <a href="<?= $baseUrl ?>/forms/<?= $form->id ?>/edit" class="glass-btn btn-sm mr-1 mb-1"><i class="fas fa-edit"></i></a>
                        <a href="<?= $baseUrl ?>/forms/<?= $form->id ?>/share" class="glass-btn btn-sm mr-1 mb-1" title="Share"><i class="fas fa-share-alt"></i></a>
                        <form method="POST" action="<?= $baseUrl ?>/forms/<?= $form->id ?>/duplicate" style="display:inline;" class="mb-1">
                            <button type="submit" class="glass-btn btn-sm mr-1" title="Duplicate" onclick="return confirm('Duplicate this form?');"><i class="fas fa-copy"></i></button>
                        </form>
                        <button type="button" class="glass-btn btn-sm mb-1" data-toggle="modal" data-target="#saveTemplateModal<?= $form->id ?>" title="Save as Template"><i class="fas fa-save"></i></button>
                        <form method="POST" action="<?= $baseUrl ?>/forms/<?= $form->id ?>/delete" style="display:inline;" onsubmit="return confirm('Delete this form permanently?');">
                            <button type="submit" class="glass-btn btn-sm mb-1" style="border-color: rgba(231,74,59,0.3); color: #e74a3b;"><i class="fas fa-trash"></i></button>
                        </form>
                        <?php endif; ?>
                    </div>
                    <?php if ($form->source_form_id): ?>
                    <div class="text-center mt-2"><small style="color: rgba(255,255,255,0.3);"><i class="fas fa-code-branch mr-1"></i>Copied from form #<?= $form->source_form_id ?></small></div>
                    <?php endif; ?>
                </div>
            </div>
            <!-- Save as Template Modal -->
            <div class="modal fade" id="saveTemplateModal<?= $form->id ?>" tabindex="-1">
                <div class="modal-dialog"><div class="modal-content glass-modal-content">
                    <form method="POST" action="<?= $baseUrl ?>/forms/<?= $form->id ?>/save-template">
                        <div class="modal-header"><h5 class="modal-title">Save as Template</h5><button type="button" class="close" data-dismiss="modal">&times;</button></div>
                        <div class="modal-body">
                            <p style="color: rgba(255,255,255,0.7);">Save "<?= htmlspecialchars($form->title) ?>" as a reusable template.</p>
                            <div class="form-group">
                                <label style="color: rgba(255,255,255,0.7);">Template Name</label>
                                <input type="text" name="template_name" class="form-control glass-input" value="<?= htmlspecialchars($form->title) ?> Template" required>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="glass-btn" data-dismiss="modal">Cancel</button>
                            <button type="submit" class="glass-btn glass-btn-primary">Save Template</button>
                        </div>
                    </form>
                </div></div>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
        <div class="col-12"><div class="empty-state"><i class="fas fa-wpforms"></i><p>No forms yet. Click "Create Form" to get started.</p></div></div>
        <?php endif; ?>
    </div>
</div>

<div id="templates-tab" class="tab-content">
    <div class="row">
        <?php if (!empty($templates)): ?>
            <?php foreach ($templates as $tpl): ?>
            <div class="col-lg-4 col-md-6 mb-4">
                <div class="glass-card h-100" style="border-color: rgba(246,194,62,0.2);">
                    <div class="text-center mb-3">
                        <i class="fas fa-file-alt fa-3x" style="color: #f6c23e;"></i>
                    </div>
                    <h5 class="font-weight-bold text-center"><?= htmlspecialchars($tpl->template_name ?: $tpl->title) ?></h5>
                    <div class="text-center mb-3">
                        <span class="glass-badge" style="background: rgba(246,194,62,0.15); color: #f6c23e;">Template</span>
                        <span class="glass-badge" style="font-size: 0.75rem;">by <?= htmlspecialchars($tpl->created_by_name ?? 'Unknown') ?></span>
                    </div>
                    <div class="d-flex justify-content-center">
                        <a href="<?= $baseUrl ?>/forms/create?from_template=<?= $tpl->id ?>" class="glass-btn glass-btn-primary btn-sm mr-1"><i class="fas fa-plus mr-1"></i>Use Template</a>
                        <?php if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'admin'): ?>
                        <form method="POST" action="<?= $baseUrl ?>/forms/<?= $tpl->id ?>/delete-template" style="display:inline;" onsubmit="return confirm('Delete this template?');">
                            <button type="submit" class="glass-btn btn-sm" style="border-color: rgba(231,74,59,0.3); color: #e74a3b;"><i class="fas fa-trash"></i></button>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
        <div class="col-12"><div class="empty-state"><i class="fas fa-file-alt"></i><p>No templates saved yet. Save a form as a template to reuse it later.</p></div></div>
        <?php endif; ?>
    </div>
</div>

<div id="field-templates-tab" class="tab-content">
    <div class="d-flex justify-content-end mb-3">
        <button type="button" class="glass-btn glass-btn-primary" data-toggle="modal" data-target="#newFieldTemplateModal"><i class="fas fa-plus mr-1"></i>New Field Template</button>
    </div>
    <div class="row">
        <?php if (!empty($fieldTemplates)): ?>
            <?php foreach ($fieldTemplates as $ft): ?>
            <div class="col-lg-3 col-md-4 col-sm-6 mb-3">
                <div class="glass-card h-100" style="padding: 1rem;">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <span class="glass-badge" style="font-size: 0.7rem;"><?= htmlspecialchars(ucfirst($ft->field_type)) ?></span>
                            <h6 class="text-white font-weight-bold mt-1 mb-1 small"><?= htmlspecialchars($ft->name) ?></h6>
                            <small style="color: rgba(255,255,255,0.5);"><?= htmlspecialchars($ft->label) ?></small>
                        </div>
                        <form method="POST" action="<?= $baseUrl ?>/forms/field-templates/<?= $ft->id ?>/delete" style="display:inline;" onsubmit="return confirm('Delete this field template?');">
                            <button type="submit" class="btn btn-sm" style="color: #e74a3b; padding: 0;"><i class="fas fa-times"></i></button>
                        </form>
                    </div>
                    <div class="mt-2 copy-btn" onclick="copyFieldTemplate(<?= htmlspecialchars(json_encode($ft)) ?>)" style="color: rgba(255,255,255,0.4); font-size: 0.75rem;">
                        <i class="fas fa-copy mr-1"></i>Copy field config
                    </div>
                </div>
            </div>
            <?php endforeach; ?>
        <?php else: ?>
        <div class="col-12"><div class="empty-state"><i class="fas fa-cube"></i><p>No field templates yet. Save commonly used field configurations to speed up form building.</p></div></div>
        <?php endif; ?>
    </div>

    <!-- New Field Template Modal -->
    <div class="modal fade" id="newFieldTemplateModal" tabindex="-1">
        <div class="modal-dialog"><div class="modal-content glass-modal-content">
            <form method="POST" action="<?= $baseUrl ?>/forms/field-templates/store">
                <div class="modal-header"><h5 class="modal-title">New Field Template</h5><button type="button" class="close" data-dismiss="modal">&times;</button></div>
                <div class="modal-body">
                    <div class="form-group">
                        <label style="color: rgba(255,255,255,0.7);">Template Name</label>
                        <input type="text" name="name" class="form-control glass-input" placeholder="e.g. Full Name" required>
                    </div>
                    <div class="row">
                        <div class="col-md-6 form-group">
                            <label style="color: rgba(255,255,255,0.7);">Field Type</label>
                            <select name="field_type" class="form-control glass-input">
                                <option value="text">Text</option><option value="textarea">Textarea</option><option value="email">Email</option>
                                <option value="number">Number</option><option value="select">Select</option><option value="checkbox">Checkbox</option>
                                <option value="radio">Radio</option><option value="date">Date</option><option value="file">File</option><option value="url">URL</option>
                            </select>
                        </div>
                        <div class="col-md-6 form-group">
                            <label style="color: rgba(255,255,255,0.7);">Label</label>
                            <input type="text" name="label" class="form-control glass-input" placeholder="Field label" required>
                        </div>
                    </div>
                    <div class="form-group">
                        <label style="color: rgba(255,255,255,0.7);">Placeholder</label>
                        <input type="text" name="placeholder" class="form-control glass-input" placeholder="Placeholder text">
                    </div>
                    <div class="form-group">
                        <label style="color: rgba(255,255,255,0.7);">Options <small style="color: rgba(255,255,255,0.4);">(for select/radio, comma-separated)</small></label>
                        <input type="text" name="options" class="form-control glass-input" placeholder="Option 1, Option 2, Option 3">
                    </div>
                    <div class="custom-control custom-checkbox">
                        <input type="checkbox" class="custom-control-input" id="ft_required" name="is_required" value="1">
                        <label class="custom-control-label" for="ft_required" style="color: rgba(255,255,255,0.7);">Required</label>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="glass-btn" data-dismiss="modal">Cancel</button>
                    <button type="submit" class="glass-btn glass-btn-primary">Save Template</button>
                </div>
            </form>
        </div></div>
    </div>
</div>

<script>
$('.tab-btn').on('click', function() {
    $('.tab-btn').removeClass('active');
    $('.tab-content').removeClass('active');
    $(this).addClass('active');
    $('#' + $(this).data('tab')).addClass('active');
});

function copyFieldTemplate(ft) {
    var html = '<div class="field-row glass-card-dark mb-3"><div class="row"><div class="col-md-4 form-group"><label style="color:rgba(255,255,255,0.7);">Field Label</label><input type="text" name="field_label[]" class="form-control glass-input" value="' + $('<span>').text(ft.label).html() + '" required></div><div class="col-md-3 form-group"><label style="color:rgba(255,255,255,0.7);">Field Type</label><select name="field_type[]" class="form-control glass-input">';
    var types = ['text','textarea','email','phone','number','select','checkbox','radio','date','file','url'];
    types.forEach(function(t) { html += '<option value="' + t + '"' + (ft.field_type === t ? ' selected' : '') + '>' + t.charAt(0).toUpperCase() + t.slice(1) + '</option>'; });
    html += '</select></div><div class="col-md-3 form-group"><label style="color:rgba(255,255,255,0.7);">Placeholder / Options</label><input type="text" name="field_placeholder[]" class="form-control glass-input" value="' + $('<span>').text(ft.placeholder || '').html() + '" placeholder="Placeholder"><small style="color:rgba(255,255,255,0.4);">For select/radio: comma-separated</small></div><div class="col-md-2 form-group d-flex align-items-end"><div class="custom-control custom-checkbox"><input type="checkbox" class="custom-control-input" id="ft_cp_' + Date.now() + '" name="field_required[]" value="1"' + (ft.is_required ? ' checked' : '') + '><label class="custom-control-label" for="ft_cp_' + Date.now() + '" style="color:rgba(255,255,255,0.7);">Required</label></div><button type="button" class="btn btn-sm btn-danger ml-2" onclick="this.closest(\'.field-row\').remove()"><i class="fas fa-times"></i></button></div></div></div>';
    $('.tab-btn[data-tab="forms-tab"]').click();
    $('#fieldsContainer').append(html);
    $.notify ? $.notify('Field template added', 'success') : alert('Field template added. Scroll down to see it.');
}
</script>
