<?php
/*
  Plugin Name: Paywerk Payments
  Description: Extends WooCommerce by adding payment options through Paywerk
  Version: SET_PAYWERK_VERSION
  Author: Paywerk
  Author URI: https://paywerk.co/en/about/
  Text Domain: paywerk-payments
  License: GPL-2.0+
  License URI: http://www.gnu.org/licenses/gpl-2.0.txt
  Domain Path: /languages
*/

use Automattic\WooCommerce\Utilities\FeaturesUtil;
use Automattic\WooCommerce\Blocks\Payments\PaymentMethodRegistry;

global $supported_langs, $lang;
$lang = preg_split('/_/', get_locale())[0];
$supported_langs = array('en', 'et', 'pl');

class PaywerkSettings {
  const DEFAULT_URL = 'https://checkout.paywerk.co';
  const DEFAULT_SANDBOX_URL = 'https://checkout.sandbox.paywerk.co';
  const DEFAULT_SHOPPER_PORTAL_URL = 'https://shopper.paywerk.co';
  const PAYWERK_PLUGIN_SETTINGS = 'woocommerce_paywerk-payments_settings';
  const TEXT_DOMAIN = 'paywerk-payments';

  public static function correctPaywerkUrl($settings) {
    if (empty($settings)) return $settings;
    switch ($settings['sandbox']) {
      case 'yes':
        if (!isset($settings['url']) || $settings['url'] == PaywerkSettings::DEFAULT_URL) $settings['url'] = PaywerkSettings::DEFAULT_SANDBOX_URL;
        break;
      default:
        $settings['url'] = PaywerkSettings::DEFAULT_URL;
    }
    return $settings;
  }
}

if (!defined('WPINC')) die;
const PAYWERK_VERSION = 'SET_PAYWERK_VERSION';

// Docs: https://docs.woocommerce.com/document/payment-gateway-api/

function paywerk_payments_init() {
	if (!class_exists('WC_Payment_Gateway')) return;

	require_once('paywerk-payments.php');
	require_once('paywerk-order-request.php');
	add_filter('woocommerce_payment_gateways', 'paywerk_add_gateway');
}

function paywerk_promotions_init() {
  require_once('paywerk-promotions.php');
  $settings = get_option(PaywerkSettings::PAYWERK_PLUGIN_SETTINGS, null);

  new PaywerkPromotions($settings);
}

function paywerk_add_gateway($methods) {
  $methods[] = new PaywerkPayments();
  return $methods;
}

function paywerk_action_links($links) {
  $plugin_links = array(
		'<a href="'.admin_url('admin.php?page=wc-settings&tab=checkout').'">'.__('Settings').'</a>',
	);
	return array_merge($plugin_links, $links);
}

function paywerk_handle_update_order_review($data) {
  $output = array();
  parse_str($data, $output);
  WC()->session->set("customerCheckoutFields", $output);

  $orderReference = WC()->session->get("orderReference");
  WC()->session->set("orderReference", $orderReference ?: uniqid('5'));
}

function paywerk_remove_admin_notices() {
  WC_Admin_Notices::remove_notice('pw_fulfil_notice');
  WC_Admin_Notices::remove_notice('pw_fulfil_success');
}

function paywerk_load_plugin_translations() {
  load_plugin_textdomain(PaywerkSettings::TEXT_DOMAIN, FALSE, basename(dirname(__FILE__)) . '/languages/');
}

function paywerk_uninstall_plugin() {
  delete_option(PaywerkSettings::PAYWERK_PLUGIN_SETTINGS);
}

function paywerk_plugin_update_finished($upgrader_object, $options) {
  $isPaywerkPlugin = $upgrader_object->new_plugin_data['TextDomain'] == PaywerkSettings::TEXT_DOMAIN;

  if ($isPaywerkPlugin) {

    $settings = get_option(PaywerkSettings::PAYWERK_PLUGIN_SETTINGS, null);

    $url = PaywerkSettings::correctPaywerkUrl($settings)['url'];

    $settings = array(
      'apiKey' => $settings['apiKey'],
      'sandbox' => $settings['sandbox'],
      'url' => $url,
      'enabled' => $settings['enabled']
    );

    update_option(PaywerkSettings::PAYWERK_PLUGIN_SETTINGS, $settings);
  }
}

function paywerk_add_module_type_script($tag, $handle, $src) {
  if ( 'paywerk' !== $handle ) {
    return $tag;
  }

  return '<script type="module" src="' . esc_url( $src ) . '" async></script>';
}

function paywerk_custom_js() {
  $settings = get_option(PaywerkSettings::PAYWERK_PLUGIN_SETTINGS, null);
  if (empty($settings)) return;

  $url = PaywerkSettings::correctPaywerkUrl($settings)['url'];

  wp_enqueue_script('paywerk', esc_url($url) . '/ui/shop.js');
}

function paywerk_custom_style() {
  wp_enqueue_style('paywerk-style', plugins_url('/css/paywerk.css', __FILE__), false, '1.0.0', 'all');
}

function paywerk_declare_cart_checkout_block() {
    FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__, true);
}

function register_paywerk_payment_type()
{
  require_once plugin_dir_path(__FILE__) . 'paywerk-gateway-block.php';
  add_action('woocommerce_blocks_payment_method_type_registration',
    function (PaymentMethodRegistry $payment_method_registry) {
      $payment_method_registry->register(new PaywerkGatewayBlock);
    }
  );
}

register_uninstall_hook(__FILE__, 'paywerk_uninstall_plugin');

add_action('plugins_loaded', 'paywerk_payments_init');
add_action('plugins_loaded', 'paywerk_promotions_init');

add_action('upgrader_process_complete', 'paywerk_plugin_update_finished', 10, 2);
add_action('plugins_loaded', 'paywerk_load_plugin_translations');
add_action('woocommerce_checkout_update_order_review', 'paywerk_handle_update_order_review', 200, 1);
add_action('admin_footer', 'paywerk_remove_admin_notices', 9999, 0);
add_filter('plugin_action_links_'.plugin_basename(__FILE__), 'paywerk_action_links');

add_action('wp_enqueue_scripts', 'paywerk_custom_js');
add_action('wp_head', 'paywerk_custom_style');
add_filter('script_loader_tag', 'paywerk_add_module_type_script' , 10, 3);
add_action('before_woocommerce_init', 'paywerk_declare_cart_checkout_block');
add_action('woocommerce_blocks_loaded', 'register_paywerk_payment_type');
