<?php

/**
 * Return the latest Budget date
 *
 * This function retrieves the Budget datestamp
 * from the database and converts it into the
 * specified date format.
 *
 * @function ow_get_budget_date()
 *
 * @uses $iris_db::get_row()
 *
 * @param (string) $format the format of the date() conversion
 *
 * @return (string) the date of the latest Budget
 *
 * @since 1.0.0 
 *
 */
function ow_get_budget_date( $format = 'F Y' ) {
	
	global $iris_db;
	
	$budget = $iris_db->get_row( 'SELECT datestamp FROM t_budgets ORDER BY datestamp DESC LIMIT 1' );
	$date = date( $format, strtotime( $budget->datestamp ) );
	return $date;
}



/**
 * Return the latest Budget title with the data appended
 *
 * This function appends the Budget date to
 * the Budget title. This function is too
 * specific. If the customer changes the title
 * of the page, this function will break.
 *
 * @function add_date_to_the_budget_title()
 *
 * @uses in_the_loop(), ow_get_budget_date()
 *
 * @param (string) $the_title the content title of the Budget page
 *
 * @return (string) the date of the latest Budget appended to the title
 *
 * @since 1.0.0 
 *
 */
function add_date_to_the_budget_title( $the_title ) {
	
    if ( in_the_loop() && $the_title == 'The Budget' ) {
		
		$the_title .= ' - ' . ow_get_budget_date( 'd F Y' );
	}
    return $the_title;  
}
add_filter( 'the_title', 'add_date_to_the_budget_title' );



/**
 * Replace [[ and ]] with "
 *
 * V3 database used a different encoding technique so all content from the 
 * budget table needs to be parsed correctly.
 *
 * @function ow_parse_budget_content()
 *
 * @param ( string) the string to be parsed.
 *
 * @return (string) the parsed string.
 *
 * @since 1.3.7 
 *
 */
function ow_parse_budget_content( $string ) {
	return str_replace( ['[[',']]'], '"', $string );
}



/**
 * Return the latest Budget content
 *
 * This function returns the latest
 * budget content from the database.
 *
 * @function add_the_budget()
 *
 * @uses $iris_db::get_row(), ow_parse_budget_content(), wpautop()
 *
 * @param N/A
 *
 * @return (string) the content of the latest Budget
 *
 * @since 1.1.3 
 *
 */
function add_the_budget() {
	
	global $iris_db;
	
	$budget = $iris_db->get_row( 'SELECT details FROM t_budgets ORDER BY datestamp DESC LIMIT 1' );
	
	$budget = ow_parse_budget_content( $budget->details );
	
	return wpautop( $budget );
}
add_shortcode( 'the_budget', 'add_the_budget' );