get_results( $wpdb->prepare( "SELECT fields FROM {$table} WHERE form_id = %d", $form_id ) ); // phpcs:ignore WordPress.DB $total = count( $rows ); if ( 0 === $total ) { echo '

' . esc_html__( 'No entries yet for this form.', 'phemightforms' ) . '

'; return; } /* translators: %d: total submission count. */ echo '

' . sprintf( esc_html__( 'Total submissions: %d', 'phemightforms' ), (int) $total ) . '

'; // Choice fields defined on the form (label + allowed choices). $registry = \PhemightForms\phemightforms()->fields; $choice_fields = []; foreach ( $form->get_fields() as $field ) { if ( isset( $field['type'] ) && $registry->has_choices( $field['type'] ) ) { $choice_fields[ $field['label'] ] = [ 'choices' => isset( $field['choices'] ) ? $field['choices'] : [], 'counts' => [], ]; } } // Tally answers from the stored entries. $quiz_scores = []; foreach ( $rows as $row ) { $data = json_decode( $row->fields, true ); if ( ! is_array( $data ) ) { continue; } foreach ( $data as $item ) { $label = isset( $item['label'] ) ? $item['label'] : ''; if ( isset( $item['type'] ) && 'quiz' === $item['type'] ) { $quiz_scores[] = $item['value']; continue; } if ( ! isset( $choice_fields[ $label ] ) ) { continue; } $values = array_map( 'trim', explode( ',', (string) $item['value'] ) ); foreach ( $values as $value ) { if ( '' === $value ) { continue; } if ( ! isset( $choice_fields[ $label ]['counts'][ $value ] ) ) { $choice_fields[ $label ]['counts'][ $value ] = 0; } $choice_fields[ $label ]['counts'][ $value ]++; } } } // Quiz summary. if ( $quiz_scores ) { self::render_quiz_summary( $quiz_scores ); } // Choice charts. foreach ( $choice_fields as $label => $info ) { echo '
'; echo '

' . esc_html( $label ) . '

'; $labels_to_show = ! empty( $info['choices'] ) ? $info['choices'] : array_keys( $info['counts'] ); foreach ( $labels_to_show as $choice ) { $count = isset( $info['counts'][ $choice ] ) ? $info['counts'][ $choice ] : 0; $pct = $total > 0 ? round( ( $count / $total ) * 100 ) : 0; ?>
'; } } /** * Render quiz score statistics. * * @param array $scores Array of "x / y" strings. */ private static function render_quiz_summary( array $scores ) { $total_pct = 0; $counted = 0; foreach ( $scores as $score ) { if ( preg_match( '/(\d+)\s*\/\s*(\d+)/', $score, $m ) && (int) $m[2] > 0 ) { $total_pct += ( (int) $m[1] / (int) $m[2] ) * 100; $counted++; } } $avg = $counted > 0 ? round( $total_pct / $counted ) : 0; echo '
'; echo '

' . esc_html__( 'Quiz results', 'phemightforms' ) . '

'; /* translators: %d: average quiz score percentage. */ echo '

' . sprintf( esc_html__( 'Average score: %d%%', 'phemightforms' ), (int) $avg ) . '

'; echo '
'; } }