<?php

class FrmStrpAppController {

	public static function load_lang() {
		load_plugin_textdomain( 'formidable-stripe', false, FrmStrpAppHelper::plugin_folder() . '/languages/' );
	}

	public static function include_updater() {
		if ( class_exists( 'FrmAddon' ) ) {
			FrmStrpUpdate::load_hooks();

			if ( self::should_show_stripe_connect_message() ) {
				self::maybe_add_stripe_connect_inbox_message();
			}
		}
		self::install();
	}

	public static function install( $old_db_version = false ) {
		FrmTransAppController::install( $old_db_version );
	}

	public static function add_gateway( $gateways ) {
		$gateways['stripe'] = array(
			'label'     => 'Stripe',
			'user_label' => __( 'Credit Card', 'formidable-stripe' ),
			'class'     => 'Strp',
			'recurring' => true,
			'include'   => array(
				'billing_first_name',
				'billing_last_name',
				'credit_card',
				'billing_address',
			),
		);
		return $gateways;
	}

	public static function add_api_routes() {
		register_rest_route(
			'frm-strp/v1',
			'/card/(?P<id>[a-z0-9 _]+)',
			array(
				'methods'  => 'DELETE',
				'callback' => array( 'FrmStrpPaymentsController', 'delete_card' ),
				'permission_callback' => 'is_user_logged_in',
			)
		);
	}

	/**
	 * @return bool
	 */
	private static function should_show_stripe_connect_message() {
		$is_setup = FrmStrpConnectHelper::stripe_connect_is_setup( 'live' );
		return ! $is_setup;
	}

	private static function maybe_add_stripe_connect_inbox_message() {
		$url = self::get_stripe_connect_settings_url();
		self::maybe_add_inbox_message(
			array(
				'key'     => 'use_strp_connect',
				'force'   => true,
				'message' => self::get_stripe_connect_message( $url ),
				'subject' => 'Your Stripe keys may not be secure!',
				'icon'    => 'frm_report_problem_icon',
				'cta'     => '<a class="button-secondary frm-button-secondary" href="' . esc_url_raw( $url ) . '">Connect Stripe Now</a>',
			)
		);
	}

	/**
	 * @param string $url
	 * @return string
	 */
	private static function get_stripe_connect_message( $url ) {
		return 'Your current Stripe payment connection is out of date and may become insecure. Please connect your Stripe account in the <a href="' . esc_url_raw( $url ) . '">Stripe settings</a>.';
	}

	/**
	 * @return string
	 */
	private static function get_stripe_connect_settings_url() {
		return admin_url( 'admin.php?page=formidable-settings&t=stripe_settings' );
	}

	/**
	 * Add a message to the Formidable Inbox, if it exists
	 *
	 * @param string $message
	 */
	private static function maybe_add_inbox_message( $message ) {
		if ( class_exists( 'FrmInbox' ) ) {
			$inbox = new FrmInbox();
			$inbox->add_message( $message );
		}
	}
}
