<?php
	/*
	 Plugin Name: flowfact-wp-connector
	 Description: Verbinden Sie Ihr Wordpress mit Ihrem FLOWFACT CRM.
	 Version: 1.0.9
	 Author: FLOWFACT
	 Author URI: http://www.flowfact.de
	 Text Domain: flowfact-wp-connector
	 Plugin Slug: flowfact-wp-connector
	 Domain Path: /languages 
	 License: GPL2
	 License URI: https://www.gnu.org/licenses/gpl-2.0.html
	 
	 FLOWFACT WP Connector is free software: you can redistribute it and/or modify
	 it under the terms of the GNU General Public License as published by
	 the Free Software Foundation, either version 2 of the License, or
	 any later version.
	  
	 FLOWFACT WP Connector is distributed in the hope that it will be useful,
	 but WITHOUT ANY WARRANTY; without even the implied warranty of
	 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	 GNU General Public License for more details.
	  
	 You should have received a copy of the GNU General Public License
	 along with FLOWFACT WP Connector. If not, see https://www.gnu.org/licenses/gpl-2.0.html.

	 */

	defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

	 
 	class FlowfactSalesautomatConnector {
		
		function __construct() {

			// load constants
			require_once( plugin_dir_path(__FILE__) .'core/constants/default.php');
			require_once( plugin_dir_path(__FILE__) .'core/constants/admin.php');
			require_once( plugin_dir_path(__FILE__) .'core/constants/api.php');

			// load api
			require_once( plugin_dir_path(__FILE__) .'core/api/api.php');

			// load admin panel
			require_once( plugin_dir_path(__FILE__) .'core/admin/settings.php');

			// load composer packs.
			require_once( plugin_dir_path(__FILE__) .'vendor/autoload.php');

			// create virtual page
			add_filter('the_posts',array( $this, 'get_vitual_page_detect'),-1);
			
		}
		
		function plugin_activate() {
			
			// extend DB
			global $wpdb;
			$charset_collate = $wpdb->get_charset_collate();
			require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );

			$sql = "CREATE TABLE ".$wpdb->prefix."ff_entity_cache (
			  entityId varchar(80) NOT NULL,
			  schemaId varchar(80) NOT NULL,
			  created datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
			  json text NOT NULL,
			  PRIMARY KEY (entityId)
			  ) $charset_collate;";
			dbDelta( $sql );
			
			$sql = "CREATE TABLE ".$wpdb->prefix."ff_schema_cache (
			  schemaId varchar(80) NOT NULL,
			  schemaName varchar(80) NOT NULL,
			  created datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
			  json text NOT NULL,
			  PRIMARY KEY (schemaId)
			  ) $charset_collate;";
			dbDelta( $sql );
			
			$sql = "CREATE TABLE ".$wpdb->prefix."ff_general_cache (
			  name varchar(80) NOT NULL,
			  created datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
			  json text NOT NULL,
			  PRIMARY KEY (name)
			  ) $charset_collate;";
			dbDelta( $sql );
			
			$sql = "CREATE TABLE ".$wpdb->prefix."ff_customer_cache (
			  id varchar(80) NOT NULL,
			  created datetime DEFAULT '0000-00-00 00:00:00' NOT NULL,
			  customer varchar(80) NOT NULL,
			  customerIp varchar(80) NOT NULL,
			  schemaId varchar(80) NOT NULL,
			  entityId varchar(80) NOT NULL,
			  value varchar(80) NOT NULL,
			  PRIMARY KEY (id)
			  ) $charset_collate;";
			dbDelta( $sql );
			
			// set rewrite
			set_transient( 'ff_flush', 1, 60 );
		}

		function plugin_deactivate() {
			
			// cleanup DB
			global $wpdb;
			$charset_collate = $wpdb->get_charset_collate();
			require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
			
			$sql = "DROP TABLE IF EXISTS ".$wpdb->prefix."ff_general_cache";
			$wpdb->query( $sql );
			
			$sql = "DROP TABLE IF EXISTS ".$wpdb->prefix."ff_schema_cache";
			$wpdb->query( $sql );
			
			$sql = "DROP TABLE IF EXISTS ".$wpdb->prefix."ff_entity_cache";
			$wpdb->query( $sql );
			
			$sql = "DROP TABLE IF EXISTS ".$wpdb->prefix."ff_customer_cache";
			$wpdb->query( $sql );
			
			// flush rewrite rules
			flush_rewrite_rules();
		}
	
		function get_vitual_page_detect($posts){
			global $wp;
			global $wp_query;
			
			
			// get path
			$uriSegments = explode("/", parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH));

			$prod = true;
			if($prod == true)
			{
				$a =  $uriSegments[1];
				$b =  $uriSegments[2];
				$c =  $uriSegments[3];
				$d =  $uriSegments[4];
			}
			else
			{
				$a =  $uriSegments[2];
				$b =  $uriSegments[3];
				$c =  $uriSegments[4];
				$d =  $uriSegments[5];
			}
			

			global $get_vitual_page_detect; // used to stop double loading
			$get_vitual_page_url = $_SERVER['REQUEST_URI']; // URL of the fake page
			
			if ( $a == FF_PLUGIN_ROUTE ) {

				// stop interferring with other $posts arrays on this page (only works if the sidebar is rendered *after* the main page)
				$get_vitual_page_detect = true;
				
				
				
				// create a fake virtual page
				$post = new stdClass;
				$post->post_author = 1;
				$post->post_name = $get_vitual_page_url;
				$post->guid = get_bloginfo('wpurl') . '/' . $get_vitual_page_url;
				
				if(!empty($a) && $a == FF_PLUGIN_ROUTE)
				{
					if($b == FF_RECOMMENDATION_ROUTE)
					{
						if(empty($c))
						{
							$FFrecommendationCore = new FFrecommendationCore();
							$data =  $FFrecommendationCore->get_recommendation_overview();
							$post->post_title 	= $data['title'];
							$post->post_content = $data['content'];
						}
						else
						{
							$FFrecommendationCore = new FFrecommendationCore();
							$data = $FFrecommendationCore->get_recommendation($c);	
							$post->post_title 	= $data['title'];
							$post->post_content = $data['content'];
						}
					}
					elseif($b == FF_ESTATEVIEW_ROUTE) 
					{
						if(empty($c))
						{
							$FFestateViewCore = new FFestateViewCore();
							$data = $FFestateViewCore->get_estate_overview();
							$post->post_title 	= $data['title'];
							$post->post_content = $data['content'];	
						}
						else
						{
							if(!empty($c) and $c == "sitemap.xml" and FF_ESTATEVIEW_SEO == "on")
							{
								if(FF_ESTATEVIEW_SEO == "on")
								{
									$FFestateViewCore = new FFestateViewCore();
									$data = $FFestateViewCore->get_estate_sitemap();
									header("Content-type: text/xml");
									echo $data['content'];	
									die;
								}
								else
								{
									global $wp_query;
									$wp_query->set_404();
									status_header( 404 );
									get_template_part( 404 ); 
									exit();
								}	
							}
							else
							{
								$FFestateViewCore = new FFestateViewCore();
								$data = $FFestateViewCore->get_estate_details($c,$d);
								$post->post_title 	= $data['title'];
								$post->post_content = $data['content'];
							}				
						}	
					}
					elseif($b == FF_ESTATEREFERENCE_ROUTE) 
					{	
						$FFestateReferenceCore = new FFestateReferenceCore();
						$data = $FFestateReferenceCore->get_estate_reference_overview();
						$post->post_title 	= $data['title'];
						$post->post_content = $data['content'];
					}
					elseif($b == FF_PROSPECTFINDER_ROUTE) 
					{	
						$FFprospectFinderCore = new FFprospectFinderCore();
						$data = $FFprospectFinderCore->get_overview();
						$post->post_title 	= $data['title'];
						$post->post_content = $data['content'];
					}
					else 
					{
						global $wp_query;
						$wp_query->set_404();
						status_header( 404 );
						get_template_part( 404 ); 
						exit();
					}
				}
				
				$post->ID = -999;
				$post->post_type = 'post';
				$post->post_status = 'static';
				$post->comment_status = 'closed';
				$post->ping_status = 'open';
				$post->comment_count = 0;
				$post->post_date = current_time('mysql');
				$post->post_date_gmt = current_time('mysql', 1);
				$posts=NULL;
				$posts[]=$post;
				
				// make wpQuery believe this is a real page too
				$wp_query->is_page = true;
				$wp_query->is_singular = true;
				$wp_query->is_home = false;
				$wp_query->is_archive = false;
				$wp_query->is_category = false;
				unset($wp_query->query["error"]);
				$wp_query->query_vars["error"]="";
				$wp_query->is_404=false;
			}
			
			remove_filter( 'the_content', 'wpautop' );
			remove_filter( 'the_excerpt', 'wpautop' );
			
			return $posts;
		}

	
		function init_modules() {
			
			// init widgets FFrecommendationWidget
			add_action( 'widgets_init', function(){
				require_once( plugin_dir_path(__FILE__) .'modules/recommendation/config.php');
				require_once( plugin_dir_path(__FILE__) .'modules/recommendation/widget.php');
				register_widget( 'FFrecommendationWidget' );
			});

			// init widgets FFestateViewWidget
			add_action( 'widgets_init', function(){
				require_once( plugin_dir_path(__FILE__) .'modules/estateView/config.php');
				require_once( plugin_dir_path(__FILE__) .'modules/estateView/widget.php');
				register_widget( 'FFestateViewWidget' );
			});

			// init widgets FFestateReferenceWidget
			add_action( 'widgets_init', function(){
				require_once( plugin_dir_path(__FILE__) .'modules/estateReference/config.php');
				require_once( plugin_dir_path(__FILE__) .'modules/estateReference/widget.php');
				register_widget( 'FFestateReferenceWidget' );
			});
			
			// init widgets FFprospectFinderWidget
			add_action( 'widgets_init', function(){
				require_once( plugin_dir_path(__FILE__) .'modules/prospectFinder/config.php');
				require_once( plugin_dir_path(__FILE__) .'modules/prospectFinder/widget.php');
				register_widget( 'FFprospectFinderWidget' );
			});
			
		}	
	}

	if( class_exists( 'FlowfactSalesautomatConnector' ) ) {
		$flowfactSalesautomatConnector = new FlowfactSalesautomatConnector();
		$flowfactSalesautomatConnector->init_modules();
	}

	// activate
	register_activation_hook( __FILE__, array($flowfactSalesautomatConnector, 'plugin_activate'));

	// deactivate
	register_deactivation_hook( __FILE__, array($flowfactSalesautomatConnector, 'plugin_deactivate'));

	
