<?php
/**
 * Admin
 *
 * @author    Wpayme <hi@wpayme.com>
 * @copyright 2024-2025 Wpayme
 * @license   GPL-3.0-or-later
 * @package   Wpayme\WordPress\Pay\Extensions\GravityForms
 */

namespace Wpayme\WordPress\Pay\Extensions\GravityForms;

use RGFormsModel;

/**
 * Title: WordPress pay extension Gravity Forms admin
 * Description:
 * Copyright: 2024-2025 Wpayme
 * Company: Wpayme
 *
 * @author  Remco Tolsma
 * @version 2.1.14
 * @since   1.0.0
 */
class Admin {
	/**
	 * Bootstrap.
	 *
	 * @return void
	 */
	public static function bootstrap() {
		// Actions.
		add_action( 'admin_init', [ __CLASS__, 'admin_init' ] );
		add_action( 'admin_init', [ __CLASS__, 'maybe_redirect_to_entry' ] );

		add_action( 'gform_entry_info', [ __CLASS__, 'entry_info' ], 10, 2 );

		// Filters.
		add_filter( 'gform_custom_merge_tags', [ __CLASS__, 'custom_merge_tags' ], 10 );

		// Actions - AJAX.
		add_action( 'wp_ajax_wpayme_pay_gf_get_form_data', [ __CLASS__, 'ajax_get_form_data' ] );
	}

	/**
	 * Admin initialize.
	 *
	 * @return void
	 */
	public static function admin_init() {
		new AdminPaymentFormPostType();
	}

	/**
	 * Add menu item to form settings.
	 *
	 * @param array<array<string, string>> $menu_items Array with form settings menu items.
	 * @return array<array<string, string>>
	 */
	public static function form_settings_menu_item( $menu_items ) {
		$menu_items[] = [
			'name'  => 'wpayme_pay',
			'label' => __( 'Pay', 'wpayme' ),
			'query' => [ 'fid' => null ],
		];

		return $menu_items;
	}

	/**
	 * Render entry info of the specified form and lead
	 *
	 * @param string $form_id Gravity Forms form ID.
	 * @param array  $lead    Gravity Forms lead/entry.
	 * @return void
	 */
	public static function entry_info( $form_id, $lead ) {
		$payment_id = gform_get_meta( $lead['id'], 'wpayme_payment_id' );

		if ( ! $payment_id ) {
			return;
		}

		printf(
			'<a href="%s">%s</a>',
			esc_attr( get_edit_post_link( $payment_id ) ),
			esc_html( get_the_title( $payment_id ) )
		);
	}

	/**
	 * Custom merge tags.
	 *
	 * @param array<array<string, string>> $merge_tags Array with merge tags.
	 * @return array<array<string, string>>
	 */
	public static function custom_merge_tags( $merge_tags ) {
		// Payment.
		$merge_tags[] = [
			'label' => __( 'Payment Status', 'wpayme' ),
			'tag'   => '{payment_status}',
		];

		$merge_tags[] = [
			'label' => __( 'Payment Date', 'wpayme' ),
			'tag'   => '{payment_date}',
		];

		$merge_tags[] = [
			'label' => __( 'Transaction Id', 'wpayme' ),
			'tag'   => '{transaction_id}',
		];

		$merge_tags[] = [
			'label' => __( 'Payment Amount', 'wpayme' ),
			'tag'   => '{payment_amount}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme Payment ID', 'wpayme' ),
			'tag'   => '{wpayme_payment_id}',
		];

		$merge_tags[] = [
			'label' => __( 'WPayme Again URL', 'wpayme' ),
			'tag'   => '{wpayme_pay_again_url}',
		];

		// Bank transfer.
		$merge_tags[] = [
			'label' => __( 'Wpayme bank transfer recipient reference', 'wpayme' ),
			'tag'   => '{wpayme_payment_bank_transfer_recipient_reference}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme bank transfer recipient bank name', 'wpayme' ),
			'tag'   => '{wpayme_payment_bank_transfer_recipient_bank_name}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme bank transfer recipient name', 'wpayme' ),
			'tag'   => '{wpayme_payment_bank_transfer_recipient_name}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme bank transfer recipient IBAN', 'wpayme' ),
			'tag'   => '{wpayme_payment_bank_transfer_recipient_iban}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme bank transfer recipient BIC', 'wpayme' ),
			'tag'   => '{wpayme_payment_bank_transfer_recipient_bic}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme bank transfer recipient city', 'wpayme' ),
			'tag'   => '{wpayme_payment_bank_transfer_recipient_city}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme bank transfer recipient country', 'wpayme' ),
			'tag'   => '{wpayme_payment_bank_transfer_recipient_country}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme bank transfer recipient account number', 'wpayme' ),
			'tag'   => '{wpayme_payment_bank_transfer_recipient_account_number}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme consumer bank account name', 'wpayme' ),
			'tag'   => '{wpayme_payment_consumer_bank_account_name}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme consumer IBAN', 'wpayme' ),
			'tag'   => '{wpayme_payment_consumer_iban}',
		];

		// Subscription.
		$merge_tags[] = [
			'label' => __( 'Wpayme Subscription ID', 'wpayme' ),
			'tag'   => '{wpayme_subscription_id}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme Subscription Payment ID', 'wpayme' ),
			'tag'   => '{wpayme_subscription_payment_id}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme Subscription Amount', 'wpayme' ),
			'tag'   => '{wpayme_subscription_amount}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme Subscription Cancel URL', 'wpayme' ),
			'tag'   => '{wpayme_subscription_cancel_url}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme Subscription Renew URL', 'wpayme' ),
			'tag'   => '{wpayme_subscription_renew_url}',
		];

		$merge_tags[] = [
			'label' => __( 'Wpayme Subscription Renewal Date', 'wpayme' ),
			'tag'   => '{wpayme_subscription_renewal_date}',
		];

		return $merge_tags;
	}

	/**
	 * Maybe redirect to Gravity Forms entry.
	 *
	 * @return void
	 */
	public static function maybe_redirect_to_entry() {
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		if ( ! \array_key_exists( 'wpayme_gf_lid', $_GET ) ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended
		$lead_id = \sanitize_text_field( \wp_unslash( $_GET['wpayme_gf_lid'] ) );

		$lead = RGFormsModel::get_lead( $lead_id );

		if ( false === $lead ) {
			\wp_die( \esc_html__( 'The requested Gravity Forms entry could not be found.', 'wpayme' ) );
		}

		$url = \add_query_arg(
			[
				'page' => 'gf_entries',
				'view' => 'entry',
				'id'   => $lead['form_id'],
				'lid'  => $lead_id,
			],
			admin_url( 'admin.php' )
		);

		wp_safe_redirect( $url );

		exit;
	}

	/**
	 * Handle AJAX request get form data
	 */
	public static function ajax_get_form_data() {
		// Verify nonce.
		$nonce = \filter_input( INPUT_GET, 'nonce', \FILTER_SANITIZE_FULL_SPECIAL_CHARS );
		if ( ! $nonce || ! \wp_verify_nonce( $nonce, 'wpayme_pay_gf_get_form_data' ) ) {
			\wp_send_json_error( [ 'message' => \__( 'Security check failed.', 'wpayme' ) ] );
			return;
		}

		// Check user permissions - only allow users who can edit Gravity Forms.
		if ( ! \current_user_can( 'gravityforms_edit_forms' ) ) {
			\wp_send_json_error( [ 'message' => \__( 'Insufficient permissions.', 'wpayme' ) ] );
			return;
		}

		$form_id = \filter_input( INPUT_GET, 'formId', \FILTER_SANITIZE_NUMBER_INT );

		if ( empty( $form_id ) ) {
			\wp_send_json_error( [ 'message' => \__( 'Invalid form ID.', 'wpayme' ) ] );
			return;
		}

		$data = RGFormsModel::get_form_meta( $form_id );

		\wp_send_json_success( $data );
	}

	/**
	 * Get new feed URL.
	 *
	 * @since 1.6.3
	 *
	 * @param string $form_id Gravity Forms form ID.
	 * @return string
	 */
	public static function get_new_feed_url( $form_id ) {
		return add_query_arg(
			[
				'page'    => 'gf_edit_forms',
				'view'    => 'settings',
				'subview' => 'wpayme_pay',
				'id'      => $form_id,
				'fid'     => 0,
			],
			admin_url( 'admin.php' )
		);
	}
}
