<?php

class Intense_Widgets {

	function __construct() {
		add_filter( 'widgets_init', array( 'Intense_Widgets', 'register' ) );
	}

	public static function get_search_paths( ) {
		$search_paths = array(
			'intense' => INTENSE_PLUGIN_FOLDER . '/widgets/'
		);

		$search_paths = apply_filters( 'intense/widgets/search_paths', $search_paths );

		return $search_paths;
	}

	public static function load_widgets() {
		global $intense_widgets_list;

		$intense_widgets_list = array();

		$search_paths = Intense_Widgets::get_search_paths();

		foreach ( $search_paths as $path_key => $path ) {
			$path_directories = scandir( $path );

			foreach ( $path_directories as $widget_directory ) {
				if ( $widget_directory === '.' or $widget_directory === '..' ) continue;

				if ( is_dir( $path . $widget_directory ) ) {
					$widget_files = scandir( $path . $widget_directory );

					foreach ( $widget_files as $key => $widget_file ) {
						if ( $widget_file === '.' or $widget_file === '..' ) continue;

						if ( substr( $widget_file, -strlen( ".php" ) ) == ".php" && substr( $widget_file, -strlen( "-options.php" ) ) != "-options.php" ) {
							$widget_title = str_replace( '.php', '', $widget_file );
							$widget_title = ucwords( str_replace( '-', ' ', $widget_title ) );
							$widget_class_name = "Intense_Widget_" . ucfirst( str_replace( ' ', '_', $widget_title ) );

							$intense_widgets_list[ $widget_class_name ][ 'title' ] = $widget_title;
							$intense_widgets_list[ $widget_class_name ][ 'path' ] = $path . $widget_directory . '/' . $widget_file;
							$intense_widgets_list[ $widget_class_name ][ 'options-path' ] = $path . $widget_directory . '/' . $widget_title . '-options.php';
							$intense_widgets_list[ $widget_class_name ][ 'directory' ] = $widget_directory;

							if ( version_compare( phpversion(), '5.3.0', '<' ) ) {
								require_once $path . $widget_directory . '/' . $widget_file;
							}
						}
					}
				}
			}
		}

		ksort( $intense_widgets_list );
	}

	public static function load_options() {
		global $intense_widgets_list;

		$options = array();

		foreach ( $intense_widgets_list as $key => $widget ) {
			$options_file = $widget[ 'options-path' ];

			if ( file_exists( $options_file ) ) {				
				require $options_file;
			}
		}

		return $options;
	}

	public static function register() {
		global $intense_widgets_list, $intense_visions_options;

		foreach ( $intense_widgets_list as $key => $value ) {
			if ( !empty( $intense_visions_options['intense_active_widgets'][ $key ] ) ) {
				register_widget( $key );
			}
		}
	}
}
