<?php
/*
  Plugin Name: Ninja Square Integration (Premium)
  Plugin URL: https://apiexperts.io/solutions/square-integration-with-ninja-forms/
  Description: Payment in ninja form using square payment method
  Version: 3.2

  Update URI: https://api.freemius.com
  Text Domain: ninja-square
  Author: apiexperts.io
  Author URI: https://apiexperts.io
 */
// Exit if accessed directly
if (!defined('ABSPATH')) {
    exit;
}

add_action('plugins_loaded', 'ninja_square_plugin_dependencies', 9);
add_action('plugins_loaded', 'ninja_define_square_app_constants', 8);
add_action('init', 'ninja_authorize_with_square');
add_action('init', 'ninja_square_callback_success');
add_action('init', 'ninja_square_disconnect');
add_action('admin_enqueue_scripts', 'ninja_enqueue_style', 999);

add_action('admin_menu', 'ninja_custom_menus');
	function ninja_custom_menus(){
		
		add_menu_page('NinjaForm Square', 'NinjaForm Square', 'manage_options', get_admin_url() . 'admin.php?page=nf-settings');
			add_submenu_page(get_admin_url() . 'admin.php?page=nf-settings', 'NinjaForm Square', 'NinjaForm Square', 'manage_options', get_admin_url() . 'admin.php?page=nf-settings');
			add_submenu_page( get_admin_url() . 'admin.php?page=nf-settings', __( 'Support', 'ninja-square' ), __( 'Support', 'ninja-square' ), 'manage_options', 'http://support.apiexperts.io/' );

			/* Technical Documentation */
			add_submenu_page( get_admin_url() . 'admin.php?page=nf-settings', __( 'Technical Documentation', 'ninja-square' ), __( 'Technical Documentation', 'ninja-square' ), 'manage_options', 'https://apiexperts.io/documentation/ninja-forms-with-square-payment-gateway/' );

			/* Contact Us */
			add_submenu_page( get_admin_url() . 'admin.php?page=nf-settings', __( 'Customization', 'ninja-square' ), __( 'Customization', 'ninja-square' ), 'manage_options', 'https://apiexperts.io/contact-us/' );
	}

function ninja_square_plugin_dependencies()
{

    if (!class_exists('Ninja_Forms')) {
        add_action('admin_notices', 'ninja_square_admin_notices');
    } else {
        define("NINJA_SQUARE_INTEGRATION_PATH", plugin_dir_path(__FILE__));
        define("NINJA_SQUARE_INTEGRATION_URL", plugin_dir_url(__FILE__));
        require_once(NINJA_SQUARE_INTEGRATION_PATH . 'lib/ninja_freemius.php');
        global $in_fs;

        if (in_fs()->is__premium_only()) {
            if (in_fs()->can_use_premium_code()) {
                update_option('is_square_premium_active' , 'active');
                require_once(NINJA_SQUARE_INTEGRATION_PATH . 'classes/ninja-square-core.php');
                require_once(NINJA_SQUARE_INTEGRATION_PATH . 'lib/square-sdk/autoload.php');
                require_once(NINJA_SQUARE_INTEGRATION_PATH . 'classes/ninja-square-settings.php');
            } else {
                delete_option('is_square_premium_active');    
            }
        }
    }
}


function ninja_check_square_expiry($expires_at = false)
{


    if ($expires_at !== false && $expires_at !== '') {
        $date_time = explode('T', $expires_at);


        $date_time[1] = str_replace("Z", "", $date_time[1]);

        $expires_at = strtotime($date_time[0].' '.$date_time[1]);
        $today = strtotime("now");

        if ($today >= $expires_at) {
            return "expired";
        } else {
            return "active";
        }
    }
}

function ninja_renew_square_token($expires_at, $refresh_access_token)
{

    $expiry_status = ninja_check_square_expiry($expires_at);

    if ($expiry_status == 'expired') {
        $oauth_connect_url = NINJA_MIDDLE_SERVER_URL;

        $args_renew = array(

            'body' => array(

                'refresh_token' => $refresh_access_token,
                'oauth_version' => 2,
                'request_type' => 'renew_token'
            ),
            'timeout' => 45

        );

        $oauth_response = wp_remote_post($oauth_connect_url, $args_renew);
        return json_decode($oauth_response['body']);
    }
}


function ninja_general_settings_token_renewal()
{


    $options = get_option('square_setting_options', array());

    if (isset($options['square_setting_expires_at']) && isset($options['square_live_refresh_token'])) {
        $expires_at = $options['square_setting_expires_at'];
        $refresh_access_token = $options['square_live_refresh_token'];

        $decoded_response = ninja_renew_square_token($expires_at, $refresh_access_token);


        if (isset($decoded_response)) {
            $options['square_setting_expires_at'] = @$decoded_response->expires_at;
            $options['square_live_refresh_token'] = @$decoded_response->refresh_token;
            $options['square_setting_live_token'] = @$decoded_response->access_token;

            update_option('square_setting_options', $options);
        }

        $options = get_option('square_setting_options', array());
    }
}

function ninja_enqueue_style()
{
    wp_enqueue_style('ninja_square_style', plugins_url('assets/css/custom-style.css', __FILE__));
}

function ninja_square_admin_notices()
{
    ?>
    <div id="message" class="error">
        <p><?php printf(__('Ninja Square Integration requires Ninja Form to be installed!', 'ninja-square')); ?></p>
    </div>
    <?php
}

function ninja_authorize_with_square()
{

    if (!empty($_GET['ninja_prepare_connection_call']) && $_GET['ninja_prepare_connection_call']) {
        /* Creating Redirect URL with sliced parameters */
        $url_identifiers = $_REQUEST;
        unset($url_identifiers['ninja_prepare_connection_call']);
        $url_identifiers['oauth_version'] = 2;
        $redirect_url = add_query_arg($url_identifiers, admin_url($url_identifiers['admin_url']));
        $redirect_url = wp_nonce_url($redirect_url, 'connect_ninja_square', 'ninja_square_token_nonce');
        /* Creating Redirect URL with sliced parameters */

        /* Preparing payload and sending to middle server */
        $middle_server_payload = array(

            'redirect' => urlencode($redirect_url),
            'scope' => urlencode('MERCHANT_PROFILE_READ PAYMENTS_READ PAYMENTS_WRITE INVENTORY_WRITE CUSTOMERS_READ CUSTOMERS_WRITE'),
            'plug' =>  NINJA_SQUARE_PLUGIN_NAME,
            'app_name' => NINJA_SQUARE_APP_NAME,
            'oauth_version' => 2,
            'request_type' => 'authorization'
        );

        $middle_server_url = add_query_arg($middle_server_payload, NINJA_MIDDLE_SERVER_URL);
        /* Preparing payload and sending to middle server */


        $query_arg = array(
            'app_name'    => NINJA_SQUARE_APP_NAME,
            'disconnect_ninja_square' => 1,
        );
        $query_arg = array_merge($url_identifiers, $query_arg);

        $disconnect_url = admin_url($url_identifiers['admin_url']);
        $disconnect_url = add_query_arg($query_arg, $disconnect_url);


        $options = get_option('square_setting_options');
        $options['square_setting_disconnect_url'] = $disconnect_url;
        update_option('square_setting_options', $options);

        wp_redirect($middle_server_url);
    }
}

function ninja_define_square_app_constants()
{

    define("NINJA_SQUARE_PLUGIN_NAME", 'Ninja-Square-premium');
    define("NINJA_SQUARE_APP_NAME", 'NinjaIntegration');
    define("NINJA_SQUARE_APP_ID", 'sq0idp-1xkuyn7Huy2tywwTkTU1VA');
    define("NINJA_MIDDLE_SERVER_URL", 'https://connect.apiexperts.io');
    define("NINJA_APPLICATION_PERSONAL_ACCESS_TOKEN", 'EAAAEJGb6oNWgB1AsBjT13tpIn5C6hss36b8lRe4dt51Fb7h0hKQph5VcRT_LYDI');
    ninja_general_settings_token_renewal();
}

function ninja_square_disconnect()
{


    if (!empty($_REQUEST['disconnect_ninja_square'])) {
        $options = get_option('square_setting_options');
        unset($options['square_setting_live_app_id']);
        unset($options['square_setting_live_location_id']);
        unset($options['square_setting_live_token']);
        unset($options['square_setting_btn_auth']);
        unset($options['square_setting_expires_at']);
        unset($options['square_live_token_details']);
        unset($options['square_live_live_locations']);
        unset($options['square_live_refresh_token']);
        unset($options['square_setting_disconnect_url']);

        update_option('square_setting_options', $options);


        $options = get_option('square_setting_options');
        $query_args = array (
            'page' => $_REQUEST['page'],
            'plug' =>  NINJA_SQUARE_PLUGIN_NAME,
            'app_name' => NINJA_SQUARE_APP_NAME

        );

        $initial_page = add_query_arg($query_args, admin_url('admin.php'));
        ninja_revoke_square_access_token($initial_page);
        wp_redirect($initial_page);
    }
}

function ninja_revoke_square_access_token($redirect_url)
{

    $oauth_connect_url = NINJA_MIDDLE_SERVER_URL;

    $args_renew = array(

        'body' => array(

            'site_url' => $redirect_url,
            'app_name' => NINJA_SQUARE_APP_NAME,
            'oauth_version' => 2,
            'request_type' => 'revoke_token'

        ),
        'timeout' => 45

    );

    $oauth_response = wp_remote_post($oauth_connect_url, $args_renew);
    wp_redirect($redirect_url);
    exit;
}

function ninja_square_callback_success()
{

    if (!empty($_REQUEST['access_token']) and !empty($_REQUEST['token_type']) and !empty($_REQUEST['ninja_square_token_nonce']) and
        $_REQUEST['token_type'] == 'bearer') {
        if (function_exists('wp_verify_nonce') && ! wp_verify_nonce($_GET['ninja_square_token_nonce'], 'connect_ninja_square')) {
            wp_die("Looks like the URL is malformed!");
        }

        $locations = ninja_get_location($_REQUEST['access_token']);
		$loc = $locations->locations;
        $options = get_option('square_setting_options');
        $options['square_setting_live_app_id'] = NINJA_SQUARE_APP_ID;
        $options['square_setting_live_location_id'] = $loc[0]->id;
        $options['square_setting_live_token'] = $_REQUEST['access_token'];
        $options['square_setting_btn_auth'] = 'true';
        $options['square_setting_expires_at'] = $_REQUEST['expires_at'];
        $options['square_live_token_details'] = $_REQUEST;
        $options['square_live_refresh_token'] = $_REQUEST['refresh_token'];
        $options['square_live_live_locations'] = json_encode($locations);

        update_option('square_setting_options', $options);


        $query_args = array (
            'page' => $_REQUEST['page'],
        );

        $initial_page = add_query_arg($query_args, admin_url('admin.php'));
        wp_redirect($initial_page);
        exit;
    }
}

function ninja_get_location($token)
{
    $url = 'https://connect.squareup.com/v2/locations';
    $headers = array(
        'Authorization' => 'Bearer '.$token, // Use verbose mode in cURL to determine the format you want for this header
        'Content-Type'  => 'application/json;',
        'token'  => $token,
    );
    $method = "GET";
    $args = array('');
    $response = wp_remote_wcsrs($url, $args, $method, $headers);
    return $response;
}

function wp_remote_wcsrs($url, $args, $method, $headers)
{
    // $args = array( 'id' => 1234 );
    // $method = 'GET'; // or 'POST', 'HEAD', etc
    // $headers = array(
    // 'Authorization' => 'Bearer ' . $auth, // Use verbose mode in cURL to determine the format you want for this header
    // 'Accept'        => 'application/json;ver=1.0',
    // 'Content-Type'  => 'application/json; charset=UTF-8',
    // 'Host'          => 'api.example.com'
    // );
    $token = $headers['token'];
    unset($headers['token']);
    $request = array(
        'headers' => $headers,
        'method'  => $method,
    );

    if ($method == 'GET' && ! empty($args) && is_array($args)) {
        $url = add_query_arg($args, $url);
    } else {
        $request['body'] = json_encode($args);
    }

    $response = wp_remote_request($url, $request);
    $decoded_response = json_decode(wp_remote_retrieve_body($response));

    return $decoded_response;
}
function activation_check_license( $plugin ) {
    if (get_option('is_square_premium_active') != 'active') {
        if ($plugin == plugin_basename(__FILE__)) {
            exit(wp_redirect(admin_url('admin.php?page=ninja-square-settings')));
        }
    }
}

add_action( 'activated_plugin', 'activation_check_license' );