<?php
add_filter( 'wp_enqueue_scripts', 'postcreator' );
function postcreator () {
	if( is_user_logged_in() ) { // Needed for page 222	
		if(page_id() === 975 || page_id() === 222) {
			$data = populate_section('requests');		
		}
		else if(page_id() === 978) {
			$data = populate_section('expired');		
		}
		else if(page_id() === 965) {
			$data = populate_section('appointment');		
		}
	}
}

function populate_section($category) {	
	// CURRENT USER OBJECT
	$user = wp_get_current_user();	
	
	// CREATE TAG TO DISPLAY RIGHT CONTENT IN CONTENT GRID POSTS MODULE
	$filter_tags = get_user_filter_tags($user);
	
	// INIT DATA
	$data = array(
			'user'			=> $user,
			'category'		=> $category,
			'filter_tag' 	=> $filter_tags[$category],
			'existent_post_ids' => array(),
	);
	
	// GET DB DATA
	$rows = get_snipes_from_db($category, $user);
	if (!empty($rows)) {
		php_console_log('We have data from db');
		$data['rows'] = $rows;
		//dump_to_file('/var/www/lab/newfile.txt', $rows, 'clear');
		$data = create_and_publish_posts($data);	
	}
	else {
		php_console_log('No data from db received.');
	}
	
	// SYNC POSTS
	sync_posts($data);
	
	return $data;
}

function sync_posts($data) {	
	$data_exists = array(
		'tags'   	=> array ( $data[user]->user_nicename ),
		'category'	=> $data[category],
	);
	$postslist = get_posts_by_tag_and_category($data_exists);
	//php_console_log('count postslist: ' . count($postslist));
	//php_console_log('count data[existent_post_ids]: ' . count($data[existent_post_ids]));	

	foreach ($postslist as $post) {		
		if (in_array($post->ID, $data[existent_post_ids])) {
			//php_console_log('Post with ID ' . $post->ID . ' has a right to exist');
		}
		else {
			//php_console_log('Post with ID: ' . $post->ID . ' is not anymore in db, delete?');
			wp_delete_post( $post->ID, true );
		}
	}
}

function create_and_publish_posts($data) {
	
	if ($data[category] == 'appointment') {
		foreach ($data[rows] as $appointment) {			
			$appointment[BUERGERAEMTER] = array($appointment[BUERGERAEMTER]);			
			$data[request] = $appointment;
			$data = create_new_post($data);	
		}
	}
	else {
		// CREATE GROUPS TO DISTINGUISH REQUESTS
		$rows_grouped = sort_aoa_by_value($data[rows], 'REQUEST_ID');

		// CREATE POSTS CONTENT AND PUBLISH
		foreach ($rows_grouped as $key=>$val) {
			$request = array('BUERGERAEMTER' => array());			
			foreach($rows_grouped[$key] as $group) {			
				foreach(array_keys($group) as $k) {				
					if ($k == 'BUERGERAMT') {
						array_push($request['BUERGERAEMTER'], $group[$k]);
					}
					else {
						$request[$k] = $group[$k];
					}				
				}				
			}		
			$data[request] = $request;			
			$data = create_new_post($data);	
		}
	}
	
	return $data;
}

function create_new_post($data) {
	$post_title = $data[category] . '_' . $data[request]['REQUEST_ID'];

	// CHECK IF POST EXISTS: IF POST DOES NOT EXIST -> ADD
	$data_exists = array(
		'tags'   	=> array ( $user->user_nicename, $data[request]['REQUEST_ID'] ),
		'category'	=> $data[category],
	);
	$postslist = get_posts_by_tag_and_category($data_exists);
	
	if (empty($postslist)) {
		php_console_log('Post ' . $post_title . ' in category ' . $data[category] . ' does not yet exist. Creating post...');		
		
		// CREATE THE POST CONTENT
		$post_content = create_post_content($data);	
		
		// INSERT NEW POST
		$categoryObj = get_category_by_slug( $data[category] );
		$new_post_id = wp_insert_post(array (
			'post_type' => 'post',
			'post_title' => $post_title,
			'post_content' => $post_content,
			'post_status' => 'publish',
			'comment_status' => 'closed',
			'ping_status' => 'closed',
			'tags_input' => array( $data[user]->user_nicename, $data[request][REQUEST_ID], $data[filter_tag] ),
			'post_category' => array( $categoryObj->term_id ),
		));			
		if ( $new_post_id ) {
			php_console_log('Post created with ID: ' . $new_post_id);
			array_push($data[existent_post_ids], $new_post_id);	
		}
		
		// CHECK IF PREMIUM POST
		$fastsnipeObj = get_fastsnipeObj();
		[$bool, $user_balance, $price, $is_premium] = check_premium( $fastsnipeObj, 'zeitraum', $data['request']['DATETIME_FROM'] );
		php_console_log('bool: ' . $bool . ' | user_balance: ' . $user_balance . ' | price: ' . $price . ' | is_premium: ' . $is_premium);
		update_post_meta( $new_post_id, 'is_premium', $is_premium );
		update_post_meta( $new_post_id, 'price', $price );		
	}
	else {
		array_push($data[existent_post_ids], $postslist[0]->ID);		
	}	
	
	return $data;
}

function get_snipes_from_db($switch, $user) {
	$wpdb = connect_to_server('zinomedia');	
	
	if ($switch == 'requests' || $switch == 'expired') {
		if ($switch == 'requests') {
			$expired = 0;
		}
		else {
			$expired = 1;
		}		
		$rows = $wpdb->get_results(	"
									Select
										reg_users.WP_ID,
										request.DATETIME_FROM,
										request.DATETIME_TO,
										request.SERVICE_ID,
										request_dienstleister.VENUE_ID,
										venues.NAME As BUERGERAMT,
										services.NAME As DIENSTLEISTUNG,
										request.EXPIRED,
										request_dienstleister.REQUEST_ID
									From
										reg_users Inner Join
										request On request.USER_ID = reg_users.ID Inner Join
										request_dienstleister On request_dienstleister.REQUEST_ID = request.ID Inner Join
										venues On venues.ID = request_dienstleister.VENUE_ID Inner Join
										services On services.ID = request.SERVICE_ID
									Where
										reg_users.WP_ID = $user->ID And
										request.EXPIRED = $expired
									", ARRAY_A );	
		return $rows;
	}
	else if ($switch == 'appointment') {
		$rows = $wpdb->get_results(	"
									Select
										reg_users.WP_ID,
										appointments.PROCESS_ID,
										appointments.AUTH_KEY,
										mapping.SERVICE_ID,
										mapping.VENUE_ID,
										appointments.ID As REQUEST_ID,
										venues.NAME As BUERGERAEMTER,
										services.NAME As DIENSTLEISTUNG,
										datetime.DATETIME
									From
										reg_users Inner Join
										appointments On appointments.USER_ID = reg_users.ID Inner Join
										mapping On mapping.ID = appointments.MAPPING_ID Inner Join
										services On services.ID = mapping.SERVICE_ID Inner Join
										venues On venues.ID = mapping.VENUE_ID Inner Join
										datetime On datetime.EPOCHTIME = mapping.DATETIME_ID
									Where
										reg_users.WP_ID = $user->ID
									", ARRAY_A );	
		return $rows;
	}
}