
<?php
add_shortcode('vacf_form','vacf_render');

function vacf_render($atts) {
    global $wpdb;
    $atts = shortcode_atts(['id'=>0],$atts);
    $form = $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}vacf_forms WHERE id=%d",$atts['id']
    ));
    if(!$form) return 'Form not found';

    $fields = json_decode($form->fields,true);
    ob_start(); ?>
    <form method="post" class="vacf-form">
        <input type="hidden" name="vacf_form_id" value="<?php echo $form->id; ?>">
        <?php foreach($fields as $f): ?>
            <input type="<?php echo esc_attr($f['type']); ?>"
                   name="<?php echo esc_attr($f['name']); ?>"
                   placeholder="<?php echo esc_attr($f['label']); ?>" required>
        <?php endforeach; ?>
        <button type="submit" name="vacf_submit">Send</button>
    </form>
    <?php
    if(isset($_POST['vacf_submit'])) vacf_submit($form,$fields);
    return ob_get_clean();
}

function vacf_submit($form,$fields) {
    global $wpdb;
    $data = [];
    foreach($fields as $f){
        $data[$f['label']] = sanitize_text_field($_POST[$f['name']]);
    }

    $wpdb->insert($wpdb->prefix.'vacf_submissions',[
        'form_id'=>$form->id,
        'data'=>maybe_serialize($data)
    ]);

    $rows = '';
    foreach($data as $k=>$v){ $rows .= "<p><b>$k:</b> $v</p>"; }

    $admin_html = str_replace('{{fields}}',$rows,$form->admin_template);
    $user_html = str_replace('{{fields}}',$rows,$form->user_template);

    add_filter('wp_mail_content_type', fn()=> 'text/html');
    wp_mail(get_option('admin_email'),'New Submission',$admin_html);
    wp_mail($_POST[array_key_first($_POST)],'Thank you',$user_html);
    remove_filter('wp_mail_content_type','__return_true');

    echo "<p class='vacf-success'>Form submitted successfully.</p>";
}
