<?php
class AdcPlugin{
	private $slug = "adc.php";
	private $analitycs = array();

	static function isMobileDevice(){
    	$aMobileUA = array(
        	'/iphone/i' => 'iPhone', 
        	'/ipod/i' => 'iPod', 
        	'/ipad/i' => 'iPad', 
        	'/android/i' => 'Android', 
        	'/blackberry/i' => 'BlackBerry', 
        	'/webos/i' => 'Mobile'
    	);

    	//Return true if Mobile User Agent is detected
    	foreach($aMobileUA as $sMobileKey => $sMobileOS){
        	if(preg_match($sMobileKey, $_SERVER['HTTP_USER_AGENT'])){
            	return true;
        	}
    	}
    	//Otherwise return false..  
    	return false;
	}	
	
	static function getAPI()
	{
 		require_once(dirname(__FILE__)."/cache.files.php");
 		$cache = new adcCacheFiles();
 		return new adcAPI(get_option('adc_api_endpoint'), get_option('adc_api_key'), $cache);
	}

	static function settings()
	{
 		$settings = self::getAPI()->settings();
        $data = $settings[self::isMobileDevice()? 'mobile' : 'desktop'];
        unset($settings['desktop']);
        unset($settings['mobile']);
        $settings = array_merge($settings, $data);
 		return $settings;
	}
	
	static function install(){

	}

	static function uninstall()
	{

	}
	function __construct()
	{
		$this->analitycs[] = new AdcAnalitycsGoogle();

	}
	function getCurrentVersion()
	{
		return ADC_PLUGIN_VERSION;
	}

	function showOptions()
	{
		$view = new View("admin_settings");
		echo $view->fetch();
	}

	function declare_query_vars($vars)
	{
		$vars = array_merge($vars, array(
			"category",
			"vendor",
			//"q",
			//"ch_category"
		));
		return $vars;
	}

	function getInfo()
	{
        $info = AdcPlugin::getAPI()->plugin_info();
    	$obj = new stdClass();
    	$obj->plugin = "adc/adc.php";
    	$obj->slug = $this->slug;
    	$obj->new_version = $info['version'];
    	$obj->url = $info['url'];
    	$obj->package = $info['package_url'];
    	$obj->requires = "4.7.5";
    	$obj->tested = "4.7.5";
    	$obj->sections = array(
			'description' => 'The new version of the Auto-Update plugin',
  			'another_section' => 'This is another section',
			'changelog' => 'Some new features'
		);
      	$obj->downloaded = 12540;
      	$obj->last_updated = '2012-01-12';		
      	return $obj;
	}

	function check_update($transient)
	{
        if (empty($transient->checked)) {
            return $transient;
        }
		$info = $this->getInfo();
		if (version_compare($this->getCurrentVersion(), $info->new_version, '<')) {
      	    $transient->response[$obj->plugin] = $info;
        }
   		return $transient;    
	}
	
	function plugin_api_call( $def, $action, $args )
	{
		if ($args->slug == $this->slug){
			return $this->getInfo();
		}
		return false;
	}
	function getRewriteRules()
	{
		$adc_rules = array(
			'^([a-zA-Z0-9\+\%\-_\.]+)/([a-zA-Z0-9_\-\+\%\.]+)' 
			=> 'index.php?page_id='.get_option("adc_details_page_id").'&category=$matches[1]&vendor=$matches[2]',
			'^search-products.*' 
			=> 'index.php?page_id='.get_option("adc_tiles_page_id").'&q=dsdsds'
		);
		return $adc_rules;
	}
	function checkRewriteRules(){
		$rules = get_option( 'rewrite_rules' );
		foreach ($this->getRewriteRules() as $key => $value) {
			if (!isset($rules[$key]) || $rules[$key] != $value)
				return false;
		}
		return true;
	}

	function registerHooks()
	{
		add_filter ('pre_set_site_transient_update_plugins', array($this, "check_update"));
		add_filter( 'plugins_api', array($this, 'plugin_api_call'), 10, 3);
		add_filter('rewrite_rules_array',function ($rules){
			$rules = array_merge($this->getRewriteRules(), $rules);			
			return $rules;
		});

		add_filter('query_vars', array($this, "declare_query_vars"));
		add_action('admin_menu', function(){
			add_options_page('ADC Options', 'ADC Options', 8, 'adc-options', array($this, "showOptions"));
		});
		add_action( 'admin_init', function (){
			register_setting( 'adc-settings', 'adc_api_endpoint' );
			register_setting( 'adc-settings', 'adc_api_key' );
			register_setting( 'adc-settings', 'adc_details_page_id' );
		});

		add_action('init', function(){
			if (!$this->checkRewriteRules()){				
				global $wp_rewrite;	
				$wp_rewrite->flush_rules();
			}					
		});

		add_action("widgets_init", function () {
    		register_widget("AdcVendorsTiles");
    		register_widget("AdcVendorDetails");
    		register_widget("AdcSearchForm");
		});
		add_shortcode( 'adc_vendors_tiles', array('AdcVendorsTiles','register_shortcode'));
		add_shortcode( 'adc_vendor_details', array('AdcVendorDetails','register_shortcode'));
		add_shortcode( 'adc_search_form', array('AdcSearchForm','register_shortcode'));

		//styles
    	wp_register_style('font-awesome', plugins_url('/assets/font-awesome/font-awesome.min.css', dirname(__FILE__)."../"), false, '4.7.0', 'all');
    	wp_register_style('adc-common', plugins_url('/assets/common.css', dirname(__FILE__)."../"), false, ADC_PLUGIN_VERSION, 'all');
    	wp_register_script('adc-common', plugins_url('/assets/common.js', dirname(__FILE__)."../"), array(), ADC_PLUGIN_VERSION);
        wp_register_script('history-api', plugins_url('/assets/history.js', dirname(__FILE__)."../"), array(), ADC_PLUGIN_VERSION);
    	//magnific popup
    	wp_register_style('magnific-popup', plugins_url('/assets/popup/magnific-popup.css', dirname(__FILE__)."../"), false, ADC_PLUGIN_VERSION, 'all');
    	wp_register_script('magnific-popup', plugins_url('/assets/popup/jquery.magnific-popup.min.js', dirname(__FILE__)."../"), array(), ADC_PLUGIN_VERSION);
    	//choosen
    	wp_register_style('chosen', plugins_url('/assets/chosen/chosen.min.css', dirname(__FILE__)."../"), false, ADC_PLUGIN_VERSION, 'all');
    	wp_register_script('chosen', plugins_url('/assets/chosen/chosen.jquery.min.js', dirname(__FILE__)."../"), array(), ADC_PLUGIN_VERSION);

    	add_action('wp_enqueue_scripts', function(){
    		wp_enqueue_script("jquery");
            wp_enqueue_script("history-api");
    		wp_enqueue_script("magnific-popup");
    		wp_enqueue_script("chosen");
    		wp_enqueue_script("adc-common");
    		wp_enqueue_style('font-awesome');
    		wp_enqueue_style('magnific-popup');
    		wp_enqueue_style('chosen');
    		wp_enqueue_style('adc-common');
    	});

    	//hubspot tracking code
    	add_action('wp_footer', array($this, 'processFooter'));    	
	}

	function processFooter()
	{
		foreach ($this->analitycs as $a){
			echo $a->renderFooter();
		}
	}
}