<?php

// Get Forms List
function adfoin_arforms_get_forms( $form_provider ) {

    if( $form_provider != 'arforms' ) {
        return;
    }
    
    global $wpdb;
    $raw = $wpdb->get_results( "SELECT id, name FROM {$wpdb->prefix}arf_forms", ARRAY_A );
    $forms = wp_list_pluck( $raw, 'name', 'id' );

    return $forms;
}

// Get Form Fields
function adfoin_arforms_get_form_fields( $form_provider, $form_id ) {

    if( $form_provider != 'arforms' ) {
        return;
    }

    global $wpdb;
    $raw = $wpdb->get_results( $wpdb->prepare( "SELECT id, field_key, name, type FROM {$wpdb->prefix}arf_fields WHERE form_id = %d", $form_id ) );
    $fields = wp_list_pluck( $raw, 'name', 'id' );

    $fields['form_id']  = __( 'Form ID', 'advanced-form-integration' );

    $special_tags = adfoin_get_special_tags();

    if( is_array( $fields ) && is_array( $special_tags ) ) {
        $fields = $fields + $special_tags;
    }

    return $fields;
}

// Get Form Name
function adfoin_arforms_get_form_name( $form_id ) {
    global $wpdb;
    $form_name = $wpdb->get_var( $wpdb->prepare( "SELECT name FROM {$wpdb->prefix}arforms WHERE id = %d", $form_id ) );
    return $form_name;
}

add_action( 'arfliteentryexecute', 'adfoin_arforms_submission', 10, 4 );

add_action( 'arfentryexecute', 'adfoin_arforms_submission', 10, 4 );

function adfoin_arforms_submission( $params, $errors, $form, $item_meta_values ) {

    $form_id = $form->id;

    $integration = new Advanced_Form_Integration_Integration();
    $saved_records = $integration->get_by_trigger( 'arforms', $form_id );

    if( empty( $saved_records ) ) {
        return;
    }

    $posted_data = $item_meta_values;
    $post = adfoin_get_post_object();
    $special_tag_values = adfoin_get_special_tags_values( $post );

    if( is_array( $posted_data ) && is_array( $special_tag_values ) ) {
        $posted_data = $posted_data + $special_tag_values;
    }

    $posted_data = apply_filters( 'adfoin_arforms_submission', $posted_data, $form_id );

    $posted_data['form_id'] = $form_id;

    adfoin_dispatch_integrations( $saved_records, $posted_data );
}