<?php

require realpath( __dir__ . '/../' ) . '/init.php';

$TCodes = $settings->get('transfer_codes');

if( isset($_POST['mail']) ):

	$key = $_POST['mail'];
	$codex = $TCodes[$key];
	
	$keyup = strtoupper($key);
	
	$json = help::get_json($__user['_json']);
	if( !isset($json['transfer_codes']) ) $json['transfer_codes'] = array();
	$json['transfer_codes'][$key] = $code = ($codex['code_type'] == 'static') ? $codex['code_value'] : help::generate_number(4);
	
	$code_updated = $link->query( sQuery::update( 'tbl_users', array("_json" => json_encode($json)), "id = {$__user['id']}" ) );
	
	if( !$code_updated ) {
		echo json_encode("{$keyup} Code could not be sent");
		exit;
	}
	
	$mailer = new mailer();
	$mailer->addAddress( $__user['email'] );
	$mailer->Subject = "{$keyup} Code";
	$mailer->Body = "
		<section>
			Your {$keyup} code is {$code}
		</section>
	";
	
	$sent = $mailer->send();
	$msg = $sent ? "{$keyup} code has been sent to your email" : "{$keyup} code not sent";
	
	echo json_encode([$msg]);
	
else:

	$_POST = help::sanitize($_POST);
	
	$key = $_POST['type'];
	$value = $_POST['code'];
	
	if( $TCodes[$key]['code_type'] == 'static' ) $result = [ $TCodes[$key]['code_value'] == $value ];
	else {
		$json = help::get_json( $__user['_json'] );
		if( !isset($json['transfer_codes']) || !isset($json['transfer_codes'][$key]) ) $result = [false];
		else $result = array( $json['transfer_codes'][$key] == $value );
	};
	
	echo json_encode($result);
	
endif;
