<?php

/**
 * Rewrite rule for Tax Rates
 *
 * This function adds the rewrite rule for
 * the Tax Rates page. This function is too
 * specific, relying on the directory structure
 * 'resources/tax-centre/tax-rates-allowances'.
 * If the customer changes the title/slug of
 * resources, tax-centre or tax-rates-allowances,
 * the rewrite rule will break the tax rates page.
 *
 * @function add_rewrite_rules_tax_rates()
 *
 * @uses add_rewrite_rule(), add_rewrite_tag()
 *
 * @param N/A
 *
 * @return N/A
 *
 * @since 1.0.0 
 *
 */
function add_rewrite_rules_tax_rates() {
	
    add_rewrite_rule(
        '^resources/tax-centre/tax-rates-allowances/([^/]*)$',
        'index.php?page_id=731&tax_rates_title=$matches[1]',
        'top'
    );
	add_rewrite_tag( '%tax_rates_title%', '([^&]+)' );
}
add_action( 'init', 'add_rewrite_rules_tax_rates' );



/**
 * Return either a list or the Tax Rates content
 *
 * This function returns the list of Tax Rates
 * or the content for the Tax Rate that is
 * selected in the URL parameter 'tax_rates_title'.
 *
 * @function add_tax_rates()
 *
 * @uses get_query_var(), $iris_db::get_results(), wpautop(), sanitize_title()
 *
 * @param N/A
 *
 * @return (string) a list of, or content to the Tax Rates helpsheets
 *
 * @since 1.0.0 
 *
 */
function add_tax_rates() {
	
	global $iris_db;
	
	$tax_rates_slug = str_replace( '-', ' ', get_query_var( 'tax_rates_title' ) );
	
	if ( $tax_rates_slug ) {
		
		$helpsheets_array = $iris_db->get_results( "SELECT title, details FROM t_taxrates WHERE title='$tax_rates_slug'" );
		$content = '';
		
		foreach ( $helpsheets_array as $helpsheet ) {
			
			$content .= '<a href="' . get_permalink() . '">Back to Tax Rates & Allowances</a>';
			$content .= '<h2>' . $helpsheet->title . '</h2>';
			$content .= wpautop( $helpsheet->details );
		}
		return $content;
	} else {
		
		$category_array = $iris_db->get_results( "SELECT title FROM t_taxrates ORDER BY title" );
		$list = '<ul>';
		
		foreach ( $category_array as $category ) {
			
			$rates_link = '/resources/tax-centre/tax-rates-allowances/' . sanitize_title( $category->title ) . '/';
			$list .= '<li><a href="' . $rates_link . '">' . $category->title . '</a></li>';
		}
		$list .= '</ul>';
		return $list;	
	}
}
add_shortcode( 'tax_rates', 'add_tax_rates' );