<?php
/**
* @package CembraPay Payment Gateway for WooCommerce
* @author  Adrian Emil Tudorache
* @license GPL-2.0+
* @link    https://www.tudorache.me/
**/

if ( ! defined( 'ABSPATH' ) ) {
    header( 'Status: 403 Forbidden' );
	header( 'HTTP/1.1 403 Forbidden' );
    exit;
}

use CembraPayWoo\Service as Service;
use CembraPayWoo\CembraPay as CembraPay;

add_action( 'plugins_loaded', 'init_custom_gateway' );

function init_custom_gateway() {
    if ( ! class_exists( 'WC_Payment_Gateway_CC' ) ) return;

    class WC_Gateway_CembraPay extends WC_Payment_Gateway_CC {

		public $language;

		private $unavailable;

        private $labels;

        public function __construct() {

            $this->id                 = 'cembrapay';
            $this->method_title       = 'CembraPay';
            $this->method_description = esc_html__( 'Pay by invoice with CembraPay', 'cembrapay' );
            $this->supports           = array( 'default_credit_card_form', 'products' );

            $this->labels             = Service::get_field_labels();
            
            // Load form fields and settings
            $this->init_form_fields();
            $this->init_settings();
            
            // Get settings values
			$this->title        = $this->labels[ 'title' ];
			$this->description  = $this->labels[ 'description' ];
            $this->enabled      = $this->get_option( 'enabled' );

			$this->icon         = $this->get_option( 'display_gateway_logo' ) ? CEMBRAURL . 'assets/img/CembraPay.gif' : '';
			$this->unavailable  = $this->labels[ 'unavailable' ];

            // Add actions for saving settings and processing payments
            add_action( 'woocommerce_update_options_payment_gateways_' . $this->id, array( $this, 'process_admin_options' ) );
            add_action( 'woocommerce_receipt_' . $this->id, array( $this, 'receipt_page' ) );
            add_action( 'woocommerce_thankyou_' . $this->id, array( $this, 'receipt_page' ) );
            add_action( 'woocommerce_thankyou', array( $this, 'receipt_page' ) );

			//Scripts and styles
			add_action( 'wp_enqueue_scripts', array( $this, 'scripts' ), 99 );

        }

        public function is_available() {
            
            $client_id = $this->get_option( 'client_id' );
            $client_secret = $this->get_option( 'client_secret' );
            
            if( empty( $client_id ) || empty( $client_secret ) ) {
                return false;
            }

            return parent::is_available();

        }

        public function payment_fields() {

            // Display the payment form description
            if ( $this->description ) {
                echo wpautop( wptexturize( $this->description ) );
            }

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

            if( $auth_type == 2 ) {

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

				if( $use_salutation_field ) {

					$salutation_label        = $this->labels[ 'salutation_field_label' ];
					$salutation_female_label = $this->labels[ 'salutation_field_label_female' ];
					$salutation_male_label   = $this->labels[ 'salutation_field_label_male' ];
					$salutation_other_label  = $this->labels[ 'salutation_field_label_other' ];
					$salutation_field_type   = $this->get_option('salutation_field_functionality');
					$salutation_field_type   = $salutation_field_type ? $salutation_field_type : 1;
					$salutation_required     = $this->get_option('salutation_field_required');

					$salutations = apply_filters( 'cembrapay_salutations', array(
						'F' => $salutation_female_label,
						'M' => $salutation_male_label,
						'N' => $salutation_other_label
					) );

					if( $salutation_field_type == 1 ) {

						Service::load_template( 'front/form-field-salutation-select', array(
							'salutation_label'    => $salutation_label,
							'salutations'         => $salutations,
							'salutation_required' => $salutation_required
						));

					}

					if( $salutation_field_type == 2 ) {

						Service::load_template( 'front/form-field-salutation-radio-buttons', array(
							'salutation_label'    => $salutation_label,
							'salutations'         => $salutations,
							'salutation_required' => $salutation_required
						));

					}

				}

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

				if( $use_birthdate_field ==1 ) {

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

                    if( ! $birthdate_field_alt_id ) {

                        $birthdate_field_type       = $this->get_option('birthdate_field_type');
                        $birthdate_field_label	    = $this->labels[ 'birthdate_field_label' ];
                        $birthdate_field_label_type = $this->get_option('birthdate_field_label_type');

                        if( $birthdate_field_type == 1 ) {
                            
                            $birthdate_field_day_label   = $this->labels[ 'birthdate_field_day_label' ];
                            $birthdate_field_month_label = $this->labels[ 'birthdate_field_month_label' ];
                            $birthdate_field_year_label  = $this->labels[ 'birthdate_field_year_label' ];

                            Service::load_template( 'front/form-field-birthdate-separate-fields', array(
                                'birthdate_field_label'       => $birthdate_field_label,
                                'birthdate_field_label_type'  => $birthdate_field_label_type,
                                'birthdate_field_day_label'   => $birthdate_field_day_label,
                                'birthdate_field_month_label' => $birthdate_field_month_label,
                                'birthdate_field_year_label'  => $birthdate_field_year_label
                            ));

                        }

                        if( $birthdate_field_type == 2 ) {

                            // wp_enqueue_script( 'jquery-ui-datepicker' );

                            Service::load_template( 'front/form-field-birthdate-datepicker', array(
                                'birthdate_field_label'      => $birthdate_field_label,
                                'birthdate_field_label_type' => $birthdate_field_label_type
                            ));

                        }

                    }

				}

            }

			$use_company_reg_field = $this->get_option('use_company_reg_field');
			if( $use_company_reg_field == 1 ) {

				$company_reg_field_required   = $this->get_option('company_reg_field_required');
				$company_reg_field_label      = $this->labels[ 'company_reg_field_label' ];
				$company_reg_field_label_type = $this->get_option('company_reg_field_label_type');

				Service::load_template( 'front/form-field-company-reg', array(
					'company_reg_field_label_type' => $company_reg_field_label_type,
					'company_reg_field_required'   => $company_reg_field_required,
					'company_reg_field_label'      => $company_reg_field_label
				));
				
			}

			$use_installments = $this->get_option('use_installments');
			if( $use_installments == 1 ) {

				$installments_intro_text = $this->labels[ 'installments_intro_text' ];

				$installments = $this->get_available_installments();

				Service::load_template( 'front/form-field-installments', array(
					'installments_intro_text' => $installments_intro_text,
					'installments'            => $installments
				));
				
			}

			$use_invoice_type = $this->get_option('use_invoice_type');
			if( $auth_type == 2 && $use_invoice_type == 1 ) {

				$invoice_type_intro_text = $this->labels[ 'invoice_type_intro_text' ];
				$invoice_via_email       = $this->labels[ 'invoice_via_email' ];
				$invoice_via_post        = $this->labels[ 'invoice_via_post' ];

				Service::load_template( 'front/form-field-invoice-type', array(
					'invoice_type_intro_text' => $invoice_type_intro_text,
					'invoice_via_email'       => $invoice_via_email,
					'invoice_via_post'        => $invoice_via_post
				));

			}

			if( $auth_type == 2 ) {
				Service::load_template( 'front/form-terms-and-conditions' );
			}
    
        }

        public function validate_fields() {

            $company_reg = isset( $_POST['cembrapay_company_reg'] ) ? sanitize_text_field( wp_unslash( $_POST['cembrapay_company_reg'] ) ) : '';
            $billing_company = isset( $_POST['billing_company'] ) ? sanitize_text_field( wp_unslash( $_POST['billing_company'] ) ) : '';
            
            $installments_active = $this->get_option('use_installments');

			if( 
                $installments_active
                && ( ! empty( $company_reg ) || ! empty( $billing_company ) ) 
            ) {

                $available_installments_for = $this->get_installments_available_for();

                if( ! $available_installments_for || empty( $available_installments_for['b2b'] ) ) {
                    wc_add_notice( esc_html__( 'Unfortunately, CembraPay is not available for Company customers', 'cembrapay' ), 'error' );
                    return false;
                }

			}

            $auth_type = $this->get_option( 'auth_type' );
            if( $auth_type == 2 ) {

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

				if( $use_salutation_field ) {

					$salutation_required = $this->get_option('salutation_field_required');

					if( $salutation_required ) {

						$salutation_field = isset( $_POST['cembrapay_salutation'] ) ? sanitize_text_field( wp_unslash( $_POST['cembrapay_salutation'] ) ) : '';

						if( ! $salutation_field ) {
							wc_add_notice( esc_html__( 'The salutation field is required', 'cembrapay' ), 'error' );
							return false;
						}

					}

				}

				$billing_company = isset( $_POST['billing_company'] ) ? sanitize_text_field( wp_unslash( $_POST['billing_company'] ) ) : '';

				$use_company_reg_field = $this->get_option('use_company_reg_field');
				if( $use_company_reg_field == 1 ) {

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

					if( $billing_company && $company_reg_field_required == 1 ) {

						$company_reg = isset( $_POST['cembrapay_company_reg'] ) ? sanitize_text_field( wp_unslash( $_POST['cembrapay_company_reg'] ) ) : '';

						if( empty( $company_reg ) ) {
							wc_add_notice( esc_html__( 'The company registration field is required', 'cembrapay' ), 'error' );
							return false;
						}

					}
					
				}

				if( ! $billing_company ) {

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

					if( $use_birthdate_field == 1 ) {

                        $birthdate = '';

                        $birthdate_field_type = $this->get_option('birthdate_field_type');
                        switch( $birthdate_field_type ) {
                            case 1:

                                $day = isset( $_POST['cembrapay_birthdate_day'] ) && $_POST['cembrapay_birthdate_day'] ? abs( sanitize_text_field( wp_unslash( $_POST['cembrapay_birthdate_day'] ) ) ) : '';

                                $day = $day < 10 ? '0' . $day : $day;

                                $month = isset( $_POST['cembrapay_birthdate_month'] ) && $_POST['cembrapay_birthdate_month'] ? abs( sanitize_text_field( wp_unslash( $_POST['cembrapay_birthdate_month'] ) ) ) : '';

                                $month = $month < 10 ? '0' . $month : $month;

                                $year = isset( $_POST['cembrapay_birthdate_year'] ) && $_POST['cembrapay_birthdate_year'] ? abs( sanitize_text_field( wp_unslash( $_POST['cembrapay_birthdate_year'] ) ) ) : '';

                                $birthdate = $year . '-' . $month . '-' . $day;

                            break;
                            case 2:

                                $birthdate = isset( $_POST['cembrapay_birthdate'] ) ? sanitize_text_field( wp_unslash( $_POST['cembrapay_birthdate'] ) ) : '';

                                $date_format = get_option('date_format');

                                $birthdate_obj = \DateTime::createFromFormat($date_format, $birthdate);

                                if ( !$birthdate_obj && strtotime($birthdate_raw) ) {
                                    $birthdate_obj = new \DateTime($birthdate_raw);
                                }

                                if ( ! $birthdate_obj) {
                                    $fallback_formats = array('Y-m-d', 'm/d/Y', 'd/m/Y', 'd.m.Y', 'F j, Y');
                                    foreach ($fallback_formats as $format) {
                                        $birthdate_obj = \DateTime::createFromFormat($format, $birthdate_raw);
                                        if ($birthdate_obj) break;
                                    }
                                }

                                $birthdate = $birthdate_obj ? $birthdate_obj->format('Y-m-d') : '';

                            break;
                        }

                        if( empty( $birthdate ) ) {

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

                            if( $birthdate_field_alt_id ) {
                                
                                $birthdate = isset( $_POST[ $birthdate_field_alt_id ] ) 
                                    ? 
                                    date( 'Y-m-d', strtotime( sanitize_text_field( wp_unslash( $_POST[ $birthdate_field_alt_id ] ) ) ) ) 
                                    : 
                                    '';

                            }

                        }

						if ( empty( $birthdate ) ) {
							wc_add_notice( esc_html__( 'The birthdate field is required', 'cembrapay' ), 'error' );
							return false;
						}

						if( 
                            ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', date('Y-m-d', strtotime($birthdate)) ) 
                            || ! preg_match( '/^\d{4}-\d{2}-\d{2}$/', $birthdate ) 
                        ) {
							wc_add_notice( esc_html__( 'The birthdate field is not in the correct format Year (4 digits) - Month (1 or 2 digits) - Day (1 or 2 digits)', 'cembrapay' ), 'error' );
							return false;
						}

                        $check_date = explode( '-', $birthdate );
                        if( 
                            ! empty( $check_date[0] ) && ! empty( $check_date[1] ) && ! empty( $check_date[2] ) 
                            && ! checkdate( intval( $check_date[1] ), intval( $check_date[2] ), intval( $check_date[0] ))
                        ) {
                            wc_add_notice( esc_html__( 'The birthdate field contains an invalid date.', 'cembrapay' ), 'error' );
                            return false;
                        }

					}

				}

				$allow_underage = $this->get_option('allow_underage');
				if( $allow_underage == 0 && $use_birthdate_field == 1 ) {

					$underage_threshold = $this->get_option('underage_threshold');
					$underage_threshold = $underage_threshold ? intval( $underage_threshold ) : 18;
		
					$inputDate = new DateTime($birthdate);
					$today = new DateTime();
					if( $today->diff($inputDate)->y <= $underage_threshold ) {
						wc_add_notice( sprintf( esc_html__( 'You must be at least %d years old to place an order', 'cembrapay' ), $underage_threshold ), 'error' );
						return false;
					}

				}

            }

			if( $auth_type == 2 && ( ! isset( $_POST['cembrapay-tc'] ) || 1 != $_POST['cembrapay-tc'] ) ) {
				wc_add_notice( esc_html__( 'You need to accept the CembraPay terms and conditions', 'cembrapay' ), 'error' );
				return false;
			}
    
            return true;

        }

		public function update_order_meta( $order_id ) {

            $locale = get_locale();

            setlocale(LC_TIME, $locale . '.UTF-8', $locale, substr( $locale, 0, 2 ));

            global $post;

			$order = wc_get_order( $order_id );

			if( 
                (
                    is_account_page() 
                    || is_checkout() 
                    || ( $post && \has_block( 'woocommerce/checkout', $post ) )
                    || ( $post && ! empty( $post->post_content ) && has_shortcode( 'woocommerce_checkout', $post->post_content ) )
                )
                && $order->get_payment_method() == 'cembrapay'
            ) {

				$salutation = isset( $_POST['cembrapay_salutation'] ) ? sanitize_text_field( wp_unslash( $_POST['cembrapay_salutation'] ) ) : '';

				$birthdate = '';
				if( 
					isset( $_POST['cembrapay_birthdate'] ) 
					&& $_POST['cembrapay_birthdate']
				) {
                    $birthdate = sanitize_text_field( wp_unslash( $_POST['cembrapay_birthdate'] ) );
                    if( $birthdate ) {
                        $birthdate = Service::convert_date( $birthdate );
                    }
				}

				if( 
					isset( $_POST['cembrapay_birthdate_day'] ) 
					&& $_POST['cembrapay_birthdate_day']
					&& isset( $_POST['cembrapay_birthdate_month'] ) 
					&& $_POST['cembrapay_birthdate_month']
					&& isset( $_POST['cembrapay_birthdate_year'] ) 
					&& $_POST['cembrapay_birthdate_year']
				) {
					
					$day = sanitize_text_field( wp_unslash( $_POST['cembrapay_birthdate_day'] ) );

					if( $day ) {
						$day = abs( $day );
						$day = $day < 10 ? '0' . $day : $day;
					}

					$month = sanitize_text_field( wp_unslash( $_POST['cembrapay_birthdate_month'] ) );

					if( $month ) {
						$month = abs( $month );
						$month = $month < 10 ? '0' . $month : $month;
					}

					$year = sanitize_text_field( wp_unslash( $_POST['cembrapay_birthdate_year'] ) );
					if( $year ) {
						$year = abs( $year );
					}

					$birthdate = $year . '-' . $month . '-' . $day;
					
				}

                if( empty( $birthdate ) ) {
                    $birthdate_field_alt_id = $this->get_option('birthdate_field_alt_id');
                    if( $birthdate_field_alt_id ) {
                        $birthdate = isset( $_POST[ $birthdate_field_alt_id ] ) 
                        ? 
                        date( 'Y-m-d', strtotime( sanitize_text_field( wp_unslash( $_POST[ $birthdate_field_alt_id ] ) ) ) )
                        : 
                        '';
                    }
                }

				$company_reg = isset( $_POST['cembrapay_company_reg'] ) && $_POST['cembrapay_company_reg'] ? sanitize_text_field( wp_unslash( $_POST['cembrapay_company_reg'] ) ) : '';

				$installment = isset( $_POST['cembrapay_installment'] ) && $_POST['cembrapay_installment'] ? sanitize_text_field( wp_unslash( $_POST['cembrapay_installment'] ) ) : '';

                if( ! $installment ) {
                    $available_installments = $this->get_available_installments();
                    if( $available_installments ) {
                        $customer_type = $order->get_billing_company() ? 'b2b' : 'b2c';
                        foreach( $available_installments as $installment_type => $data ) {
                            if( $data['for'] == 'all' || $customer_type == $data['for'] ) {
                                $installment = $installment_type;
                                break;
                            }
                        }
                    }
                }

				$invoice_type = isset( $_POST['cembrapay_invoice_type'] ) && $_POST['cembrapay_invoice_type'] ? sanitize_text_field( wp_unslash( $_POST['cembrapay_invoice_type'] ) ) : '';

				$order = wc_get_order( $order_id );

				if( ! empty( $salutation ) ) {
					$order->update_meta_data( '_user-salutation', $salutation );
				}

				if( ! empty( $birthdate ) ) {
					$order->update_meta_data( '_user-birthdate', $birthdate );
				}

				if( ! empty( $company_reg ) ) {
					$order->update_meta_data( '_company-reg', $company_reg );
				}

				if( ! empty( $installment ) ) {
					$order->update_meta_data( '_installment_type', $installment );
				}

				if( ! empty( $invoice_type ) ) {
					$order->update_meta_data( '_invoice_type', $invoice_type );
				}

				$order->update_meta_data( '_initial_total', $order->get_total() );

				if( WC()->session ) {
					$threatmetrix_session_id = WC()->session->get('cembrapay_threatmetrix_session_id');
					$order->update_meta_data( '_threatmetrix_session_id', $threatmetrix_session_id );
				}
	
				$order->save();
	
			}

		}

        /**
         * Process the payment and return the result.
         *
         * @param int $order_id
         * @return array
         */
        public function process_payment( $order_id ) {

            $this->update_order_meta( $order_id );

			$order = wc_get_order( $order_id );

			$auth_type = $this->get_option( 'auth_type' );
			$auth_type = $auth_type == 1 ? 'checkout' : 'direct';

			$cembrapay = new CembraPay( $order_id, $auth_type );
			$authorize = $cembrapay->request();

			if( isset( $authorize['status'] ) && $authorize['status'] == 'SUCCESS' && $auth_type == 'direct' && ! isset( $authorize['redirect'] ) ) {

				$order->payment_complete();
            	$order->add_order_note( esc_html__( 'Payment authorized and processed correctly.', 'cembrapay' ) );

			}

			if( isset( $authorize['status'] ) && $authorize['status'] == 'DECLINED' ) {

				wc_add_notice( $this->unavailable, 'error');

                $order->update_status('failed', esc_html__('Payment declined by CembraPay', 'cembrapay'));

				return array(
					'result' => 'failure',
                    'message' => $this->unavailable
				);

			}

			if( ! $authorize || ( isset( $authorize['status'] ) && $authorize['status'] == 'ERROR' ) ) {

				wc_add_notice( $this->unavailable, 'error');

                $errors = '';

				if( isset( $authorize['errors'] ) && is_array( $authorize['errors'] ) ) {

                    $order->update_status('failed', esc_html__('Payment declined by CembraPay', 'cembrapay'));
					
					foreach( $authorize['errors'] as $error ) {
						$errors .= sprintf( 
							esc_html__( 'Error code %s. Message: %s' ), 
							isset( $error['processingErrorCode'] ) ? $error['processingErrorCode'] : 'N/A',
							isset( $error['processingErrorDescr'] ) ? $error['processingErrorDescr'] : 'N/A'
						). '<br />';
					}
					
					wc_add_notice( $errors, 'error' );

				}

                if( $errors ) {

                    return array(
                        'result' => 'failure',
                        'message' => $errors
                    );

                }

			}

			WC()->cart->empty_cart();

			$order_status = $this->get_option( 'order_status' );
			$order_status = $order_status ? $order_status : 'processing';
			
			if( $auth_type == 'checkout' ) {
				$order_status = 'pending';
			}

			if( $order_status ) {
				$order->update_status( $order_status, sprintf( esc_html__( 'Order status set to %s', 'cembrapay' ), $order_status ) );
			}

            // Return success and redirect to the thank you page
            return array(
                'result'   => 'success',
                'redirect' => isset( $authorize['redirect'] ) && $authorize['redirect'] && $auth_type == 'checkout' ? $authorize['redirect'] : $this->get_return_url( $order ),
            );
        }

		/**
		 * Enqueue scripts
		 */
		function scripts() {

            global $post;
			
			if( 
                ! is_checkout() 
                && $post
                && ! empty( $post->post_content )
                && ! \has_block('woocommerce/checkout', $post) 
                && ! has_shortcode('woocommerce_checkout', $post->post_content) 
            ) {
				return;
			}

			global $wp;

			$order_id = isset($wp->query_vars['order-pay']) ? absint($wp->query_vars['order-pay']) : 0;
			$order    = $order_id ? wc_get_order( $order_id ) : null;

            $locale = determine_locale();
            $date_format = get_option( 'date_format' );

			wp_enqueue_style( 'cembrapay', CEMBRAURL . 'assets/css/frontend/main.css' );
			wp_enqueue_script( 'cembrapay', CEMBRAURL . 'assets/build/frontend/main.js', array( 'jquery' ), '', true );
			
			$localizefrontend = array(
				'autoSelectGateway' => $this->get_option( 'auto_select_gateway' ),
				'allowUnderage'     => $this->get_option( 'allow_underage' ),
				'underageThreshold' => $this->get_option( 'underage_threshold' ),
				'installments'      => $this->get_available_installments(),
                'dateFormat'        => $date_format,
                'defaultBirthdate'  => date( $date_format, strtotime( '1990-01-01' ) ),
                'locale'            => substr( $locale, 0, 2 ),
				'orderPayOrder'     => array(
					'billingAddress1' => $order ? $order->get_billing_address_1() : '',
					'billingAddress2' => $order ? $order->get_billing_address_2() : '',
					'billingPostcode' => $order ? $order->get_billing_postcode() : '',
					'billingCity'     => $order ? $order->get_billing_city() : '',
					'billingState'    => $order ? $order->get_billing_state() : '',
					'billingCountry'  => $order ? $order->get_billing_country() : '',
					'billingEmail'    => $order ? $order->get_billing_email() : '',
				)
			);

			wp_localize_script('cembrapay', 'cembrapay', $localizefrontend);

            $cembrapay_settings = Service::get_payment_gateway_settings();
            $tmx_enabled = $cembrapay_settings['use_tmx'] ?? 0;

            if( $tmx_enabled && is_checkout() && ! is_wc_endpoint_url('order-received') && WC()->session ) {
                wp_enqueue_script( 'threatmetrix', 'https://cdn.cembrapay.ch/public/fp-clientlib-v5.js', array(), '', false );
            }

		}

		/**
		 * Output for the order received page.
		 */
		public function receipt_page( $order_id ) {

            if( WC()->session ) {
                $threatmetrix_session_id = WC()->session->get('cembrapay_threatmetrix_session_id');
                if( $threatmetrix_session_id ) {
                    WC()->session->__unset('cembrapay_threatmetrix_session_id');
                }
            }

            $params = array(
                'cembrapay',
                'code',
                'trx',
                'timestamp',
                'thumbprint',
                'signature'
            );

            $receipt_data = array();

            foreach( $params as $param ) {
                if( isset( $_GET[ $param ] ) ) {
                    $receipt_data[ $param ] = sanitize_text_field( $_GET[ $param ] );
                }
            }

            if( isset( $receipt_data['cembrapay'] ) && $receipt_data['cembrapay'] == 'success' ) {

                $order = wc_get_order( $order_id );

                if( $order ) {

                    $order->payment_complete();
                    $order->add_order_note( esc_html__( 'Payment authorized and processed correctly.', 'cembrapay' ) );

                    if( $receipt_data ) {
                        $order->update_meta_data( '_cembrapay_checkout_data', $receipt_data );
                    }

                    $use_order_confirmation = $this->get_option( 'use_order_confirmation' );
					if( $use_order_confirmation == 1 ) {
						$cembrapay = new CembraPay( $order_id, 'confirmation' );
						$cembrapay->request();
					}
                    
                    $order_status = $this->get_option( 'order_status' );
					$order_status = $order_status ?? $order->get_status();

					if( $order_status ) {
						$order->update_status( $order_status, sprintf( esc_html__( 'Order status set to %s', 'cembrapay' ), $order_status ) );
					}

                    $save = $order->save();

                    $order_received_url = $order->get_checkout_order_received_url();
                    if( $order_received_url ) {
                        wp_redirect( $order_received_url );
                        exit;
                    }

                }

            }

        }		

		public function get_available_installments() {
				
			$installments = array();

            $use_installments = $this->get_option('use_installments');
            if( ! $use_installments ) {
                return $installments;
            }

			$use_cembrapay_invoice = $this->get_option('use_cembrapay_invoice');
			if( $use_cembrapay_invoice == 'yes' ) {
				
				$installments['CEMBRAPAY-INVOICE'] = array(
					'for'      => $this->get_option('cembrapay_invoice_for'),
					'template' => $this->labels[ 'cembrapay_invoice_template' ]
				);

			}

			$use_installments_full = $this->get_option('use_installments_full');
			if( $use_installments_full == 'yes' ) {
				
				$installments['SINGLE-INVOICE'] = array(
					'for'      => $this->get_option('installments_full_for'),
					'template' => $this->labels[ 'installments_full_template' ]
				);

			}

			$use_installments_3 = $this->get_option('use_installments_3');
			if( $use_installments_3 == 'yes' ) {
				
				$installments['INSTALLMENT_3'] = array(
					'for'      => $this->get_option('installments_3_for'),
					'template' => $this->labels[ 'installments_3_template' ]
				);

			}

			$use_installments_4 = $this->get_option('use_installments_4');
			if( $use_installments_4 == 'yes' ) {
				
				$installments['INSTALLMENT_4'] = array(
					'for'      => $this->get_option('installments_4_for'),
					'template' => $this->labels[ 'installments_4_template' ]
				);

			}

			$use_installments_6 = $this->get_option('use_installments_6');
			if( $use_installments_6 == 'yes' ) {
				
				$installments['INSTALLMENT_6'] = array(
					'for'      => $this->get_option('installments_6_for'),
					'template' => $this->labels[ 'installments_6_template' ]
				);

			}

			$use_installments_12 = $this->get_option('use_installments_12');
			if( $use_installments_12 == 'yes' ) {
				
				$installments['INSTALLMENT_12'] = array(
					'for'      => $this->get_option('installments_12_for'),
					'template' => $this->labels[ 'installments_12_template' ]
				);

			}

			$use_installments_24 = $this->get_option('use_installments_24');
			if( $use_installments_24 == 'yes' ) {
				
				$installments['INSTALLMENT_24'] = array(
					'for'      => $this->get_option('installments_24_for'),
					'template' => $this->labels[ 'installments_24_template' ]
				);

			}

			$use_installments_36 = $this->get_option('use_installments_36');
			if( $use_installments_36 == 'yes' ) {
				
				$installments['INSTALLMENT_36'] = array(
					'for'      => $this->get_option('installments_36_for'),
					'template' => $this->labels[ 'installments_36_template' ]
				);

			}

			$use_installments_48 = $this->get_option('use_installments_48');
			if( $use_installments_48 == 'yes' ) {
				
				$installments['INSTALLMENT_48'] = array(
					'for'      => $this->get_option('installments_48_for'),
					'template' => $this->labels[ 'installments_48_template' ]
				);

			}

			return apply_filters( 'cembrapay_available_installments', $installments );

		}

        public function get_installments_available_for(): array {

            $active_installments = $this->get_available_installments();
            
            if( ! $active_installments ) {
                return array();
            }

            $has_b2b = false;
            $has_b2c = false;

            foreach( $active_installments as $installment => $data ) {

                if( ! empty( $data['for'] ) ) {

                    if( $data['for'] == 'all' ) {
                        $has_b2b = true;
                        $has_b2c = true;
                        break;
                    }
                    if( $data['for'] == 'b2b' ) {
                        $has_b2b = true;
                    }
                    if( $data['for'] == 'b2c' ) {
                        $has_b2c = true;
                    }
                    if( $has_b2b && $has_b2c ) {
                        break;
                    }

                }

            }

            return array(
                'b2b' => $has_b2b,
                'b2c' => $has_b2c
            );

        }

		public function process_admin_options() {
			parent::process_admin_options();

			//Act only on the CembraPay settings page
			if( isset( $_POST['woocommerce_cembrapay_enabled'] ) ) {
				delete_option('cembrapay_access_token');
			}
			
		}

        /**
         * Get all woocommerce order statuses
         */
        public function get_wc_order_statuses() {

            $statuses = wc_get_order_statuses();

            $formatted_statuses = array(
                '' => esc_html__('Allow WooCommerce to set the status automatically', 'cembrapay')
            );
            foreach( $statuses as $key => $status ) {
                $formatted_statuses[ str_replace( 'wc-', '', $key ) ] = $status;
            }

            return $formatted_statuses;

        }

        /**
         * Initialize gateway settings fields.
         */
        public function init_form_fields() {

            $order_statuses = $this->get_wc_order_statuses();
            if( ! $order_statuses ) {
                $order_statuses = array(
                    ''				=> esc_html__('Allow WooCommerce to set the status automatically', 'cembrapay'),
					'processing' 	=> 'Processing',
					'on-hold' 		=> 'On Hold',
					'completed' 	=> 'Completed',
					'pending' 		=> 'Pending',
					'cancelled' 	=> 'Cancelled',
					'refunded' 		=> 'Refunded',
					'failed' 		=> 'Failed'
                );
            }
            
            $formfields_enabled = array(

				'enabled' => array(
					'title'   => esc_html__( 'Enable/Disable', 'cembrapay' ),
					'type'    => 'checkbox',
					'label'   => esc_html__( 'Enable CembraPay Payment', 'cembrapay' ),
					'default' => 'yes'
				)

			);

            $formfields_title_desc_instructions = array(

				'title' => array(
					'title'       => esc_html__( 'Title', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'This controls the title for the payment method the customer sees during checkout.', 'cembrapay' ),
					'default'     => esc_html__( 'CembraPay Payment', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'description' => array(
					'title'       => esc_html__( 'Description', 'cembrapay' ),
					'type'        => 'textarea',
					'description' => esc_html__( 'Payment method description that the customer will see on your checkout.', 'cembrapay' ),
					'default'     => esc_html__( 'Performs a check on the CembraPay database before placing an order.', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'instructions' => array(
					'title'       => esc_html__( 'Instructions', 'cembrapay' ),
					'type'        => 'textarea',
					'description' => esc_html__( 'Instructions that will be added to the thank you page and emails.', 'cembrapay' ),
					'default'     => esc_html__( 'To proceed, please fill all the required fields, including the salutation and birthdate fields if required.', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'unavailable' => array(
					'title'       => esc_html__( 'Unavailable', 'cembrapay' ),
					'type'        => 'textarea',
					'description' => esc_html__( 'Message that will appear on the checkout page if the CembraPay credit check is negative.', 'cembrapay' ),
					'default'     => esc_html__( 'Unfortunately CembraPay is not available for your order. Please select a different payment gateway.', 'cembrapay' ),
					'desc_tip'    => true,
				),

			);

            $formfields_api = array(

				'api_settings' => array(
					'title'       => esc_html__( 'API Settings', 'cembrapay' ),
					'type'        => 'title',
					'description' => esc_html__( 'Below information should be taken from CembraPay', 'cembrapay' ),
				),

				'mode' => array(
					'title'       => esc_html__( 'Mode', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						1 => esc_html__( 'Sandbox', 'cembrapay' ),
						2 => esc_html__( 'Live', 'cembrapay' )
					),
					'description' => esc_html__( 'Set the way the check is made - testing or live environment.', 'cembrapay' ),
					'default'     => 1,
					'desc_tip'    => true,
				),

				'client_id' => array(
					'title'       => esc_html__( 'Client ID', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'API element provided by CembraPay.', 'cembrapay' ),
					'default'     => '',
					'desc_tip'    => true,
				),

				'client_secret' => array(
					'title'       => esc_html__( 'Client Secret', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'API element provided by CembraPay.', 'cembrapay' ),
					'default'     => '',
					'desc_tip'    => true,
				),

				'connection_status' => array(
					'title'       => esc_html__( 'Connection status', 'cembrapay' ),
					'type'        => 'text',
					'description' => '',
					'default'     => '',
					'desc_tip'    => true,
				),

				'api_settings_separator' => array(
					'title'       => '',
					'type'        => 'title',
					'description' => '<hr />'
				),

			);

            $formfields_admin = array(

				'administration' => array(
					'title'       => esc_html__( 'Administration', 'cembrapay' ),
					'type'        => 'title',
					'description' => '',
				),

                'auth_type' => array(
					'title'       => esc_html__( 'Checkout authorization type', 'cembrapay' ),
					'type'        => 'select',
					'description' => esc_html__( 'Choose the one that applies. Checkout authorization will redirect the customer to CembraPay and will required them to create an account in order to place an order. Direct authorization will require the user to send their salutation and date of birth to CembraPay and will send out API requests to the CembraPay API to determine if the customer is elligible to place an order or not.', 'cembrapay' ),
					'options'     => array(
						1 => esc_html__( 'Checkout Authorization', 'cembrapay' ),
						2 => esc_html__( 'Direct Authorization', 'cembrapay' )
					),
                    'default'     => 1,
					'desc_tip'    => true,
				),

				'use_order_id_prefix' => array(
					'title'       => esc_html__( 'Enable Order ID Prefix', 'cembrapay' ),
					'type'        => 'select',
					'description' => esc_html__( 'The prefix should be the first 3 characters of your websites\' domain. This is used for the CembraPay calls and may be requested by the CembraPay staff.', 'cembrapay' ),
					'options'     => array(
						0 => esc_html__( 'No', 'cembrapay' ),
						1 => esc_html__( 'Yes', 'cembrapay' )
					),
					'desc_tip'    => true,
				),

				'order_id_prefix' => array(
					'title'       => esc_html__( 'Order ID Prefix', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'Set the order ID prefix. We recommend using the first 3 letters of your websites\' domain', 'cembrapay' ),
					'default'     => substr( str_replace(array('http://www', 'https://www.', 'http://', 'https://', 'www.'), '', site_url()), 0, 3),
					'desc_tip'    => true,
				),

				'order_id_source' => array(
					'title'       => esc_html__( 'Order ID Source', 'cembrapay' ),
					'type'        => 'select',
					'options'	  => array(
						1 => 'WooCommerce default order ID',
						2 => 'Order meta'
					),
					'description' => esc_html__( 'Select where to take the Order ID from', 'cembrapay' ),
					'default'     => 1,
					'desc_tip'    => true,
				),

				'order_id_meta_key' => array(
					'title'       => esc_html__( 'Order ID meta key', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'Get from database. You may need to contact your developer in order to correctly use this feature.', 'cembrapay' ),
					'desc_tip'    => true
				),

				'enable_on_order_refunds' => array(
					'title'       => esc_html__( 'Enable on Order Refunds', 'cembrapay' ),
					'type'        => 'select',
					'description' => esc_html__( 'If set to yes, the plugin will send a partial cancellation to CembraPay when an order gets refunded or partially refunded.', 'cembrapay' ),
					'options'     => array(
						1 => esc_html__( 'Yes', 'cembrapay' ),
						0 => esc_html__( 'No', 'cembrapay' )
					),
					'desc_tip'    => true,
				),

				'display_gateway_logo' => array(
					'title'		  => esc_html__('Display CembraPay logo on the checkout page', 'cembrapay'),
					'type'		  => 'select',
					'options'	  => array(
						0 => esc_html__( 'No', 'cembrapay' ),
						1 => esc_html__( 'Yes', 'cembrapay' )
					),
					'description' => esc_html__( 'Display CembraPay logo by the name of the Gateway on the checkout page', 'cembrapay' ),
					'desc_tip'	  => true
				),

				'auto_select_gateway' => array(
					'title'		  => esc_html__( 'Auto select CembraPay gateway', 'cembrapay' ),
					'type'		  => 'select',
					'options'	  => array(
						0 => esc_html__( 'No', 'cembrapay' ),
						1 => esc_html__( 'Yes', 'cembrapay' )
					),
					'description' => esc_html__( 'Auto select CembraPay gateway if it is displayed on the checkout page', 'cembrapay' ),
					'desc_tip'	  => true
				),

				'administration_separator' => array(
					'title'       => '',
					'type'        => 'title',
					'description' => '<hr />'
				)

			);

            $formfields_salutation = array(

				'salutation_settings' => array(
					'title'       => esc_html__( 'Salutation settings', 'cembrapay' ),
					'type'        => 'title',
					'description' => '',
				),

				'use_salutation_field' => array(
					'title'       => esc_html__( 'Use salutation field', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						1 => esc_html__( 'Yes', 'cembrapay' ),
						0 => esc_html__( 'No', 'cembrapay' )
					),
					'description' => esc_html__( 'Add a checkout form field to collect the customer\'s salutation. Can be skipped with CembraPay agreement.', 'cembrapay' ),
					'default'     => 1,
					'desc_tip'    => true,
				),

				'salutation_field_label' => array(
					'title'       => esc_html__( 'Salutation field label', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'Set a custom label for the salutation field.', 'cembrapay' ),
					'default'     => esc_html__( 'Salutation', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'salutation_field_label_female' => array(
					'title'       => esc_html__( 'Salutation field Female label', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'Set a custom label for Female option in the salutation field.', 'cembrapay' ),
					'default'     => esc_html__( 'Female', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'salutation_field_label_male' => array(
					'title'       => esc_html__( 'Salutation field Male label', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'Set a custom label for Male option in the salutation field.', 'cembrapay' ),
					'default'     => esc_html__( 'Male', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'salutation_field_label_other' => array(
					'title'       => esc_html__( 'Salutation field Other label', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'Set a custom label for Other option in the salutation field.', 'cembrapay' ),
					'default'     => esc_html__( 'Other', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'salutation_field_functionality' => array(
					'title'       => esc_html__( 'Salutation field functionality', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						1 => esc_html__( 'Select box (dropdown)', 'cembrapay' ),
						2 => esc_html__( 'Radio Buttons', 'cembrapay' )
					),
					'description' => esc_html__( 'Choose how the salutation field is displayed on the checkout page.', 'cembrapay' ),
					'default'     => 1,
					'desc_tip'    => true,
				),

				'salutation_field_required' => array(
					'title'       => esc_html__( 'Salutation field required', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						1 => esc_html__( 'Yes', 'cembrapay' ),
						0 => esc_html__( 'No', 'cembrapay' )
					),
					'description' => esc_html__( 'Choose whether the salutation field should be required or not on the checkout page.', 'cembrapay' ),
					'default'     => 1,
					'desc_tip'    => true,
				),

				'salutation_field_separator' => array(
					'title'       => '',
					'type'        => 'title',
					'description' => '<hr id="salutation_separator" />'
				)

			);

            $formfields_birthdate = array(

				'birthdate_settings' => array(
					'title'       => esc_html__( 'Birthdate settings', 'cembrapay' ),
					'type'        => 'title',
					'description' => '',
				),

				'use_birthdate_field' => array(
					'title'       => esc_html__( 'Use birthdate field', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						1 => esc_html__( 'Yes', 'cembrapay' ),
						0 => esc_html__( 'No', 'cembrapay' )
					),
					'description' => esc_html__( "Add a checkout form field to collect the customer's date of birth. Can be skipped with CembraPay agreement.", 'cembrapay' ),
					'default'     => 1,
					'desc_tip'    => true,
				),

				'birthdate_field_type' => array(
					'title'       => esc_html__( 'Birthdate field type', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						1 => esc_html__( 'Separate Fields for day, month, and year', 'cembrapay' ),
						2 => esc_html__( 'Single field datepicker', 'cembrapay' )
					),
					'description' => esc_html__( 'Choose between datepicker or separate fields for day, month and year', 'cembrapay' ),
					'default'     => 1,
					'desc_tip'    => true,
				),

				'birthdate_field_label' => array(
					'title'       => esc_html__( 'Birthdate field label', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'Set a custom label for the Birthdate field.', 'cembrapay' ),
					'default'     => esc_html__( 'Birthdate', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'birthdate_field_day_label' => array(
					'title'       => esc_html__( 'Birthdate field day label', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'Set a custom label for the Birthdate day field', 'cembrapay' ),
					'default'     => esc_html__( 'Day', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'birthdate_field_month_label' => array(
					'title'       => esc_html__( 'Birthdate field month label', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'Set a custom label for the Birthdate month field', 'cembrapay' ),
					'default'     => esc_html__( 'Month', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'birthdate_field_year_label' => array(
					'title'       => esc_html__( 'Birthdate field year label', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'Set a custom label for the Birthdate year field', 'cembrapay' ),
					'default'     => esc_html__( 'Year', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'birthdate_field_label_type' => array(
					'title'       => esc_html__( 'Birthdate field label type', 'cembrapay' ),
					'description' => esc_html__( 'Choose between a classic label or a placeholder for the Birthdate field.', 'cembrapay' ),
					'type'        => 'select',
					'options'	  => array(
						1 => esc_html__( 'Classic label', 'cembrapay' ),
						2 => esc_html__( 'Placeholder', 'cembrapay' )
					),
					'desc_tip'    => true,
				),

				'birthdate_field_alt_id' => array(
					'title'       => esc_html__( 'Birthdate field alternative ID', 'cembrapay' ) . '<br/><a href="' . CEMBRAURL . 'assets/img/birthdate.mp4" target="_blank" rel="noopener noreferrer">' . esc_html__( 'Check how to get the field ID', 'cembrapay' ) . '</a>',
					'type'        => 'text',
					'description' => esc_html__( 'If your checkout page already uses a salutation field, add the ID here.', 'cembrapay' ),
					'default'     => '',
					'desc_tip'    => true,
				),

				'birthday_field_separator' => array(
					'title'       => '',
					'type'        => 'title',
					'description' => '<hr id="birthdate_separator" />'
				)

			);

            $formfields_company_reg = array(

				'company_reg_settings' => array(
					'title'       => esc_html__( 'Company / B2B settings', 'cembrapay' ),
					'type'        => 'title',
					'description' => '',
				),

				'use_company_reg_field' => array(
					'title'       => esc_html__( 'Use company registration field', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						0 => esc_html__( 'No', 'cembrapay' ),
						1 => esc_html__( 'Yes', 'cembrapay' )
					),
					'description' => esc_html__( 'Add a checkout form field to collect the customer\'s company registration number. Enabling this field, will automatically enable the B2B functionality.', 'cembrapay' ),
					'default'     => 0,
					'desc_tip'    => true,
				),

				'company_reg_field_required' => array(
					'title'       => esc_html__( 'Company registration field required', 'cembrapay' ),
					'type'        => 'select',
					'description' => esc_html__( 'Make the company registration field required or not. If set to Yes, users will be required to supply the number before placing an order.', 'cembrapay' ),
					'options' => array(
						1 => esc_html__( 'Yes', 'cembrapay' ),
						0 => esc_html__( 'No', 'cembrapay' )
					),
					'default'     => 1,
					'desc_tip'    => true
				),

				'company_reg_field_label' => array(
					'title'       => esc_html__( 'Company registration field label', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'Set a custom label for the company registration field.', 'cembrapay' ),
					'default'     => 'Company registration number',
					'desc_tip'    => true,
				),

				'company_reg_field_label_type' => array(
					'title'       => esc_html__( 'Company registration field label type', 'cembrapay' ),
					'description' => esc_html__( 'Choose between a classic label or a placeholder for the Company registration field.', 'cembrapay' ),
					'type'        => 'select',
					'options'	  => array(
						1 => 'Classic label',
						2 => 'Placeholder'
					),
					'desc_tip'    => true,
				),

				'company_reg_field_separator' => array(
					'title'       => '',
					'type'        => 'title',
					'description' => '<hr />'
				)

			);

            $formfields_installments = array(

				'installments_description' => array(
					'title'       => esc_html__( 'Installments settings', 'cembrapay' ),
					'description' => esc_html__( 'Please check the your contract with CembraPay AG before activation', 'cembrapay' ),
					'type'        => 'title'
				),

				'use_installments' => array(
					'title'       => esc_html__( 'Use installments', 'cembrapay' ),
					'description' => esc_html__( 'Allows the customer to choose on checkout between paying in full or using installments.', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						0 => esc_html__( 'No', 'cembrapay' ),
						1 => esc_html__( 'Yes', 'cembrapay' )
					),
					'default'     => 0,
					'desc_tip'    => true,
				),

				'installments_intro_text' => array(
					'title'       => esc_html__( 'Installments intro text', 'cembrapay' ),
					'description' => '',
					'type'        => 'textarea',
					'default'     => esc_html__( 'Please choose your payment plan', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'use_cembrapay_invoice' => array(
					'title'       => esc_html__( 'CembraPay invoice', 'cembrapay' ),
					'label'		  => esc_html__( 'Enable', 'cembrapay' ),
					'description' => '',
					'type'        => 'checkbox',
					'default'     => esc_html__( 'Enable CembraPay invoice', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'cembrapay_invoice_for' => array(
					'title'       => esc_html__( 'CembraPay invoice available for', 'cembrapay' ),
					'description' => '',
					'type'        => 'select',
					'options'	  => array(
						'all' => esc_html__( 'B2C & B2B', 'cembrapay' ),
						'b2c' => esc_html__( 'B2C', 'cembrapay' ),
						'b2b' => esc_html__( 'B2B', 'cembrapay' ),
					),
					'default'     => '',
					'desc_tip'    => true,
				),

				'cembrapay_invoice_template' => array(
					'title'       => esc_html__( 'Description (visible on the website)', 'cembrapay' ),
					'description' => '',
					'type'        => 'textarea',
					'default'     => esc_html__( 'CembraPay invoice template', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'use_installments_full' => array(
					'title'       => esc_html__( 'Pay in full', 'cembrapay' ),
					'label'		  => esc_html__( 'Enable', 'cembrapay' ),
					'description' => '',
					'type'        => 'checkbox',
					'default'     => esc_html__( 'Enable installment pay in full', 'cembrapay' ),
					'desc_tip'    => true,
				),

				'installments_full_for' => array(
					'title'       => esc_html__( 'Pay in full available for', 'cembrapay' ),
					'description' => '',
					'type'        => 'select',
					'options'	  => array(
						'all' => esc_html__( 'B2C & B2B', 'cembrapay' ),
						'b2c' => esc_html__( 'B2C', 'cembrapay' ),
						'b2b' => esc_html__( 'B2B', 'cembrapay' ),
					),
					'default'     => '',
					'desc_tip'    => true,
				),

				'installments_full_template' => array(
					'title'       => esc_html__( 'Description (visible on the website)', 'cembrapay' ),
					'description' => '',
					'type'        => 'textarea',
					'default'     => esc_html__( 'Pay in full template', 'cembrapay' ),
					'desc_tip'    => true,
				)

			);

			$available_installments = array( 3, 4, 6, 12, 24, 36, 48 );

			foreach( $available_installments as $installment ) {

				$formfields_installments['use_installments_' . $installment] = array(
					'title'       => sprintf( esc_html__( 'Pay in %s payments', 'cembrapay' ), $installment ),
					'label'		  => esc_html__( 'Enable', 'cembrapay' ),
					'description' => '',
					'type'        => 'checkbox',
					'default'     => sprintf( esc_html__( 'Pay in %s installments', 'cembrapay' ), $installment ),
					'desc_tip'    => true,
				);

				$formfields_installments['installments_' . $installment . '_for'] = array(
					'title'       => sprintf( esc_html__( '%s payments available for', 'cembrapay' ), $installment ),
					'description' => '',
					'type'        => 'select',
					'options'	  => array(
						'all' => esc_html__( 'B2C & B2B', 'cembrapay' ),
						'b2c' => esc_html__( 'B2C', 'cembrapay' ),
						'b2b' => esc_html__( 'B2B', 'cembrapay' ),
					),
					'default'     => '',
					'desc_tip'    => true,
				);

				$formfields_installments['installments_' . $installment . '_template'] = array(
					'title'       => esc_html__( 'Description (visible on the website)', 'cembrapay' ),
					'description' => '',
					'type'        => 'textarea',
					'default'     => sprintf( esc_html__( 'Pay in %s installments', 'cembrapay' ), $installment ),
					'desc_tip'    => true,
				);

			}

			$formfields_installments['installments_separator'] = array(
				'title'       => '',
				'type'        => 'title',
				'description' => '<hr />'
			);

            $formfields_invoice_type = array(

				'invoice_type_description' => array(
					'title'       => esc_html__( 'Invoice type settings', 'cembrapay' ),
					'type'        => 'title'
				),

				'use_invoice_type' => array(
					'title'       => esc_html__( 'Use invoice type', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						0 => esc_html__( 'No', 'cembrapay' ),
						1 => esc_html__( 'Yes', 'cembrapay' )
					),
					'description' => esc_html__( 'Allow user to choose between having the invoice sent by e-mail or on paper via Post Office.', 'cembrapay' ),
					'default'     => 0,
					'desc_tip'    => true,
				),

				'invoice_type_intro_text' => array(
					'title'		  => esc_html__( 'Invoice type intro text', 'cembrapay' ),
					'type'		  => 'textarea',
					'description' => esc_html__( 'The text added here will appear before the invoice type options in the payment gateway on the checkout page. Leave empty if you do not wish to provide the user with any other infos.', 'cembrapay' ),
					'default'	  => 'Select invoice type',
					'desc_tip'	  => true
				),

				'invoice_via_email' => array(
					'title'       => esc_html__( 'Invoice sent via email template', 'cembrapay' ),
					'type'        => 'textarea',
					'description' => esc_html__( 'You can use the {email} tag inside the template', 'cembrapay' ),
					'default'     => esc_html__('Invoice sent via e-mail to: {email}', 'cembrapay'),
					'desc_tip'    => true,
				),

				'invoice_via_post' => array(
					'title'       => esc_html__( 'Invoice sent via Post Office template', 'cembrapay' ),
					'type'        => 'textarea',
					'description' => esc_html__( 'You can use the {address} tag inside the template', 'cembrapay' ),
					'default'     => esc_html__('Invoice sent by Post (4.25 CHF per letter) to: {address}', 'cembrapay'),
					'desc_tip'    => true,
				),

				'ui_settings_separator' => array(
					'title'       => '',
					'type'        => 'title',
					'description' => '<hr />'
				)

			);

            $formfields_workflow = array(

				'workflow_description' => array(
					'title'       => esc_html__( 'Workflow settings', 'cembrapay' ),
					'type'        => 'title'
				),

				'order_status' => array(
					'title'       => esc_html__( 'Order status', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						''				=> esc_html__('Allow WooCommerce to set the status automatically', 'cembrapay'),
						'processing' 	=> 'Processing',
						'on-hold' 		=> 'On Hold',
						'completed' 	=> 'Completed',
						'pending' 		=> 'Pending',
						'cancelled' 	=> 'Cancelled',
						'refunded' 		=> 'Refunded',
						'failed' 		=> 'Failed'
					),
					'description' => esc_html__( 'Default order status for orders placed with CembraPay.', 'cembrapay' ),
					'default'     => 1,
					'desc_tip'    => true,
				),

                'settlements_order_status' => array(
					'title'       => esc_html__( 'Settlements order status', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						''				=> esc_html__('Allow WooCommerce to set the status automatically', 'cembrapay'),
						'processing' 	=> 'Processing',
						'on-hold' 		=> 'On Hold',
						'completed' 	=> 'Completed',
						'pending' 		=> 'Pending',
						'cancelled' 	=> 'Cancelled',
						'refunded' 		=> 'Refunded',
						'failed' 		=> 'Failed'
					),
					'description' => esc_html__( 'Default order status to send settlements to CembraPay. Please use with caution. The default status is Completed.', 'cembrapay' ),
					'default'     => 1,
					'desc_tip'    => true,
				),

				'use_order_confirmation' => array(
					'title'       => esc_html__( 'Use order confirmation', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						0 => esc_html__( 'No', 'cembrapay' ),
						1 => esc_html__( 'Yes', 'cembrapay' )
					),
					'description' => esc_html__( 'Optional call that represents an extra safety layer in the relationship between the shop and CembraPay. If enabled, the request will only be sent when using Checkout Authorzation as the checkout authorization type.', 'cembrapay' ),
					'default'     => 0,
					'desc_tip'    => true
				),

                'use_tmx' => array(
					'title'       => esc_html__( 'Use Threatmetrix', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						0 => esc_html__( 'No', 'cembrapay' ),
						1 => esc_html__( 'Yes', 'cembrapay' )
					),
					'description' => esc_html__( 'Enable or disable the Threatmetrix script in the front end. Ask CembraPay support for more information', 'cembrapay' ),
					'default'     => 0,
					'desc_tip'    => true
				),

				'allow_underage' => array(
					'title'       => esc_html__( 'Allow Underage Users', 'cembrapay' ),
					'type'        => 'select',
					'options' => array(
						0 => esc_html__( 'No', 'cembrapay' ),
						1 => esc_html__( 'Yes', 'cembrapay' )
					),
					'description' => esc_html__( 'Allow underaged users to pay with CembraPay', 'cembrapay' ),
					'default'     => 0,
					'desc_tip'    => true
				),

				'underage_threshold' => array(
					'title'       => esc_html__( 'Underaged Threshold', 'cembrapay' ),
					'type'        => 'text',
					'description' => esc_html__( 'The number set here will represent the maximum age for underaged. Typically this value should be 18.', 'cembrapay' ),
					'default'     => '18',
					'desc_tip'    => true
				),

				'workflow_settings_separator' => array(
					'title'       => '',
					'type'        => 'title',
					'description' => '<hr />'
				)

			);

            $formfields_multilanguage = array();
            
            $formfields_logs = array(

				'logs' => array(
					'title'       => esc_html__( 'Logs', 'cembrapay' ),
					'type'        => 'title',
					'description' => esc_html__( 'Choose to log CembraPay activity', 'cembrapay' ),
				),

				'logs_enable' => array(
					'title'       => esc_html__( 'Logs Enable', 'cembrapay' ),
					'type'        => 'select',
					'options'	  => array(
						0 => esc_html__( 'No', 'cembrapay' ),
						1 => esc_html__( 'Yes', 'cembrapay' )
					),
					'label'		  => esc_html__( 'Enable', 'cembrapay' ),
					'description' => esc_html__( 'Enable logging on CembraPay activity. Logs older than 3 months will be deleted. If you need records of older logs, please make regular database backups.', 'cembrapay' ),
					'default'     => '0',
					'desc_tip'    => true,
				),

				'logs_deletion' => array(
					'title'       => esc_html__( 'Delete logs older than', 'cembrapay' ),
					'type'        => 'select',
					'options'	  => array(
						1 => esc_html__( '30 days', 'cembrapay' ),
						2 => esc_html__( '3 months', 'cembrapay' ),
						3 => esc_html__( '6 months', 'cembrapay' ),
						4 => esc_html__( '1 year', 'cembrapay' ),
						5 => esc_html__( 'Never delete', 'cembrapay' ),
					),
					'label'		  => esc_html__( 'Enable', 'cembrapay' ),
					'description' => esc_html__( 'Choose for how long to keep the logs in the database. Please keep in mind that logs will take up space on your server. It is recommended to keep the logs in the past 30 days.', 'cembrapay' ),
					'default'     => '0',
					'desc_tip'    => true,
				),

				'logs_separator' => array(
					'title'       => '<a style="cursor: pointer;">' . esc_html__( 'Check CembraPay error logs', 'cembrapay' ) . '</a>',
					'type'        => 'title',
					'description' => '<hr />'
				)

			);

            $formfields = apply_filters( 'cembrapay_form_fields_enabled', $formfields_enabled ) + 
			apply_filters( 'cembrapay_form_fields_title_desc_instructions', $formfields_title_desc_instructions ) + 
			apply_filters( 'cembrapay_form_fields_api', $formfields_api ) + 
			apply_filters( 'cembrapay_form_fields_admin', $formfields_admin ) + 
			apply_filters( 'cembrapay_form_fields_salutation', $formfields_salutation ) + 
			apply_filters( 'cembrapay_form_fields_birthdate', $formfields_birthdate ) + 
			apply_filters( 'cembrapay_form_fields_company_reg', $formfields_company_reg ) + 
			apply_filters( 'cembrapay_form_fields_installments', $formfields_installments ) + 
			apply_filters( 'cembrapay_form_fields_invoice_type', $formfields_invoice_type ) + 
			apply_filters( 'cembrapay_form_fields_workflow', $formfields_workflow ) + 
			apply_filters( 'cembrapay_form_fields_multilanguage', $formfields_multilanguage ) + 
			apply_filters( 'cembrapay_form_fields_logs', $formfields_logs );

			$this->form_fields = apply_filters( 'cembrapay_form_fields', $formfields );

        }

    }

    /**
     * Add the gateway to WooCommerce available payment methods.
     */
    function add_custom_gateway_class( $methods ) {
        $methods[] = 'WC_Gateway_CembraPay';
        return $methods;
    }

    add_filter( 'woocommerce_payment_gateways', 'add_custom_gateway_class' );

}
?>