<?php
/**
 * Plugin Name: Mozola Ventures Admin
 * Description: Administration plugin for websites hosted by Mozola Ventures Corp
 * Version: 1.0.5
 * Author: Mozola Ventures Corp.
 * Author URI: https://mozolaventures.com
 */

if ( ! defined( 'WPINC' ) ) {
    die;
}

include('config.inc.php');

define (ICON_SVG, 'data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0idXRmLTgiPz4NCjwhLS0gR2VuZXJhdG9yOiBBZG9iZSBJbGx1c3RyYXRvciAxNi4wLjAsIFNWRyBFeHBvcnQgUGx1Zy1JbiAuIFNWRyBWZXJzaW9uOiA2LjAwIEJ1aWxkIDApICAtLT4NCjwhRE9DVFlQRSBzdmcgUFVCTElDICItLy9XM0MvL0RURCBTVkcgMS4xLy9FTiIgImh0dHA6Ly93d3cudzMub3JnL0dyYXBoaWNzL1NWRy8xLjEvRFREL3N2ZzExLmR0ZCI+DQo8c3ZnIHZlcnNpb249IjEuMSIgaWQ9IkxheWVyXzEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiIHg9IjBweCIgeT0iMHB4Ig0KCSB3aWR0aD0iMTZweCIgaGVpZ2h0PSIxNnB4IiB2aWV3Qm94PSIwIDAgMTYgMTYiIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDE2IDE2IiB4bWw6c3BhY2U9InByZXNlcnZlIj4NCjxnPg0KCTxwYXRoIGZpbGw9IiMwMDAwMDAiIGQ9Ik0xMC44MTgsMC41OThjMS42NDYsMC45NjgsMi43NTEsMi43NTYsMi43NTEsNC44MDNjMCwzLjA3Ni0yLjQ5Myw1LjU2OS01LjU2OSw1LjU2OQ0KCQljLTMuMDc1LDAtNS41NjgtMi40OTQtNS41NjgtNS41NjljMC0yLjA0NywxLjEwNS0zLjgzNSwyLjc1LTQuODAzQzIuMiwxLjczNCwwLjA4LDQuNjE5LDAuMDgsOGMwLDQuMzc0LDMuNTQ2LDcuOTIsNy45Miw3LjkyDQoJCXM3LjkyLTMuNTQ2LDcuOTItNy45MkMxNS45Miw0LjYxOSwxMy44MDEsMS43MzQsMTAuODE4LDAuNTk4eiIvPg0KCTxnPg0KCQk8cGF0aCBmaWxsPSIjMDAwMDAwIiBkPSJNNy4zMiwxMC45NzFMNS4wMywwLjA4aDIuMjM1bDAuNzI3LDIuMjdsMC43MzEtMi4yN2gyLjI0N2wtMi4yOSwxMC44OTFWNS41MThMNy45OTIsNy42MjRMNy4zMiw1LjUxOA0KCQkJVjEwLjk3MXoiLz4NCgk8L2c+DQo8L2c+DQo8L3N2Zz4NCg==');

// this allows for the plugin to be check for new versions
require 'library/plugin-update-checker/plugin-update-checker.php';
$MyUpdateChecker = new PluginUpdateChecker_3_1('http://plugins.mozolaventures.com/wordpress/mozola-ventures-admin.json', __FILE__, 'mozola-ventures-admin');

// initial registration
register_activation_hook( __FILE__, 'mvadmin_activation' );

// put the site into restricted mode if we are past the expiry date (allows a grace period based on Site account info)
add_action('get_header', 'mvadmin_site_closed');


// trying to  add custom css for this plugin... not working right now
//add_action( 'wp_enqueue_scripts', 'mvadmin_register_plugin_styles' );

// add menus to administration pages
add_action( 'admin_menu', 'mvadmin_add_menus' );
add_action( 'admin_init', 'mvadmin_settings_init' );

// add custom dashboard widgets
add_action( 'wp_dashboard_setup', 'mvadmin_add_dashboard_widgets' );

function mvadmin_site_closed() {
	// need to check to see if we are past the expiry date (allows a grace period based on Site account info)
	$options = get_option( 'mvadmin_settings' );
	$key = $options['mvadmin_key'];
	
	$closed = true;

	if ($key != '') {
		$request = MVADMIN_WEBSERVICE . '/site/expirydate?key=' . $key;

		if (mvadmin_use_curl()) {
			$ch = curl_init($request); // start CURL - set URL
			
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get the response as a variable
			$jsonData = curl_exec($ch); // connect and get your JSON response
			
			$data = json_decode($jsonData,true);
			//$info = curl_getinfo($ch);
		} else {
			$response = wp_remote_get($request);
			$data = json_decode(wp_remote_retrieve_body($response),true);
		}
		
		$closed = $data['Closed'];
	}
	
	if ($closed && (!current_user_can('mvadmin_renew') || !is_user_logged_in())) {
		wp_die('<h1 style="color:red">Website Currently Offline</h1><br />Contact the site administrator if you need access!');
	}
}

function mvadmin_activation() {
	// create the admin role
	$editorRole = get_role('editor');

	remove_role('admin');	// this is only to remove the existing role to reassign with new capabilities
	$adminRole = add_role('admin', 'Admin', $editorRole->capabilities); // copy the capabilities from the editor role
	// add new capabilities - starting with the users
	$adminRole->add_cap('create_users');
	$adminRole->add_cap('delete_users');
	$adminRole->add_cap('edit_users');
	$adminRole->add_cap('list_users');
	$adminRole->add_cap('promote_users');
	$adminRole->add_cap('remove_users');
	// add custom capability for this plugin
	$adminRole->add_cap('mvadmin_renew');
	
	// add custom capability for this plugin to the administrator role as well
	$administratorRole = get_role('administrator');
	$administratorRole->add_cap('mvadmin_renew');
}

function mvadmin_add_dashboard_widgets() {
	if (current_user_can('mvadmin_renew')) {
		wp_add_dashboard_widget ('mvadmin_dashboard_site_renew_widget', 'Site Renewal', 'mvadmin_dashboard_site_renew_widget');
	}
}

function mvadmin_dashboard_site_renew_widget($post, $callback_args) {
	$options = get_option( 'mvadmin_settings' );
	$key = $options['mvadmin_key'];
	
	$expiryDate = __('Unable to retrieve Expiry Date...'); $renewalCost = '';
	
	if ($key != '') {
		$request = MVADMIN_WEBSERVICE . '/site?key=' . $key;

		if (mvadmin_use_curl()) {
			$ch = curl_init($request); // start CURL - set URL
			
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get the response as a variable
			$jsonData = curl_exec($ch); // connect and get your JSON response
			
			$data = json_decode($jsonData,true);
			//$info = curl_getinfo($ch);
		} else {
			$response = wp_remote_get($request);
			$data = json_decode(wp_remote_retrieve_body($response),true);
		}
		
		if (isset($data['Expiry_Date'])) {
			$expiryDate = $data['Expiry_Date'];
		}
		
		if (isset($data['Charges']) && $data['Renew_Now']) {
			$renewalCost .= '<table class="mvadmin-renewal-cost">';
			foreach ($data['Charges'] as $row) {
				$rowCost = $row['Quantity'] * $row['Price'];
				$renewalCost .= '<tr><td>' . $row['Description'] . '</td><td style="text-align:right; padding-left:10px;">$' . number_format($rowCost, 2) . '</td></tr>';
				$subTotal += $rowCost;
				$currency = $row['Currency'];
			}
			if ($currency == 'CAD') {
				$taxes = round($subTotal * 0.13, 2);
				$renewalCost .= '<tr><td style="text-align:right;">' . __('HST') . '</td><td style="text-align:right; padding-left:10px;">$' . number_format($taxes, 2) . '</td></tr>';
			}
			if (count($data) > 1 || $taxes > 0) {
				$renewalCost .= '<tr><td style="text-align:right;">' . __('Total') . '</td><td style="text-align:right; padding-left:10px; border-top:1px solid;">$' . number_format($subTotal + $taxes, 2) . '</td></tr>';
			}
			$renewalCost .= '</table>';
			
		}
	}
	?>
    <div id="mvadmin-widget">
    	<div class="activity-block">
        	<h3><?php echo __('Expiry Date') . ' ' . $expiryDate; ?></h3>
            <?php
			if ($renewalCost != '') {
            	echo $renewalCost;
                mvadmin_paypal_button($key);
            }
			?>
        </div>
    </div>
    <?php
}

function mvadmin_paypal_button($key) {
	?>
    
    <script src="https://www.paypalobjects.com/api/checkout.js"></script>

    <script>

    paypal.Button.render({
        env: '<?php echo PAYPAL_BUTTON_ENV; ?>',

        commit: true, // Show a 'Pay Now' button

        payment: function() {
            var CREATE_PAYMENT_URL = '<?php echo plugins_url( 'proxy.php?url=', __FILE__ ) . rawurlencode(MVADMIN_WEBSERVICE . '/paypal/createpayment?key=' . $key); ?>';
            
            return paypal.request.post(CREATE_PAYMENT_URL).then(function(res) {
                return res.id;
            });
        },

        onAuthorize: function(data, actions) {
            var EXECUTE_PAYMENT_URL = '<?php echo plugins_url( 'proxy.php?url=', __FILE__ ) . rawurlencode(MVADMIN_WEBSERVICE . '/paypal/executepayment'); ?>';

            return paypal.request.post(EXECUTE_PAYMENT_URL, {
                paymentID: data.paymentID,
                payerID: data.payerID,
                key: '<?php echo $key; ?>'
            }).then(function(res) {
                // The payment is complete!
                // You can now show a confirmation message to the customer
                window.alert('Thank you for your payment!');
                location.reload();
            });
        }

    }, '#paypal-button');
    </script>    

    <div id="paypal-button"></div>
    <?php
}

function mvadmin_add_menus() { 
	$siteRenewalNotification = '';
	
	$options = get_option( 'mvadmin_settings' );
	$key = $options['mvadmin_key'];
	if ($key != '') {
		$request = MVADMIN_WEBSERVICE . '/site/expirydate?key=' . $key;
		
		if (mvadmin_use_curl()) {
			$ch = curl_init($request); // start CURL - set URL
			
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get the response as a variable
			$jsonData = curl_exec($ch); // connect and get your JSON response
			
			$data = json_decode($jsonData,true);
			//$info = curl_getinfo($ch);
		} else {
			$response = wp_remote_get($request);
			$data = json_decode(wp_remote_retrieve_body($response),true);
		}
		
		if ($data['Renew_Now'] == 1) {
			$siteRenewalNotification = ' <span class="update-plugins count-1"><span class="pending-count" style="font-weight:bold;">!</span></span>';
		}
	}
	
	add_menu_page( 'Site Renewal', 'Site Renewal' . $siteRenewalNotification, 'mvadmin_renew', 'mvadmin-site-renewal', 'mvadmin_site_renewal_page', ICON_SVG, 3 );
	add_menu_page( 'Mozola Ventures', 'Mozola Ventures', 'manage_options', 'mozola-ventures-admin', 'mvadmin_options_page', ICON_SVG );
}

function mvadmin_options_page() { 
	echo '<form action="options.php" method="post">';
	echo '<h1>';
	echo 'Mozola Ventures';
	if (IS_DEV) { echo ' (DEV)'; }
	echo '</h1>';

	settings_fields( 'mvadmin-settings' );
	do_settings_sections( 'mvadmin-settings' );
	submit_button();
	
	echo '</form>';
}

function mvadmin_register_plugin_styles() {
	wp_register_style( 'mvadmin-style', plugins_url( '/' , __FILE__ ) . 'assets/css/style.css' );
	wp_enqueue_style( 'mvadmin-style' );
}

function mvadmin_site_renewal_page() {
	if (current_user_can('mvadmin_renew')) {
		$options = get_option( 'mvadmin_settings' );
		$key = $options['mvadmin_key'];
		
		$expiryDate = __('Unable to retrieve Expiry Date...'); $renewalCost = '';
		
		if ($key != '') {
			$request = MVADMIN_WEBSERVICE . '/site?key=' . $key;

			if (mvadmin_use_curl()) {
				$ch = curl_init($request); // start CURL - set URL
				
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get the response as a variable
				$jsonData = curl_exec($ch); // connect and get your JSON response
				
				$data = json_decode($jsonData,true);
				//$info = curl_getinfo($ch);
			} else {
				$response = wp_remote_get($request);
				$data = json_decode(wp_remote_retrieve_body($response),true);
			}
			
			if (isset($data['Expiry_Date'])) {
				$expiryDate = $data['Expiry_Date'];
			}
			
			if (isset($data['Charges']) && $data['Renew_Now']) {
				$renewalCost .= '<table class="mvadmin-renewal-cost">';
				foreach ($data['Charges'] as $row) {
					$rowCost = $row['Quantity'] * $row['Price'];
					$renewalCost .= '<tr><td>' . $row['Description'] . '</td><td style="text-align:right; padding-left:10px;">$' . number_format($rowCost, 2) . '</td></tr>';
					$subTotal += $rowCost;
					$currency = $row['Currency'];
				}
				if ($currency == 'CAD') {
					$taxes = round($subTotal * 0.13, 2);
					$renewalCost .= '<tr><td style="text-align:right;">' . __('HST') . '</td><td style="text-align:right; padding-left:10px;">$' . number_format($taxes, 2) . '</td></tr>';
				}
				if (count($data) > 1 || $taxes > 0) {
					$renewalCost .= '<tr><td style="text-align:right;">' . __('Total') . '</td><td style="text-align:right; padding-left:10px; border-top:1px solid;">$' . number_format($subTotal + $taxes, 2) . '</td></tr>';
				}
				$renewalCost .= '</table>';
			}
		}
		?>
        
		<h1><?php echo __('Site Renewal'); ?></h1>
        
		<div><?php echo __('Expiry Date') . ' ' . $expiryDate; ?></div>
        
		<?php
		if ($renewalCost != '') {
			echo $renewalCost;
			mvadmin_paypal_button($key);
		}
		
		// get and display the list of receipts
		if ($key != '') {
			$request = MVADMIN_WEBSERVICE . '/site/receipts?key=' . $key;
			
			if (mvadmin_use_curl()) {
				$ch = curl_init($request); // start CURL - set URL
				
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // get the response as a variable
				$jsonData = curl_exec($ch); // connect and get your JSON response
				
				$data = json_decode($jsonData,true);
				//$info = curl_getinfo($ch);
			} else {
				$response = wp_remote_get($request);
				$data = json_decode(wp_remote_retrieve_body($response),true);
			}
			
			if (count($data) > 0) {
				echo '<h1>' . __('Receipts') . '</h1>';
				echo '<table>';
				foreach ($data as $row) {
					echo '<tr>';
					echo '<td>' . substr($row['create_time'],0,10) . '</td>';
					echo '<td style="padding-left:10px;">' . $row['sale_id'] . '</td>';
					echo '<td style="text-align:right; padding-left:10px;">$' . $row['amount']['total'] . ' ' . $row['amount']['currency'] . '</td>';
					echo '<td style="padding-left:10px;"><a href="' . plugins_url( 'receipt.php?key=' . $key . '&id=' . $row['id'] . '&sale_id=' . $row['sale_id'], __FILE__ ) . '" target="_blank">' . __('pdf') . '</a></td>';
					echo '</tr>';
				}
				echo '</table>';
			}
		}
	}
}

function mvadmin_settings_init() { 
	register_setting( 'mvadmin-settings', 'mvadmin_settings' );

	add_settings_section(
		'mvadmin-settings-section', 
		__( 'Settings' ), 
		'mvadmin_section_settings_callback', 
		'mvadmin-settings'
	);

	add_settings_field( 
		'mvadmin_key', 
		__( 'Site Key' ), 
		'mvadmin_key_render', 
		'mvadmin-settings', 
		'mvadmin-settings-section' 
	);

	add_settings_field( 
		'mvadmin_use_curl', 
		__( 'Use CURL' ), 
		'mvadmin_use_curl_render', 
		'mvadmin-settings', 
		'mvadmin-settings-section' 
	);
}

function mvadmin_section_settings_callback() { 
}

function mvadmin_key_render() { 
	$options = get_option( 'mvadmin_settings' );
	?>
	<input type='text' name='mvadmin_settings[mvadmin_key]' value='<?php echo $options['mvadmin_key']; ?>'>
	<?php
}

function mvadmin_use_curl_render() { 
	$options = get_option( 'mvadmin_settings' );
	?>
	<input type='checkbox' name='mvadmin_settings[mvadmin_use_curl]' value="1" '<?php echo checked(1, $options['mvadmin_use_curl'], false); ?>'>
	<?php
}

function mvadmin_use_curl() {
	$useCurl = false;

	$options = get_option( 'mvadmin_settings' );
	if ($options['mvadmin_use_curl'] == 1) { $useCurl = true; }
	
	return $useCurl;
}
?>