
<?php
add_action('admin_menu', function() {
    add_menu_page('Contact Form Ultimate','Contact Form Ultimate','manage_options','vacf_ultimate','vacf_builder_page');
});

function vacf_builder_page() {
    global $wpdb;
    $table = $wpdb->prefix.'vacf_forms';

    if (isset($_POST['save_form'])) {
        $wpdb->insert($table, [
            'name' => sanitize_text_field($_POST['form_name']),
            'layout' => sanitize_text_field($_POST['layout']),
            'fields' => wp_kses_post($_POST['fields']),
            'admin_template' => wp_kses_post($_POST['admin_template']),
            'user_template' => wp_kses_post($_POST['user_template'])
        ]);
        echo '<div class="updated"><p>Form Saved</p></div>';
    }
    ?>
    <div class="wrap">
        <h2>Create Form (Drag & Drop)</h2>
        <form method="post">
            <input type="text" name="form_name" placeholder="Form Name" required><br><br>

            <select name="layout">
                <option value="one">One Column</option>
                <option value="two">Two Column</option>
            </select><br><br>

            <h3>Drag Fields</h3>
            <div id="vacf-fields">
                <button type="button" onclick="vacfAddField('text')">Text</button>
                <button type="button" onclick="vacfAddField('email')">Email</button>
                <button type="button" onclick="vacfAddField('phone')">Phone</button>
            </div>

            <textarea name="fields" id="vacf-fields-output" hidden></textarea>

            <h3>Admin Email Template (HTML)</h3>
            <textarea name="admin_template" rows="6" style="width:100%">
<h2>New Submission</h2>
{{fields}}
            </textarea>

            <h3>User Auto Responder (HTML)</h3>
            <textarea name="user_template" rows="6" style="width:100%">
<h2>Thank You</h2>
<p>We received your message.</p>
{{fields}}
            </textarea>

            <br><br>
            <button class="button-primary" name="save_form">Save Form</button>
        </form>

        <h3>Existing Forms</h3>
        <?php
        $forms = $wpdb->get_results("SELECT * FROM $table");
        foreach ($forms as $f) {
            echo "<p><b>{$f->name}</b> — <code>[vacf_form id='{$f->id}']</code></p>";
        }
        ?>
    </div>
    <?php
}
