<?php

namespace Dolphy\Plugin\WooCommerce\Gateways;

use Dolphy\Plugin\Exceptions\Exception;
use Dolphy\Plugin\Helpers\WooCommerce;
use Dolphy\Plugin\Option\Payment\Paystack as PaystackOption;
use Exception as GlobalException;
use WC_Payment_Gateway;
use Yabacon\Paystack as YabaconPaystack;

// require_once CYBERPULL_AUTOLOAD_PAYSTACK;

if (WooCommerce::isPaymentGatewayActive() && WooCommerce::isPaystackEnabled()) {

  class Paystack extends WC_Payment_Gateway {

    function __construct() {
      $this->id = 'paystack';
      $this->icon = DOLPHY_ASSETS.'/images/paystack-small.png';
      $this->has_fields = false; // in case you need a custom credit card form
      $this->method_title = 'Paystack';
      $this->method_description = 'Give your customers the gift of modern, frictionless, painless payments. Integrate Paystack once and let your customers pay you however they want.';

      // gateways can support subscriptions, refunds, saved payment methods,
      // but in this tutorial we begin with simple payments
      $this->supports = array(
        'products'
      );

      // Method with all the options fields
      $this->init_form_fields();

      // Load the settings.
      $this->init_settings();

      $paystack = PaystackOption::instance();

      $this->title = $this->get_option('title');
      if (empty($this->title)) {
        $this->title = $paystack->title;
      }

      $this->description = $this->get_option('description');
      if (empty($this->description)) {
        $this->description = $paystack->description;
      }

      $this->enabled = $this->get_option('enabled');

      // This action hook saves the settings
      add_action("woocommerce_update_options_payment_gateways_{$this->id}", array($this, 'process_admin_options'));

      // We need custom JavaScript to obtain a token
      add_action('wp_enqueue_scripts', array($this, 'payment_scripts'));

      // You can also register a webhook here
      add_action('woocommerce_api_cyberpull-verify-paystack', array($this, 'webhook'));
    }

    public function init_form_fields() {
      $paystack = PaystackOption::instance();

      $this->form_fields = array(
        'enabled' => array(
          'title'       => 'Enable/Disable',
          'label'       => 'Enable Paystack Gateway',
          'type'        => 'checkbox',
          'description' => '',
          'default'     => 'no'
        ),

        'title' => array(
          'title'       => 'Title',
          'type'        => 'text',
          'description' => 'This controls the title which the user sees during checkout.',
          'default'     => $paystack->title,
        ),

        'description' => array(
          'title'       => 'Description',
          'type'        => 'textarea',
          'description' => 'This controls the description which the user sees during checkout.',
          'default'     => $paystack->description,
        ),
      );
    }

    public function payment_fields() {
      echo wpautop(wp_kses_post($this->description));
    }

    public function payment_scripts() {
      //
    }

    public function validate_fields() {
      //
    }

    public function process_payment($orderId) {
      try {
        $order = wc_get_order($orderId);
        $paystack = PaystackOption::instance();

        $user = $order->get_user();
        $amount = $order->get_total() * 100;

        $options = array(
          'amount' => $amount,
          'email' => $user->user_email,
          'callback_url' => site_url('/wc-api/cyberpull-verify-paystack/'),
        );

        // currency

        $metadata = array(
          'name' => $user->display_name,
          'email' => $options['email'],
          'orderId' => $orderId
        );

        $options['metadata'] = $metadata;

        $sdk = new YabaconPaystack($paystack->secretKey);
        $trx = $sdk->transaction->initialize($options);

        if(!$trx->status) {
          throw new Exception($trx->message);
        }

        return array(
          'result' => 'success',
          'redirect' => $trx->data->authorization_url
        );
      } catch (GlobalException $e) {
        wc_add_notice($e->getMessage(), 'error');
      }
    }

    public function webhook() {
      global $woocommerce;

      try {
        $paystack = PaystackOption::instance();

        $sdk = new YabaconPaystack($paystack->secretKey);

        if (!array_key_exists('reference', $_GET)) {
          throw new Exception('Invalid Payment Reference!');
        }

        $reference = sanitize_key($_GET['reference']);

        $trx = $sdk->transaction->verify([
          'reference' => $reference
        ]);

        // status should be true if there was a successful call
        if(!$trx->status) throw new Exception($trx->message);

        $data = $trx->data;

        if (!isset($data->metadata->orderId)) {
          throw new Exception('Unable to retrieve order ID!');
        }

        $orderId = $data->metadata->orderId;

        if (($order = wc_get_order($orderId)) === false) {
          throw new Exception('Unable to retrieve order!');
        }

        $returnUrl = $this->get_return_url($order);
        $orderStatus = $order->get_status();

        if ($orderStatus === 'completed') {
          throw new Exception('This order has already been completed!');
        }

        if ($orderStatus !== 'pending') {
          throw new Exception('This order is currently not pending!');
        }

        if ($data->status != 'success') {
          $order->update_status('failed', 'You payment failed with status: '.$data->gateway_response);
          wp_redirect($returnUrl);
        }

        $amount = $data->amount / 100;

        $order->payment_complete();
        $order->reduce_order_stock();

        $order->add_order_note('Your payment has been received. We will get back to you shortly. Thank you!', true);

        // Empty cart
        $woocommerce->cart->empty_cart();

        wp_redirect($returnUrl);

      } catch (GlobalException $e) {
        wp_die($e->getMessage());
      }
    }

  }

}
