<?php
/**
 * check_form.php
 *
 * This application will mark a quiz made with ACF
 * and update the user_meta with the scores
 *
 * @author Ash Davies <[email protected]>
 */


// Initiate WP
require_once('../../../wp-config.php');  
$wp->init();  
$wp->parse_request();  
$wp->query_posts();  
$wp->register_globals(); 

// Assign current post ID as variable
$current_post = $_POST['post_id'];

// Remove post_id from $_POST
if (array_key_exists('post_id', $_POST)) {
	unset($_POST['post_id']);
}

/**
 * Master array; multidimensional; 
 * This array stores the question as the key, and the answers as values
 *
 * Proposed Structure:
 * 
 * - question 		[str] 		( e.g. 'Is the sky blue?' )
 * - - correct 		[bool(int)] ( e.g. 0 = False, 1 = True )
 * - - chosen 		[bool(int)]	( See above )
 * 
 * @var array
 */
$q_and_a = array();


// Loop through $_POST data
foreach ($_POST as $question => $answer) { // --- $answer is User's answer NOT default answer

	// Replace '_' with ' ' for each question
	$question_edit = str_replace('_', ' ', $question);

	// Query DB for meta_key of current question
	$questions =   "SELECT meta_key
					FROM wp_postmeta
					WHERE post_id = '" . $current_post . "'
					and meta_value = '" . $question_edit . "';";

	$question_meta = $wpdb->get_row($questions,ARRAY_A);

	$question_meta_key = $question_meta['meta_key'];

	// Swap the question key for a default answer key
	//
	// $subject is the original string
	// $search is the thing you want to replace
	// $replace is what you want to replace it with
	$subject = $question_meta_key;
	$search = 'question';
	$replace = 'correct_answer';

	$question_meta_edit = substr_replace($subject, $replace, strrpos($subject, $search), strlen($search));

	// Query DB for value of default answer using key
	$answers = "SELECT meta_value
				FROM wp_postmeta
				WHERE post_id = '" . $current_post . "'
				and meta_key = '" . $question_meta_edit . "';";

	$default_answer_meta = $wpdb->get_row($answers,ARRAY_A);

	// Collect variables again
	$question 		= $question_edit;
	$default_answer = $default_answer_meta['meta_value'];
	$their_answer	= $answer;

	$q_and_a[$question] = array(
		'correct'	=> $default_answer,
		'chosen'	=> $their_answer
	);
};

# Do stuff with the master array! '$q_and_a'