<?php

/**
 * This filter disabled XML-RPC for security purposes.
 *
 * @since 1.3.7
 */
add_filter( 'xmlrpc_enabled', '__return_false' );

/**
 * Prevent search engines from indexing the site unless it is live.
 *
 * @since 1.2.1
 */
function ow_robots_txt( $output ) {
	if ( ! ow_global_var( 'in_production' ) ) {	
		$output = "User-agent: *\r\nDisallow: /";
	}
	return $output;
}
add_filter( 'robots_txt', 'ow_robots_txt' );



// START SESSION
// function start_session() {

//     if ( ! session_id() ) {
//         session_start();
//     }
// }
// add_action( 'init', 'start_session', 1 );


// LIMIT POST REVISIONS TO KEEP DATABASE SMALLER
const WP_POST_REVISIONS = 3;

// TURNS OFF PHP FILE EDITOR
const DISALLOW_FILE_EDIT = true;

/**
 * Gets the customer information from the database.
 *
 * This function will get the customer
 * details (global configuration values),
 * returning them as a global array.
 *
 * @function query_db()
 *
 * @uses $wpdb::get_results()
 *
 * @return (array) the global variables in a global array
 * 
 * @since 1.0.0 
 *
 */
function query_db() {
	
	global $wpdb;
	global $ow_global_variables;
	
	$global_option = $wpdb->get_results( 'SELECT gc_option, gc_value FROM ow_global_configuration' );
	$array = [];
	
	foreach ( $global_option as $row ) {
		
		$array[$row->gc_option] = $row->gc_value;
	}
	$ow_global_variables = $array;

	return false;
}
add_action( 'plugins_loaded', 'query_db', 1 );



/**
 * Gets the customer information from the global array.
 *
 * This function will get the customer
 * details (global configuration values).
 * The function query_db() returns the
 * values as a global array so whenever
 * we run this function, it isn't
 * querying the database each time.
 *
 * @function ow_global_var()
 *
 * @uses developer_console_message()
 *
 * @param (string) $var the global variable name
 *
 * @return (string) the global variable value
 * 
 * @since 1.0.0 
 *
 */
function ow_global_var( $var ) {
	
	global $ow_global_variables;
	
	if ( is_array($ow_global_variables) && ! array_key_exists( $var, $ow_global_variables ) ) {
		
		return false;
	} else {
		
		$result = $ow_global_variables[$var];

		if ( $result != NULL ) {
			
			return $result;
		} else {
			
			developer_console_message( $var . ' is empty', 'warning' );
			return false;
		}
	}
}



/**
 * Register a new global variable.
 *
 * This function will register a key and value
 * pair to be used in the ow_global_var() function.
 *
 * @function ow_new_global_var()
 *
 * @uses ow_global_var(), developer_console_message()
 *
 * @param (string) $title the global variable key
 * @param (string) $var the global variable value
 *
 * @return N/A registers the new variable.
 * 
 * @since 1.1.0 
 *
 */
function ow_new_global_var( $title, $var ) {
	
	global $wpdb;
	
	$wpdb->query( $wpdb->prepare( 'REPLACE INTO ow_global_configuration ( gc_option, gc_value ) VALUES ( %s, %s )', $title, $var ) );
	
	$backtrace = debug_backtrace(1);
	
	$debug_file = basename( $backtrace[0]['file'] );
	$debug_line = $backtrace[0]['line'];
	
	developer_console_message( "$title: $var - This variable has been registered, you can now remove the function 'ow_new_global_var()' from $debug_file on line $debug_line.", 'alert' );
};



/**
 * Adds merge tags
 *
 * This function will swap out merge
 * tags in the main WordPress content
 *
 * @function content_merge_tags()
 *
 * @uses ow_global_var(), securemail()
 *
 * @param (string) $input the WordPress content
 *
 * @return (string) the Wordpress content after merge tags have been added.
 * 
 * @since 1.0.14 
 *
 */
function content_merge_tags( $input ) {

	$merge_tags_list = array(
		'/\%\%company\%\%/' => ow_global_var( 'accountant_name' ),
		'/\%\%tel\%\%/' 	=> ow_global_var( 'accountant_phone' ),
		'/\%\%email\%\%/'   => securemail( ow_global_var( 'accountant_email' ) ),
		'/\%\%website\%\%/' => '<a href="' . site_url() . '">' . site_url() . '</a>',
		'/\%\%area\%\%/' 	=> ow_global_var( 'accountant_main_area' ),
	);

	foreach ( $merge_tags_list as $tag => $value ) {
		
		$input = preg_replace( $tag, $value, $input );
	}
	return $input;
}
add_filter( 'the_content', 'content_merge_tags' );



/**
 * Returns the accountant address
 *
 * This function returns the accountants address
 * separated with a <br /> tag as default. The
 * address can be filtered to add the accountant
 * name at the beginning if needed.
 *
 * @function get_address()
 *
 * @uses ow_global_var(), apply_filters()
 *
 * @param (string) $sep The separator of each line in the address
 * @param (string) $alt An alternative address.
 *
 * @return (string) the accountant address enclodes in <address> tags
 *
 * @since 1.0.14 
 *
 */
function get_address( $sep = '<br />', $alt = '' ) {
	
	$address = ( $alt == '' ) ? ow_global_var( 'accountant_address' ) : $alt;
 
	$address = preg_replace( '/\s{2,}/', $sep, $address );
	
	$address = apply_filters( 'address', $address );
 
	echo '<address>' . $address . '</address>';
}



/**
 * Returns an attributes string for use in a html tag.	
 *
 * This function takes an array and returns a string of attributes.
 *
 * @function ow_array_attributes()
 *
 * @uses esc_attr()
 *
 * @param (array) $array  The attributes in an array.
 *
 * @return (string)		  The string of attributes.
 *
 * @since 1.1.6 
 *
 */
function ow_array_attributes( $array ) {
    $attributes = [];
	foreach ( $array as $key => $value ) {
		if ( is_bool( $value ) ) {
			$attributes[] = $key;
		}
		else if ( $value ) {
			$attributes[] = $key . '="' . esc_attr( $value ) . '"';
		}
	}
	return implode( ' ', $attributes );
}

/**
 * Returns the CDN link based on the hosting server address.
 *
 * This function ensures that the appropriate CDN link 
 * is dynamically returned based on the hosting server's address. 
 * It helps in managing server-specific configurations and 
 * improves efficiency by fetching 
 * resources from the correct CDN.
 *
 * @function get_plugin_cdn_link()
 *
 * @uses ow_global_var()
 * @uses constants like SERVER_1, SERVER_2, SERVER1_CDN, SERVER2_CDN
 *
 * @return (string) $cdn_link returns the appropirate cdn URL.
 *
 * @since 1.5.6
 *
 */

function get_plugin_cdn_link(){
	if( ow_global_var( 'hosted_in' ) == SERVER_1 ) {
		$cdn_link= SERVER1_CDN; 
	}else if( ow_global_var( 'hosted_in' ) == SERVER_2 ) {
		$cdn_link= SERVER2_CDN; 
	}else{
		$cdn_link= SERVER2_CDN; 
	}

	return $cdn_link;
}


/**
 * Echoes the telephone number in a link.
 *
 * This function echoes the telephone number given as a tel link.
 *
 * @function ow_the_telephone()
 *
 * @uses ow_array_attributes()
 *
 * @param (string) $number  The phone global variable.
 * @param (array)  $attr 	The attributes for the link.
 *
 * @return (string) 		The phone number in a tel link.
 *
 * @since 1.1.6 
 *
 */
function ow_the_telephone( $number, $attr = array() ) {
	$attributes = ow_array_attributes( array_merge( array(
		'href' => 'tel:' . str_replace( ' ', '', $number ),
	), $attr ) );
	return "<a {$attributes}>{$number}</a>";
}



/**
 * Returns The trading name sentence
 *
 * If the practice mname is different from
 * the full practice name, this function
 * will output a sentence e.g. XXX is a
 * trading name of YYY.
 *
 * @function company_trading_name()
 *
 * @uses ow_global_var()
 *
 * @return (string) the sentence explaining the trading name.
 *
 * @since 1.0.17 
 *
 */
function company_trading_name() {
	
	$name = ow_global_var( 'accountant_name' );
	$full_name = ow_global_var( 'accountant_full_name' );
	
	if ( $name != $full_name ) {
		
		echo $name . ' is a trading name of ' . $full_name ;
	} else {
		
		return false;
	}
}



// ADD CALL TO ACTION
function add_call_to_action( $link = '', $content = '' ) {
	
	$link = shortcode_atts( array( 'href' => '' ), $link, 'call_to_action' );
	return '<a href="' . $link['href'] . '" class="call-to-action">' . $content . '</a>';
}
add_shortcode( 'call_to_action', 'add_call_to_action' );



// REDIRECT AFTER LOGIN TO IRIS PLUGIN DASHBOARD
function ow_login_redirect( $redirect_to, $request, $user ) {
	
    return admin_url( 'admin.php?page=iris-dashboard' );
}
add_filter( 'login_redirect', 'ow_login_redirect', 10, 3 ); 



// ADD IRIS DEFAULT AVATAR
function ow_iris_avatar( $avatar ) {
	
	if ( current_user_can('administrator') ) {
		
    	$avatar = plugins_url( 'img/iris-logo-avatar.png', __FILE__ );
	}
	return $avatar;
}
add_filter( 'pre_option_avatar_default', 'ow_iris_avatar' );



function mtd_enabled() {
	
	if( ow_global_var( 'iris_mtd' ) === '1' || ! is_package_1() ) {
		
		return true;
	}
	return false;
}

function opt_newsletter() {
	
	if( ow_global_var( 'opt_newsletter' ) === '0') {
		
		return true;
	}
	return false;
}

function opt_card() {
	
	if( ow_global_var( 'opt_card' ) === '0') {
		
		return true;
	}
	return false;
}

function is_package_1() {
	
	if( ow_global_var( 'website_package' ) === PACKAGE_1 ) {
		
		return true;
	} else {
		
		return false;
	}
}


function is_package_2() {
	
	if( ow_global_var( 'website_package' ) === PACKAGE_2 ) {
		
		return true;
	} else {
		
		return false;
	}
}

function is_package_3() {
	
	if( ow_global_var( 'website_package' ) === PACKAGE_3 ) {
		
		return true;
				
	} else {
		
		return false;
	}
}

function is_package_4() {
	
	if( ow_global_var( 'website_package' ) === PACKAGE_4 ) {
		
		return true;
	} else {
		
		return false;
	}
}

function is_package_5() {
	
	if( ow_global_var( 'website_package' ) === PACKAGE_5 ) {
		
		return true;
	} else {
		
		return false;
	}
}
function is_package_6() {
	
	if( ow_global_var( 'website_package' ) === PACKAGE_6 ) {
		
		return true;
	} else {
		
		return false;
	}
}
function is_package_7() {
	
	if( ow_global_var( 'website_package' ) === PACKAGE_7 ) {
		
		return true;
	} else {
		
		return false;
	}
}
function is_package_8() {
	
	if( ow_global_var( 'website_package' ) === PACKAGE_8 ) {
		
		return true;
	} else {
		
		return false;
	}
}

function add_version() {
	
	echo "<!--\r\nCopyright © " . date( 'Y' ) . " | " . PRODUCT_NAME . " | " . PRODUCT_WEBSITE . "\r\n";
	echo "Version: " . OW_VERSION . "\r\nPackage: " . ow_global_var( 'website_package' ) . "\r\n-->\r\n";
}
add_action( 'copyright', 'add_version', 1 );






// THE MESSAGE SHOWN ON A FAILED LOGIN ATTEMPT
function wrong_login() {
	
  return 'Wrong username or password.';
}
add_filter( 'login_errors', 'wrong_login' );


// RETURNS THE LATEST UPDATE VERSION
function get_update_version() {
	
	$json = file_get_contents( 'https://cdn.irisopenwebsite.co.uk/v4/plugins/ow-plugin-meta.json' );
	$obj = json_decode( $json );
	return $obj->version;
}

// COMPARES THE VERSION NUMBER TO THE AVAILABLE UPDATE
function update_available() {
	
	if ( version_compare( OW_VERSION, UPDATE_VERSION ) < 0 ) {
		
		return true;
	} else {
		
		return false;
	}
}
define( 'UPDATE_VERSION', get_update_version() );



function demo_website() {
	
	$host = $_SERVER['SERVER_NAME'];
	$templates = array(
	   'design1.iriswebportallive.co.uk',
	   'design2.iriswebportallive.co.uk',
	   'design3.iriswebportallive.co.uk',
	   'design4.iriswebportallive.co.uk',
	   'design5.iriswebportallive.co.uk',
	   'design6.iriswebportallive.co.uk',
	   'design7.iriswebportallive.co.uk',
	   'design8.iriswebportallive.co.uk',
	);
	
	if ( in_array( $host, $templates ) ) {
		
		wp_register_script( 'demo-bar', 'https://cdn.irisopenwebsite.co.uk/v4/demo-site-bar/iris-demo-bar.min.js', array( 'jquery' ), null, true );
		wp_enqueue_script( 'demo-bar' );		
	}
}
add_action('wp_head','demo_website');





function add_demo_async_attribute( $tag, $handle ) {
	
    if ( 'demo-bar' !== $handle ) {
		
        return $tag;
	}
    return str_replace( ' src', ' async src', $tag );
}
add_filter('script_loader_tag', 'add_demo_async_attribute', 10, 2);

// Removes site health check widget
add_action('wp_dashboard_setup', 'remove_site_health_dashboard_widget');
function remove_site_health_dashboard_widget()
{
remove_meta_box('dashboard_site_health', 'dashboard', 'normal');
}
/*REMOVE COMMENTS - added on plugin update 1.5.2 in April 2023*/
add_action('admin_init', function () {
    // Redirect any user trying to access comments page
    global $pagenow;
     
    if ($pagenow === 'edit-comments.php') {
        wp_safe_redirect(admin_url());
        exit;
    }
 
    // Remove comments metabox from dashboard
    remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
 
    // Disable support for comments and trackbacks in post types
    foreach (get_post_types() as $post_type) {
        if (post_type_supports($post_type, 'comments')) {
            remove_post_type_support($post_type, 'comments');
            remove_post_type_support($post_type, 'trackbacks');
        }
    }
});
 
// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);
 
// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);
 
// Remove comments page in menu
add_action('admin_menu', function () {
    remove_menu_page('edit-comments.php');
});
 
// Remove comments links from admin bar
add_action('init', function () {
    if (is_admin_bar_showing()) {
        remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
    }
});
/*REMOVE COMMENTS END*/

/**
 * Defines and adds a custom options for Twitter Fields.
 *
 * This function adds a custom options page for Twitter Fields to the WordPress Admin Menu. The Twitter fields are only shown in the menu 
 * if the `opt_twitter` option is set to 1 using the `ow_global_var()` function.
 *
 * @function custom_twitter_fields_menu()
 *
 * @uses ow_global_var(), add_options_page()
 *
 * @param (string) $opt_twitter the global variable name
 *
 * @since 1.5.6
 */
function custom_twitter_fields_menu() {
  if (ow_global_var('opt_twitter') == 1) {
    add_options_page(
      'Custom Twitter Fields', // Page title
      'Custom Twitter Fields', // Menu title
      'manage_options', // Capability
      'custom-fields', // Menu slug
      'custom_twitter_fields_page' // Callback function to render the page
    );
  } else {
    // Do nothing: Twitter fields will be hidden from menu
  }
}
add_action('admin_menu', 'custom_twitter_fields_menu');

/**
 * Displays a custom settings page for Twitter fields.
 *
 * This function displays a custom settings page for Twitter fields
 * and allows users to update their Twitter account information.
 *
 * @function custom_twitter_fields_page()
 *
 * @since 1.5.6
 */

function custom_twitter_fields_page() {
    ?>
    <div class="wrap">
        <h1>Custom Twitter Fields</h1>
        <form method="post" action="options.php" enctype="multipart/form-data">
            <?php
            settings_fields('custom_twitter_fields_group');
            do_settings_sections('custom-twitter-fields');
            submit_button();
            ?>
        </form>
    </div>
    <?php
}

/**
 * This function registers the settings used for custom Twitter fields in the WordPress admin backend.
 *
 * The function registers the settings used for custom Twitter fields in the WordPress admin backend. 
 * It sets the Twitter name, subname, link, color, and image for the user.
 *
 * @function custom_twitter_fields_settings()
 *
 * @uses register_setting(), add_settings_section(), add_settings_field(), sanitize_text_field(), add_action() 
 *
 * @param (string) name: The name of the twitter account
 * @param (string) subname: The subname of the setting group
 * @param (string) linkk: The url of the Twitter profile
 * @param (string) color: The colors to be used for the Twitter settings
 * @param (array) image: The Twitter profile image URL with a "string" type, a sanitize callback, and a default value of an empty string
 *
 * @since 1.5.6
 */
function custom_twitter_fields_settings() {
    register_setting('custom_twitter_fields_group', 'twitter_name');
	register_setting('custom_twitter_fields_group', 'twitter_subname');
    register_setting('custom_twitter_fields_group', 'twitter_linkk');
	register_setting('custom_twitter_fields_group', 'twitter_color');
    register_setting('custom_twitter_fields_group', 'twitter_image', array(
        'type' => 'string', 
        'sanitize_callback' => 'sanitize_text_field',
        'default' => ''
    ));

    add_settings_section(
        'custom_twitter_fields_section',
        ' Your Twitter Information',
        null,
        'custom-twitter-fields'
    );

    add_settings_field(
        'twitter_name',
        'Twitter Name',
        'custom_twitter_name_callback',
        'custom-twitter-fields',
        'custom_twitter_fields_section'
    );
	  add_settings_field(
        'twitter_subname',
        'Twitter SubName',
        'custom_twitter_subname_callback',
        'custom-twitter-fields',
        'custom_twitter_fields_section'
    );

	add_settings_field(
        'twitter_linkk',
        'Twitter Linkk',
        'custom_twitter_link_callback',
        'custom-twitter-fields',
        'custom_twitter_fields_section'
    );
	

    add_settings_field(
        'twitter_image',
        'Twitter Image',
        'custom_twitter_image_callback',
        'custom-twitter-fields',
        'custom_twitter_fields_section'
      );
	
		add_settings_field(
    'twitter_color',
    'Twitter Color',
    'custom_twitter_color_callback',
    'custom-twitter-fields',
    'custom_twitter_fields_section'
);
}
add_action('admin_init', 'custom_twitter_fields_settings');

/**
 * This function Generates a form input field for a Twitter name option.
 *
 * This function generates an input field that's used for 
 * collecting Twitter name option value from the user. The option value 
 * will be saved to the WordPress database and can be retrieved later using the 
 * get_option() function.
 *
 * @function custom_twitter_name_callback()
 *
 * @uses get_option, esc_attr
 *
 * @param (string) twitter_name The current Twitter username option value.
 *
 * @since 1.5.6
 */
function custom_twitter_name_callback() {
    $twitter_name = get_option('twitter_name');
    echo '<input type="text" name="twitter_name" value="' . esc_attr($twitter_name) . '" />';
}

/**
 * This function Generates a form input field for a Twitter subname option.
 *
 * This function is used in a WordPress options form to display a text input field
 * for the user to enter or update their Twitter subname. The Twitter subname is retrieved from the options
 * database, sanitized with the 'esc_attr' function, and output as the value of the input field.
 *
 * @function custom_twitter_subname_callback()
 *
 * @uses get_option, esc_attr
 *
 * @param (string) $twitter_subname The current Twitter subname option value.
 *
 * @since 1.5.6
 */
function custom_twitter_subname_callback() {
    $twitter_subname = get_option('twitter_subname');
    echo '<input type="text" name="twitter_subname" value="' . esc_attr($twitter_subname) . '" />';
}

/**
 * This function Generates a form input field for a Twitter link option.
 *
 * This function gets the Twitter link option saved in the WordPress database and outputs it as an input field 
 * in the settings page. The option can be updated and saved by the user in the input field.
 *
 * @function custom_twitter_link_callback()
 *
 * @uses get_option, esc_attr
 *
 * @param (string) $twitter_linkk The current Twitter link option value.
 *
 * @since 1.5.6
 */
function custom_twitter_link_callback() {
    $twitter_linkk = get_option('twitter_linkk');
    echo '<input type="url" name="twitter_linkk" value="' . esc_attr($twitter_linkk) . '" />';
}

/**
 * This function creates a callback for a custom Twitter image input field.
 *
 * This function creates an HTML input field that allows the user to upload an image
 * for use as the Twitter Card image for their website. If an image has already been uploaded, it is displayed
 * below the input field.
 *
 * @function custom_twitter_image_callback()
 *
 * @uses get_option, esc_attr
 *
 * @param (file) twitter_image The Twitter image that the user has uploaded.
 *
 * @since 1.5.6
 */
function custom_twitter_image_callback() {
    $twitter_image = get_option('twitter_image');
    echo '<input type="file" name="twitter_image" accept="image/*" />';
    if ($twitter_image) {
        echo '<br /><img src="' . esc_attr($twitter_image) . '" width="100" />';
    }
}
/**
 * This function creates a callback for a custom Twitter color input field.
 *
 * This function creates an HTML input field that allows the user to choose
 * the color for the twitter feed. 
 *
 * @function custom_twitter_color_callback()
 *
 * @uses get_option, esc_attr
 *
 * @param (color) twitter_color The Twitter color that the user has updated.
 *
 * @since 1.5.6
 */
function custom_twitter_color_callback() {
    $twitter_color = get_option('twitter_color');
    echo '<input type="color" id="twitter-color" name="twitter_color" value="' . esc_attr($twitter_color) . '" />';
 // Add JavaScript to fetch and save the selected color
    ?>
    <script type="text/javascript">
        jQuery(document).ready(function($){
            $('#twitter-color').wpColorPicker({
                change: function(event, ui){
                    $('#twitter-color').val(ui.color.toString());
                }
            });
        });
    </script>
    <?php
}

/**
 * Uploads a Twitter image returns the URL of the uploaded image.
 *
 * This function handles uploading of an image to Twitter and 
 * returns the corresponding URL of the uploaded image.
 *
 * @function handle_twitter_image_upload()
 *
 * @uses wp_handle_upload, media_handle_upload
 *
 * @param (string) $option 
 *
 * @since 1.5.6
 */
function handle_twitter_image_upload($option) {
    if (!empty($_FILES['twitter_image']['tmp_name'])) {
        require_once(ABSPATH . 'wp-admin/includes/file.php'); //call media_handle_upload
        $urls = wp_handle_upload($_FILES['twitter_image'], array('test_form' => false));
        $temp = $urls['url'];
        return $temp;
    }
    return get_option($option);
}
add_filter('pre_update_option_twitter_image', 'handle_twitter_image_upload');
