<?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();
 		if (!$settings) return false;
        $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', 'manage_options', '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' );
			register_setting( 'adc-settings', 'adc_tiles_sticky_offset' );
			register_setting( 'adc-settings', 'adc_details_sticky_offset' );
			if (!get_option("adc_tiles_sticky_offset"))
				update_option("adc_tiles_sticky_offset", "#header.fixed");
			if (!get_option("adc_details_sticky_offset"))
				update_option("adc_details_sticky_offset", "#header.fixed");
		});

		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'));


    	add_action('wp_enqueue_scripts', function(){
			//styles
	    	wp_register_style('font-awesome', $this->getUrl('/assets/font-awesome/font-awesome.min.css'), false, '4.7.0', 'all');
	    	wp_register_style('adc-common', $this->getUrl('/assets/common.css'), false, ADC_PLUGIN_VERSION, 'all');
	    	wp_register_script('adc-common', $this->getUrl('/assets/common.js'), array(), ADC_PLUGIN_VERSION);
	    	wp_register_script('skicky-kit', $this->getUrl('/assets/sticky-kit.js'), array(), ADC_PLUGIN_VERSION);
	    	wp_register_script('scrollto', $this->getUrl('/assets/scrollto.js'), array(), ADC_PLUGIN_VERSION);
	        wp_register_script('history-api', $this->getUrl('/assets/history.js'), array(), ADC_PLUGIN_VERSION);
	    	//magnific popup
	    	wp_register_style('magnific-popup', $this->getUrl('/assets/popup/magnific-popup.css'), false, ADC_PLUGIN_VERSION, 'all');
	    	wp_register_script('magnific-popup', $this->getUrl('/assets/popup/jquery.magnific-popup.min.js'), array(), ADC_PLUGIN_VERSION);
	    	//choosen
	    	wp_register_style('chosen', $this->getUrl('/assets/chosen/chosen.min.css'), false, ADC_PLUGIN_VERSION, 'all');
	    	wp_register_script('chosen', $this->getUrl('/assets/chosen/chosen.jquery.min.js'), array(), ADC_PLUGIN_VERSION);

    		wp_enqueue_script("jquery");
            wp_enqueue_script("history-api");
    		wp_enqueue_script("magnific-popup");
    		wp_enqueue_script("chosen");
    		wp_enqueue_script("skicky-kit");
    		wp_enqueue_script("scrollto");
    		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 getUrl($file)
	{
		if (file_exists(WPMU_PLUGIN_DIR."/adc")){
			return WPMU_PLUGIN_URL."/adc".$file;
		} else {
			return plugins_url($file, dirname(__FILE__)."../");
		}
	}
	function processFooter()
	{
		foreach ($this->analitycs as $a){
			echo $a->renderFooter();
		}
	}
}