<?php

/**
 * Square Builder Payment Settings.
 *
 * @package EverestForms\Pro\Addons\Square\Builder
 * @since   1.0.0
 */


namespace  EverestForms\Pro\Addons\Square\Process;

use EverestForms\Pro\Addons\Square\Api\Api;

defined( 'ABSPATH' ) || exit;

/**
 * Payment process class.
 *
 * @since 1.0.0
 */
class Process {

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 */
	public function __construct() {

		add_action( 'everest_forms_process_complete', array( $this, 'process_entry' ), 20, 4 );

		add_action( 'wp_ajax_everest_forms_square_payment_credit_card', array( $this,'payment_credit_card' ) );
		add_action( 'wp_ajax_nopriv_everest_forms_square_payment_credit_card', array( $this,'payment_credit_card' ) );

		// Ajax Square Status.
		add_action( 'wp_ajax_evf_square_update_entry_square_payment_status', array( $this, 'update_entry_square_status' ) );
		add_action( 'wp_ajax_nopriv_evf_square_update_entry_square_payment_status', array( $this, 'update_entry_square_status' ) );

		// Delete Entry.

		add_action( 'wp_ajax_everest_forms_square_payment_delete_entry_after_failed', array( $this, 'remove_entry_after_failed' ) );
		add_action( 'wp_ajax_nopriv_everest_forms_square_payment_delete_entry_after_failed', array( $this, 'remove_entry_after_failed' ) );
	}

	/**
	 * Payment through credit card.
	 *
	 * @since 1.0.0
	 */
	public function payment_credit_card() {
		check_ajax_referer( 'evf_square_payment_nonce', 'security' );

		if ( empty( $_POST ) ) {
			return;
		}

		if ( ! isset( $_POST['source_id'] ) && empty( $_POST['source_id'] ) ) {
			return;
		}

		$payment_response = Api::create_payment( $_POST );
	}

	/**
	 * Process entry for square payment
	 *
	 * @param array  $fields Fields Data.
	 * @param array  $entry  Entry Data.
	 * @param array  $form_data Form Data.
	 * @param string $entry_id Entry Id.
	 */
	public function process_entry( $fields, $entry, $form_data, $entry_id ) {
		if ( ! $this->is_square_enabled( $form_data ) ) {
			return false;
		}

		$payment_fields = evf_get_payment_items( $fields, $entry, $form_data );
		$total_amount   = evf_sanitize_amount( evf_get_total_payment( $fields, $entry, $form_data ) );
		$discount       = apply_filters( 'everest_forms_coupon_discount', 0, $total_amount, $fields, $form_data );
		$total_amount  -= $discount;

		if ( $total_amount <= 0 ) {
			return;
		}

		if ( empty( $entry_id ) || empty( $form_data['payments']['square']['enable_square'] ) || empty( $payment_fields ) || empty( $total_amount ) ) {
			return;
		} else {
			if ( 'no' === get_option( 'everest_forms_pro_square_test_mode' ) ) {
				$payment_mode = __( 'Live', 'everest-forms-pro' );
			} else {
				$payment_mode = __( 'Test', 'everest-forms-pro' );
			}

			// Update entry to include payment details.
			$entry_data = array(
				'status' => 'Pending',
				'type'   => 'payment',
				'meta'   => wp_json_encode(
					array(
						'payment_gateway'     => 'square',
						'payment_discount'    => $discount,
						'payment_total'       => $total_amount,
						'payment_currency'    => get_option( 'everest_forms_currency' ),
						'payment_mode'        => $payment_mode,
						'payment_transaction' => '',
					)
				),
			);

			evf_payment_entries( $entry_id, $entry_data );
		}
	}

	/**
	 * Update entry stripe status.
	 *
	 * @return void
	 */
	public function update_entry_square_status() {
		check_ajax_referer( 'evf_square_payment_nonce', 'security' );

		if ( empty( $_POST ) ) {
			return;
		}

		if ( ! empty( sanitize_text_field( wp_unslash( $_POST['entry_id'] ) ) ) && ! empty( $_POST ) ) {
			$transaction_id              = isset( $_POST['payment_data']['payment']['id'] ) ? sanitize_text_field( wp_unslash( $_POST['payment_data']['payment']['id'] ) ) : '';
			$receipt_url                 = isset( $_POST['payment_data']['payment']['receipt_url'] ) ? sanitize_text_field( wp_unslash( $_POST['payment_data']['payment']['receipt_url'] ) ) : '';
			$payment_status              = isset( $_POST['payment_data']['payment']['status'] ) ? sanitize_text_field( wp_unslash( $_POST['payment_data']['payment']['status'] ) ) : '';
			$entry_id                    = sanitize_text_field( wp_unslash( $_POST['entry_id'] ) );
			$entry                       = evf_get_entry( $entry_id );
			$form_data                   = evf()->form->get( $entry->form_id, array( 'content_only' => true ) );
			$meta                        = evf_decode( $entry->meta['meta'] );
			$meta['receipt_url']         = $receipt_url;
			$meta['transaction_id']      = $transaction_id;
			$meta['payment_transaction'] = $transaction_id;

			if ( 'COMPLETED' === $payment_status ) {
				$entry_update = array(
					'status' => 'Complete',
					'meta'   => wp_json_encode( $meta ),
				);
			} else {
				$entry_update = array(
					'status' => 'Failed',
					'meta'   => wp_json_encode( $meta ),
				);
			}

			// Update payment info based on stripe server response.
			evf_payment_entries( $entry_id, $entry_update, true );

			$fields                 = json_decode( $entry->fields, true );
			$entry                  = array();
			$entry['form_fields']   = array();
			$entry['hp']            = '';
			$entry['id']            = $entry_id;
			$entry['author']        = '';
			$data['entry']          = $entry;
			$data['fields']         = $fields;
			$data['payment_status'] = isset( $entry_update['status'] ) ? $entry_update['status'] : 'Failed';

			// After Square Payment Complete.
			do_action( 'everest_forms_square_process_complete', $fields, $form_data, $entry_id, $data );

			wp_send_json_success(
				array( 'message' => esc_html__( 'Payment made successfully', 'everest-forms-pro' ) )
			);
		}
	}

	/**
	 * Remove the entry after payment failed.
	 *
	 * @since 1.7.7
	 */
	public function remove_entry_after_failed() {
		if ( isset( $_POST['entry_id'], $_POST['action'] ) && 'everest_forms_square_payment_delete_entry_after_failed' === $_POST['action'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
			$result = false;
			if ( class_exists( 'EVF_Admin_Entries' ) ) {
				$form_id  = isset( $_POST['form_id'] ) ? absint( $_POST['form_id'] ) : 0;
				$entry_id = isset( $_POST['entry_id'] ) ? absint( $_POST['entry_id'] ) : 0;
				$result   = \EVF_Admin_Entries::remove_entry( $entry_id, $form_id );
			}
			return $result;
		}
		wp_send_json_error(
			array( 'message' => esc_html__( 'Bad request.', 'everest-forms-pro' ) )
		);
	}

	/**
	 * Check the Square is enable or not, if enabled return true otherwise false.
	 *
	 * @param array $form_data Form data.
	 *
	 * @return bool
	 */
	public function is_square_enabled( $form_data ) {
		$is_paypal_enabled        = isset( $form_data['payments']['paypal']['enable_paypal'] ) ? $form_data['payments']['paypal']['enable_paypal'] : '0';
		$is_stripe_enabled        = isset( $form_data['payments']['stripe']['enable_stripe'] ) ? $form_data['payments']['stripe']['enable_stripe'] : '0';
		$is_authorize_net_enabled = isset( $form_data['payments']['authorize_net']['enable_authorize_net'] ) ? $form_data['payments']['authorize_net']['enable_authorize_net'] : '0';
		$is_razorpay_enabled      = isset( $form_data['payments']['razorpay']['enable_razorpay'] ) ? $form_data['payments']['razorpay']['enable_razorpay'] : '0';
		$is_square_enabled        = isset( $form_data['payments']['square']['enable_square'] ) ? $form_data['payments']['square']['enable_square'] : '0';

		if ( '1' === $is_square_enabled && '0' === $is_paypal_enabled && '0' === $is_stripe_enabled && '0' === $is_authorize_net_enabled && '0' === $is_razorpay_enabled ) {
			return true;
		}

		return false;
	}
}
