<?php

class Rover_IDX_Database
	{
	public static function update_rover_tables()
		{
		self::create_tracking_table();

		update_option("roveridx_db_version", roverVERSIONS::VERSION);
		}

	public static function delete_tracking_table()
		{
		global								$wpdb;


		if ($wpdb->query("DROP TABLE ".self::tracking_table().";"))
			return true;

		return false;
		}

	public static function already_in_tracking($id, $region) {

		global								$wpdb;

		$key								= $id.'-'.$region;

		$rows								= $wpdb->get_results(
											"SELECT * FROM ".self::tracking_table()." WHERE id = '$key'"
											);

		return ((count($rows)) ? true : false);
		}

	public static function update_tracking($id, $region) {

		global								$wpdb;

		$key								= $id.'-'.$region;

		$wpdb->insert( self::tracking_table(), array( 'id' => $key, 'time' => current_time('mysql') ) );

		#	Purge old tracking records
		$wpdb->query( $wpdb->prepare( "DELETE FROM ".self::tracking_table()." WHERE time = '%s'", date ( 'Y-m-j' , strtotime ( '-7 days' ) ) ));
		}

	public static function tracking_table_exists()
		{
		global								$wpdb;

		$rows								= $wpdb->get_results(
											"SELECT `TABLE_NAME` FROM information_schema.tables
											WHERE table_schema = '".DB_NAME."'
											AND table_name = '".self::tracking_table()."'"
											);

		return ((count($rows)) ? true : false);
		}

	public static function set_template_meta($roveridx_post_id, $template_file = null)
		{
		//	Don't 'add_post_meta' - it keeps adding entries to wp-postmeta

		if (function_exists('genesis_unregister_layout'))		//	StudioPress Genesis platform
			{
			update_post_meta( $roveridx_post_id, '_genesis_layout',	'full-width-content' );
			}
		else if (function_exists('woo_post_meta'))				//	WooThemes framework
			{
			update_post_meta( $roveridx_post_id, '_layout', 		'layout-full' );
			}

		if (!is_null($template_file))
			{
			//	Do this in all cases, even if we are StudioPress or Woothemes

			$template_file					= sanitize_file_name($template_file);

			update_post_meta($roveridx_post_id, roverKEYS::WP_TEMPLATE_KEY, $template_file);
			}
		}

	public static function create_quick_setup_pages($rover_idx, $settings)
		{
		$the_html							= array();

		if ($settings['create_home'] == 'true')
			{
			$ret							= self::create_page(
																$title		= 'Home',
																$parent		= 0,
																$content	= '[rover_idx_slider]',
																$meta		= 'home'
																);

			$the_html[]						= $ret['html'];
			}

		if ($settings['create_listings'] == 'true')
			{
			$selected_cities				= self::get_listing_cities($rover_idx, $settings);

			$ret							= self::create_page(
																$title		= $settings['listings_parent'],
																$parent		= 0,
																$content	= '[rover_idx_listings format="full"]',
																$meta		= 'listings'
																);

			$the_html[]						= $ret['html'];
			$parent_id						= $ret['id'];

			foreach($selected_cities as $one_city)
				{
				$ret						= self::create_page(
																$title		= $settings['listings_parent'].' in '.$one_city,
																$parent		= $parent_id,
																$content	= '[rover_idx_listings format="full" cities="'.$one_city.'"]',
																$meta		= 'listings-'.strtolower(preg_replace('/[^a-zA-Z0-9]/', '', $one_city))
																);

				$the_html[]					= $ret['html'];
				}
			}

		if ($settings['create_contact'] == 'true')
			{
			$ret							= self::create_page(
																$title		= 'Contact',
																$parent		= 0,
																$content	= '[rover_idx_contact]',
																$meta		= 'contact'
																);

			$the_html[]						= $ret['html'];
			}

		return '<div>'.implode('<br>', $the_html).'</div>';
		}

	public static function fetch_quick_setup_pages()
		{
		$the_html							= array();

		$home_rows							= self::find_quick_pages('home');
		$listing_rows						= self::find_quick_pages('listings');
		$contact_rows						= self::find_quick_pages('contact');

		if (count($home_rows))
			$the_html[]						= number_format((count($home_rows))).' Home page';

		if (count($listing_rows))
			$the_html[]						= number_format((count($listing_rows))).' Listing pages';

		if (count($contact_rows))
			$the_html[]						= number_format((count($contact_rows))).' Contact page';

		return implode(', ', $the_html);
		}

	public static function reset_quick_setup_pages()
		{
		$the_html							= array();

		$home_rows							= self::find_quick_pages('home');
		$listing_rows						= self::find_quick_pages('listings');
		$contact_rows						= self::find_quick_pages('contact');

		if (count($home_rows))
			{
			foreach($home_rows as $one_row)
				{
				$the_html[]					= 'Deleting Home ['.$one_row->ID.']';
				wp_delete_post($one_row->ID);
				}
			}

		if (count($listing_rows))
			{
			foreach($listing_rows as $one_row)
				{
				$the_html[]					= 'Deleting Listing ['.$one_row->ID.']';
				wp_delete_post($one_row->ID);
				}
			}

		if (count($contact_rows))
			{
			foreach($contact_rows as $one_row)
				{
				$the_html[]					= 'Deleting Contact ['.$one_row->ID.']';
				wp_delete_post($one_row->ID);
				}
			}

		$the_html[]							= 'Done';

		return implode('<br>', $the_html);
		}

	private static function create_tracking_table()
		{
		global $wpdb;

		$sql								= "CREATE TABLE ".self::tracking_table()." (
											id VARCHAR(20) NOT NULL,
											time datetime NULL DEFAULT NULL,
											UNIQUE KEY id (id) );";

		require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
		dbDelta($sql);

		if (!empty($wpdb->last_error))
			wp_die($wpdb->last_error.' / '.$sql);
		}

	private static function tracking_table()	{

		global $wpdb;

		return $wpdb->prefix . 'roveridx_tracking';;
		}

	private static function find_quick_pages($meta)
		{
		global								$wpdb;

		$existing_pages						= $wpdb->get_results( "
																SELECT	  p.*
																FROM		$wpdb->posts as p
																INNER JOIN  $wpdb->postmeta as m ON (m.post_id = p.ID AND m.meta_key = 'rover_quickstart_page')
																WHERE	   p.post_type = 'page'
																AND			p.post_status = 'publish'
																AND			m.meta_value LIKE '".$meta."%'
																");


		return $existing_pages;
		}

	private static function create_page($title, $parent, $content, $meta)
		{
		$the_html							= array();
		$post_id							= 0;

		$existing_pages						= self::find_quick_pages($meta);

		if (count($existing_pages) === 0)
			{
			$post_id						= wp_insert_post(
															array(
																'comment_status'	=>	'closed',
																'ping_status'		=>	'closed',
																'post_author'		=>	get_current_user_id(),
																'post_date'			=>	date('Y-m-d H:i:s', strtotime('Now')),
																'post_content'		=>	$content,
																'post_title'		=>	$title,
																'post_status'		=>	'publish',
																'post_name'			=>	$title,
																'post_parent'		=>	$parent,
																'post_type'			=>	'page',
																'meta_input'		=> array(
																						'rover_quickstart_page' => $meta
																						)
															)
														);

			if (is_wp_error($post_id)) {
				$errors						= $post_id->get_error_messages();
				foreach ($errors as $error) {
					$the_html[]				= '['.$title.'] Error creating page: ['.$error.']';
					}
				}
			else
				{
				if (!is_null($post_id))
					$the_html[]				= 'Created ['.$post_id.'] ['.$title.'] with '.$content;
				}
			}
		else
			{
			$the_html[]						= '['.$title.'] with meta ['.$meta.'] already exists!';
			}

		return array(
					'id'					=> $post_id,
					'html'					=> implode('', $the_html)
					);
		}

	private static function get_listing_cities($rover_idx, $settings)
		{
		$rover_content						= $rover_idx->CONTENT->rover_content('ROVER_COMPONENT_GET_QUICKSTART_CITIES', array('for_cities' => $settings['for_cities']));

		return explode(',', $rover_content['the_html']);
		}
	}
?>