<?php
require 'conn/codeblocs.php';


// return;
if(!empty($_POST)){

	$data = sanitizeData($_POST);
	// print_r( $data );
	// exit;

	$PDO->beginTransaction();
	// mysqli_autocommit($LINK, false);

	$response_batch = array(
		'response_batch_id'=>null,
		'survey_id'=>$data['survey_id'],
		'vendee_id'=>$data['survey_vendee_id'],
		'response_token'=>$data['survey_token']
	);

	
	$res1 = submitList($response_batch, 'survey_response_batch', '', ['response_batch_id'], true, '', 1);
	// print_r($res1);

	foreach($data['response_data'] as $q=>$a){
		$response_arr = [
			'response_id'=>null,
			'response_batch_id'=>$res1['id'],
			'question_id'=>$q,
			'response_data'=>$a
		];
		// preprint($response_arr);
		// continue;

		$res2 = submitList($response_arr, 'survey_responses', '', ['response_id'], true, '', 1);
		// print_r($res2);

	}

	// preprint(saw('response_id, question_id, response_data', 'survey_responses', 'response_id>41', 1));
	
	// EXIT;
	$PDO->commit();

	$vendee = SW('*', 'survey_vendee', 'vendee_id = ?', 1, 1, [$data['survey_vendee_id']]);
	$survey = SW('*', 'survey_instance', 'survey_id = ?', 1, 1, [$data['survey_id']]);
	// preprint($vendee);

	$mail_subject = 'Survey response received: '.$survey['survey_slug'];
	$mail_body = 'A new survey entry has been received<div style="font-weight:bold">'.$survey['survey_name'].'</div><div style="padding:2em 0"><a href="'.(DOC_BASE . APP_ROOT .'display').'/?sid='.$data['survey_id'].'&vid='.$data['survey_vendee_id'].'">View Submissions</a></div>';
	$recipient = $vendee['email'] ?? 'sp.mailer@gmail.com';
	$recipient_name = $vendee['short_vendee'];
	$sender = 'survey-noreply@swiftpractice.com';
	$sender_name = 'SP Survey';
	$smtp_id = 3;
	
	require 'phpmailer.php';
	send_email($sender, $sender_name, $recipient, $recipient_name, $mail_subject, $mail_body, 3);
	
	exit;
}
