<?php
add_filter( 'wp_enqueue_scripts', 'my_aktive_snipes_buttons' );
function my_aktive_snipes_buttons() {	
	if(page_id() === 975) { // aktive-snipes
		if (isset($_GET["d"])) {
			$category = 'requests';
			[$bool, $redirect] = db_delete_own_post_by_requestid_category($category, $_GET["d"]);
			if ($redirect)
				redirect($redirect);
			else
				redirect('.');
		}
		else {
			show_button_container();
			confirm_modal('#button-delete-appointment', 'id', 'Löschen', 'Termin wirklich stoppen und löschen?<br><br>Bei Premium-Snipes werden dir deine FastCoins wieder gutgeschrieben.', 'Ja', 'Abbrechen', '_self');
		}		
	}
	if(page_id() === 978) { // inaktive-snipes
		if (isset($_GET["d"])) {
			$category = 'expired';	
			[$bool, $redirect] = db_delete_own_post_by_requestid_category($category, $_GET["d"]);
			if ($redirect)
				redirect($redirect);
			else
				redirect('.');		
		}
		else {
			show_button_container();
			confirm_modal('#button-delete-appointment', 'id', 'Löschen', 'Termin wirklich löschen?<br><br>Bei Premium-Snipes werden dir deine FastCoins wieder gutgeschrieben.', 'Ja', 'Abbrechen', '_self');
		}		
	}
	if(page_id() === 965) { // meine-snipes
		if (isset($_GET["d"])) {
			$category = 'appointment';	
			db_delete_own_post_by_requestid_category($category, $_GET["d"]);
			redirect('.');
		}
		else {
			show_button_container();
			confirm_modal('#button-delete-appointment', 'id', 'Löschen', 'Termin wirklich löschen?<br><br>Bei erfolgreichen Premium-Snipes werden keine FastCoins gutgeschrieben.', 'Ja', 'Abbrechen', '_self');
		}		
	}
	if(page_id() === 986) { // account
		if (isset($_GET["d"])) {
			php_console_log('deleting account...');
			api_delete_account();
			wp_logout();
		}
		else {
			button_change_account();
			//show_button_container();
			confirm_modal('#button-delete-account', 'id', 'Account löschen', 'Account endgültig löschen?<br><br>Bitte beachte, dass alle deine Daten, sowie alle aktiven Suchen und erfolgreiche Snipes gelöscht werden.<br><br>FastCoins kannst du ggfs. vorher an Freunde senden, da sie sonst verloren gehen.<br>Rückerstattungen sind nicht möglich.', 'Ja', 'Abbrechen', '_self');
		}		
	}
}

function button_change_account() {
	?>
		<script>
		// START JAVASCRIPT		
		document.addEventListener("DOMContentLoaded", function(event) {			
			jQuery('#button-account-change').click(function() {
				jQuery('.mepr-account-form ').show();
				jQuery('.fl-node-5e6bb58413fa7,.fl-node-5e63bb5062a0c,.fl-node-5e6bb5bc08bf1,.fl-node-5e6bb1c31677c,#button-appointment-container').hide();
				jQuery('.mepr-account-form').append('<a style="padding: 10px 75px 10px 75px !important; margin: 0 0 0 0 !important;" class="appointment-control" href="http://zinomedia.de/terminsnipe/dash/account/">Abbrechen</a>')			
			});		
		});
		// END JAVASCRIPT
		</script>
	<?php	
}

function api_delete_account() {
	$user = wp_get_current_user();	
	
	// The data to send to the API
	$postData = array(
		'WP_ID' => $user->ID,
		'event' => 'restapi-delete-user',
	);

	// Create the context for the request
	$context = stream_context_create(array(
		'http' => array(
			'method' => 'POST',
			'header' => "Content-Type: application/json\r\n",
			'content' => json_encode($postData)
		)
	));

	// Send the request
	$response = file_get_contents('https://terminsnipe:y9aFwUO7htuyKMaaPQWu@service.berlin.de.zinomedia.de/www/src/terminsnipe_controller.pl', FALSE, $context);

	// Check for errors
	if($response === FALSE){
		die('Error');
	}

	// Decode the response
	$responseData = json_decode($response, TRUE);

	// Print the date from the response
	echo $responseData['published'];
	dump_to_file('/var/www/lab/newfile.txt', $responseData);
	
}

function show_button_container() {
	?>
		<script>
		// START JAVASCRIPT		
		document.addEventListener("DOMContentLoaded", function(event) {			
			jQuery('#button-appointment-container').ready(function() {
				jQuery('#button-appointment-container').css('display', 'flex');
			});				
		});
		// END JAVASCRIPT
		</script>
	<?php	
}

function db_delete_own_post_by_requestid_category($category, $request_id) {
	// CHECK IF POST IS FROM USER WHO WANTS TO DELETE IT
	$user = wp_get_current_user();
	$data = array(
		'tag1'   	=> $request_id,
		'category'	=> $category,
	);
	$postslist = get_own_posts_by_tag_and_category($data);

	if (!empty($postslist)) {
		php_console_log('Post belongs to user');			
		
		// DELETE FROM DB
		if ($category === 'requests') {
			$table = 'request';
		}
		else if ($category === 'expired') {
			$table = 'request';
		}
		else if ($category === 'appointment') {
			$table = 'appointments';
		}
		
		$wpdb = connect_to_server('zinomedia');
		$status = $wpdb->delete( $table, array( 'ID' => $_GET["d"] ) );
		
		if ($category === 'requests' || $category === 'expired') {
			[$bool, $redirect] = refund_coins($postslist, $user);
			return [$bool, $redirect];
		}
	}
	else if (empty($postslist)) {
		php_console_log('Post does NOT belong to user');
		
		return [0, null];
	}
}

function refund_coins($postslist, $user) {
	$postmeta = get_post_meta( $postslist[0]->ID );
	if( $postmeta['is_premium'][0] ) {
		$balance_before_refund = mycred_return_users_balance();
		mycred_add( 'booking_manually_cancelled', $user->ID, $postmeta['price'][0], 'Cancellation by user, refund points' );
		$redirect = 'http://zinomedia.de/terminsnipe/?uccr&price=' . $postmeta['price'][0] . '&bbr=' . $balance_before_refund;
		return [1, $redirect];
	}
	else {
		return [0, null];
	}
}

function confirm_modal($button_id, $data_attribute, $title, $msg, $true, $false, $open) {
	?>
		<script>
		// START JAVASCRIPT		
		document.addEventListener("DOMContentLoaded", function(event) {	
			var data_attribute = "<?php echo $data_attribute ?>";
			var button = "<?php echo $button_id ?>";
			var id = jQuery(button).data(data_attribute);
			var redirect = '.?d=' + id;
			
			jQuery(button).ready(function() {
				jQuery(button).click(function() {
					Confirm("<?php echo $title ?>", "<?php echo $msg ?>", "<?php echo $true ?>", "<?php echo $false ?>", redirect, "<?php echo $open ?>");
				});	
			});				
		});
		// END JAVASCRIPT
		</script>
	<?php	
}

function get_own_posts_by_tag_and_category($data) {
	$user = wp_get_current_user();
	$args = array(
		'tax_query' => array(
			'relation' => 'AND',
			array(
				'taxonomy' => 'post_tag',
				'field' => 'slug',
				'terms' => $data['tag1'],
				'include_children' => false
			),
			array(
				'taxonomy' => 'post_tag',
				'field' => 'slug',
				'terms' => $user->user_nicename,
				'include_children' => false
			),
			array(
				'taxonomy' => 'category',
				'field' => 'slug',
				'terms' =>  $data['category'],
			),
		)
	);	
	$postslist = get_posts( $args );
	
	return $postslist;
}