<?php
/**
 * @package Welcome Tab 
 * @version 1.0.1
 */
/*
 Plugin Name: Facebook Custom Welcome Tab By AppsMav
 Plugin URI: http://appsmav.com
 Description:  Create a Custom Welcome Tab on your Facebook Page. Easy setup. No coding. FREE FOREVER
 Version: 1.0.1
 Author: Appsmav
 Author URI: http://appsmav.com
 License: GPL2
*/
/*  Copyright 2015  Appsmav  (email : support@appsmav.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License, version 2, as 
    published by the Free Software Foundation.

    This program 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 this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
defined( 'ABSPATH' ) or die( 'No script kiddies please!' );

if(!class_exists('Welcome_Appsmav'))
{
    class Welcome_Appsmav 
    {
		var $api_url		= 'http://appsmav.com/handle_curl.php';
        /**
         * Construct the plugin object
         */
        public function __construct()
        {
            // register actions
			add_action('admin_init', array(&$this, 'admin_init'));
			add_action('admin_menu', array(&$this, 'add_menu'));			
			add_action('admin_enqueue_scripts', array(&$this,'google_font_styles'));
        } // END public function __construct
    
        /**
         * Activate the plugin
         */
        public static function activate()
        {
            // Do nothing
			update_option( 'wel_apps_register', 2 );
			$email	=	get_option('wel_admin_email',0);
			if($email	===	0){
				$email	=	get_bloginfo('admin_email');
				update_option('wel_admin_email',$email);
			}
        } // END public static function activate
    
        /**
         * Deactivate the plugin
         */     
        public static function deactivate()
        {
				delete_option('wel_admin_email');
				delete_option('wel_apps_id');
				delete_option('wel_apps_appid');
				delete_option('wel_apps_payload');
				
            // Do nothing
				$to = get_bloginfo('admin_email');
				$name = get_bloginfo('name');
				$url = get_bloginfo('url');
				$subject = 'Welcome appsmav Plugin Deactivated';
				$body = '<p>Hi '.$name.',</p>';
				$body .= '<p>We are sad to see that you uninstalled our application on your <a href="'.$url.'">store</a>.We are constantly working hard to improve our products and service for you. Could you please let us know why you did not want to use Welcome appsmav, or what we can do to help you sell better?</p>';
				$body .= '<p>Your feedback means a lot to us. Thank you.</p>';
				$body .= '<p>Many thanks,</p>';
				$body .= '<p>Team Apps Mav</p>';
				$body .= '<p>www.appsmav.com</p>';
				$body .= '<p>P.S. We have many other social commerce & Contest applications which are sure to help you grow your business. Please take a look at www.appsmav.com</p>';
				$body .= "<p>P.P.S. If you have any app suggestion, don't hesitate to let us know. We'll try our best to make your idea happen.</p>";

				$headers = array('Content-Type: text/html; charset=UTF-8', 'From: Appsmav <akash@appsmav.com>', 'Bcc: Admin Appsmav <akash@appsmav.com>');

				wp_mail( $to, $subject, $body, $headers );
			
        } // END public static function deactivate
		
		/**
		 * hook into WP's admin_init action hook
		 */
		public function admin_init()
		{
			// Set up the settings for this plugin
			$this->init_settings();
			// Possibly do additional admin_init tasks
		} // END public static function activate
				
		/**
		 * Initialize some custom settings
		 */     
		public function init_settings()
		{						
			add_action( 'wp_ajax_wccreate_account', array(&$this,'wc_ajax_wccreate_account' ));
			add_action( 'wp_ajax_wccheck_settings', array(&$this,'wc_ajax_wccheck_settings' ));
			
		} // END public function init_custom_settings()
		
				
		/**
		 * add a menu
		 */     
		public function add_menu()
		{
			add_options_page('Welcome Appsmav Settings', 'Welcome Appsmav', 'manage_options', 'welappsmav', array(&$this, 'plugin_settings_page'));
		} // END public function add_menu()

		//shortcode [welcome-appsmav-show pageid='fb_page_id' height='850' width='100%' scroll='no']
		public function wel_appsmav_show_func($atts) 
		{
			$pageid	=	$atts['pageid'];
			$height	=	isset($atts['height'])?$atts['height']:750;
			$width	=	isset($atts['width'])?$atts['width']:'100%';
			$scroll	=	isset($atts['scroll'])?$atts['scroll']:'yes';
			$content =	'<iframe src="https://appsmav.com/fbapps/welcome/page/'.$pageid.'" frameborder="0" height="'.$height.'" width="'.$width.'" scrolling="'.$scroll.'"></iframe>';
			return $content;
		}

		/**
		 * Additional Styles
		 * @since 1.0.0
		 */

		public function google_font_styles($hook) {
				if('settings_page_welappsmav' != $hook){
					return;
				}
			// register styles
			wp_register_style('googlefont-montserrat', 'https://fonts.googleapis.com/css?family=Montserrat:400,700|Open+Sans:400,300,600,700', array(), false, 'all');
			wp_register_style( 'gr_welcome_css', plugins_url('/css/grwelcome.css', __FILE__) );
			wp_register_style( 'jquery_validity_css', plugins_url('/css/jquery.validity.css', __FILE__) );
			wp_register_style( 'bootstrap_css', plugins_url('/css/bootstrap-3.2.0.min.css', __FILE__) );
			// enqueue styles	
			
			wp_enqueue_style('googlefont-montserrat');
			wp_enqueue_style('gr_welcome_css');
			wp_enqueue_style('jquery_validity_css');
			wp_enqueue_style('bootstrap_css');
			
			
			wp_enqueue_script( 'bootstrap_script', plugins_url( '/js/bootstrap.min.js',__FILE__ ),array(), '1.0.1', true );
			wp_enqueue_script( 'jquery_validity_script', plugins_url( '/js/jquery.validity.js',__FILE__ ),array(), '1.0.1', true );
			wp_enqueue_script( 'gr_welcome_script', plugins_url( '/js/grwelcome.js',__FILE__ ),array(), '1.0.1', true );
			
		}

		
		/**
		 * Menu Callback
		 */     
		public function plugin_settings_page()
		{
			if(!current_user_can('manage_options'))
			{
				wp_die(__('You do not have sufficient permissions to access this page.'));
			}

			// Render the settings template
				$login_url	='';
				if(get_option('wel_apps_register', 0 )	== 1){
					$arr['id_apps']		=	get_option('wel_apps_id', 0 );
					$arr['id_site']		=	get_option('wel_apps_appid', 0 );
					
					$arr['admin_email']	=	get_option('wel_admin_email');
					$arr['payload']		=	get_option('wel_apps_payload', 0 );
										
					$login_url	=	'https://appsmav.com/login/index/autologin?id_apps='.$arr['id_apps'].'&id_site='.$arr['id_site'].'&admin_email='.$arr['admin_email'].'&payload='.$arr['payload'];
				 }
				 
				include(sprintf("%s/templates/settings.php", dirname(__FILE__)));

		} // END public function plugin_settings_page()
		
		public function wc_ajax_wccheck_settings(){
			
			$email	=	get_option('wel_admin_email');
			if(isset($_POST['admin_email']))
				$email	=	$_POST['admin_email'];
				
			$param['email_id']		=	$email;
			$param["app"] 			=	'wc';
			$param["action"] 		=	"verifyAccount"; 
			
			
			$url	=	$this->api_url;
			$ch = curl_init();
			curl_setopt($ch,CURLOPT_URL,$url);
			curl_setopt($ch,CURLOPT_HEADER,0);
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $param); 
			$response = curl_exec($ch);
			curl_close($ch);

			
			$res = json_decode($response, true);
			if($res['error'] == 1){
				$res['gr_reg']	=	2;
			}else if($res['is_shop'] == 1 && $res['is_valid'] == 1){
			
				$res['gr_reg']	=	0;
				update_option( 'wel_apps_id', $res['id_apps']);
				update_option( 'wel_apps_appid', $res['id_site']);
				update_option( 'wel_apps_payload', $res['pay_load']);
				update_option( 'wel_admin_email', $param['email_id']);
				update_option( 'wel_apps_register', 1 );
				$res['login_url']	=	'https://appsmav.com/login/index/autologin?id_apps='.$res['id_apps'].'&id_site='.$res['id_site'].'&admin_email='.$param['email_id'].'&payload='.$res['pay_load'];
				
			}
							
			die(json_encode($res));
		}
		
		public function wc_ajax_wccreate_account(){
			self::callAcctRegister($_POST);
		}
		
		private function callAcctRegister($p){
		
			$params["action"] = "createaccount"; 
			$params["firstname"] = $p['wel_reg_firstname'];
			$params["lastname"] = $p['wel_reg_lastname'];
			$params["companyname"] = $p['wel_reg_companyname'];
			$params["email"] = $p['wel_reg_email'];
			$params["address1"] = $p['wel_reg_address1'];
			$params["city"] = $p['wel_reg_city'];
			$params["state"] = $p['wel_reg_state'];
			$params["postcode"] = $p['wel_reg_postcode'];
			$params["country"] = $p['wel_reg_country'];
			$params["currency"] = ($params["country"] === 'AU')? 3:1;
			$params["phonenumber"] = $p['wel_reg_phonenumber'];
			$params["notes"] = 'Wordpress';
			$params["app"] = 'wc';
		
			$url = $this->api_url;
			$ch = curl_init();
			curl_setopt($ch,CURLOPT_URL,$url);
			curl_setopt($ch,CURLOPT_HEADER,0);
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $params); 
			$res = curl_exec($ch);
			curl_close($ch);
			$resArr	=	json_decode($res,true);
			
			if(trim($resArr['result'])	==	'success'){
				
				$param				=	array();
				$param['id_site']	=	$resArr['service_id'];
				$param['email']		=	$params["email"];
				self::callGrConnectRegisterApi($param,$p);
			}else{
				$resArr['error']	=	1;
				die(json_encode($resArr));
			}
			
		}
		
		private function callGrConnectRegisterApi($params,$p)
		{
			$param['email_id']		=	$params['email'];
			$param["app"] 			=	'wc';
			$param["action"] 		=	"verifyAccount";
			
			$url	=	$this->api_url;
			$ch = curl_init();
			curl_setopt($ch,CURLOPT_URL,$url);
			curl_setopt($ch,CURLOPT_HEADER,0);
			curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $param); 
			$response = curl_exec($ch);
			curl_close($ch);

			
			$res = json_decode($response, true);
			
			if($res['error']	==	0){
				update_option( 'wel_apps_id', $res['id_apps']);
				update_option( 'wel_apps_appid', $params['id_site']);
				update_option( 'wel_apps_payload', $res['pay_load']);
				update_option( 'wel_admin_email', $params['email']);
				update_option( 'wel_apps_register', 1 );
								
				$admin_email	=	$params['email'];
				$payload		=	$res['pay_load'];
					
				$res['login_url']	=	'https://appsmav.com/login/index/autologin?id_apps='.$res['id_apps'].'&id_site='.$params['id_site'].'&admin_email='.$admin_email.'&payload='.$payload;
				$response	=	json_encode($res);	
			}
			die($response);
		}	

    } // END class GR_Connect
} // END if(!class_exists('GR_Connect'))


if(class_exists('Welcome_Appsmav'))
{
    // Installation and uninstallation hooks
    register_activation_hook(__FILE__, array('Welcome_Appsmav', 'activate'));
    register_deactivation_hook(__FILE__, array('Welcome_Appsmav', 'deactivate'));

    // instantiate the plugin class
    $wel_appsmav = new Welcome_Appsmav();
	
	// Add the settings link to the plugins page
    function plugin_welappsmav_settings_link($links)
    { 
        $settings_link = '<a href="options-general.php?page=welappsmav">Settings</a>'; 
        array_unshift($links, $settings_link); 
        return $links; 
    }

    $plugin = plugin_basename(__FILE__); 
    add_filter("plugin_action_links_$plugin", 'plugin_welappsmav_settings_link');
	add_shortcode('welcome-appsmav-show', array( 'Welcome_Appsmav', 'wel_appsmav_show_func' ) );
}