<?php

namespace KnitPayUPI\Gateways\UpiQR\Freecharge;

use KnitPayUPI\Gateways\UpiQR\KnitPayUPIIntegration;
use Pronamic\WordPress\Html\Element;
use Exception;
use KnitPay\Utils as KnitPayUtils;

/**
 * Title: FreeCharge Integration
 * Copyright: 2020-2026 Knit Pay
 *
 * @author  Knit Pay
 * @version 1.7.0.0
 * @since   1.7.0.0
 */
class Integration extends KnitPayUPIIntegration {
	private $config;

	/**
	 * Construct UPI QR integration.
	 *
	 * @param array $args Arguments.
	 */
	public function __construct( $args = [] ) {
		$args = wp_parse_args(
			$args,
			[
				'id'           => 'freecharge',
				'name'         => 'UPI/QR - FreeCharge Personal (Broken)',
				'product_url'  => 'https://play.google.com/store/apps/details?id=com.freecharge.android',
				'provider'     => 'freecharge',
				'gateway_name' => 'Freecharge', // Set this if display name and actual name are different.
			]
		);
		
		parent::__construct( $args );
	}
	
	public function get_setup_settings_fields( $fields ) {
		$fields = $this->get_login_logout_fields( $fields );

		if ( isset( $this->config ) && $this->config->is_connected ) {
			$fields = parent::get_setup_settings_fields( $fields );

			unset( $fields['transaction_id_field'] );
			unset( $fields['merchant_category_code'] );
		}
		
		return $fields;
	}
	
	private function get_login_logout_fields( $fields ) {      
		// Callback URL.
		$config_id = KnitPayUtils::get_gateway_config_id();
		if ( ! empty( $config_id ) ) {
			$this->config = $this->get_config( $config_id );
		}
		
		if ( isset( $this->config ) && $this->config->is_connected ) {
			$fields = $this->get_connection_status_field( $fields );

			// Return if already logged in.
			return $fields;
		}
		
		// Registered Phone.
		$fields[] = [
			'section'  => 'general',
			'title'    => __( 'Phone Number', 'knit-pay-upi' ),
			'type'     => 'description',
			'callback' => [ $this, 'field_send_phone_otp' ],
			'tooltip'  => __( 'Phone number registered at Freecharge.', 'knit-pay-upi' ),
		];
		
		// Submit OTP.
		$fields[] = [
			'section'  => 'general',
			'title'    => __( 'OTP', 'knit-pay-upi' ),
			'type'     => 'description',
			'callback' => [ $this, 'field_submit_otp' ],
		];
		
		// Load admin.js Javascript
		$fields[] = [
			'section'  => 'general',
			'type'     => 'custom',
			'callback' => function () {
				echo '<script src="' . plugins_url( '', __FILE__ ) . '/js/admin.js"></script>';
			},
		];
		
		return $fields;
	}
	
	/**
	 * Get config.
	 *
	 * @param int $post_id Config ID.
	 * @return Config
	 */
	public function get_config( $post_id ) {
		$config = new Config();
		$config->copy_properties( parent::get_config( $post_id ) );
		
		$config->phone_number    = $this->get_meta( $post_id, 'upi_qr_freecharge_phone_number' );
		$config->cookie          = $this->get_meta( $post_id, 'upi_qr_freecharge_cookie' );
		$config->csrf_identifier = $this->get_meta( $post_id, 'upi_qr_freecharge_csrf_identifier' );
		$config->otp_id          = $this->get_meta( $post_id, 'upi_qr_freecharge_otp_id' );
		$config->is_connected    = $this->get_meta( $post_id, 'upi_qr_freecharge_is_connected' );

		if ( $config->is_connected && '' === $config->cookie ) {
			$config->is_connected = false;
			update_post_meta( $post_id, '_pronamic_gateway_upi_qr_freecharge_is_connected', false );
		}
		
		if ( '' === $config->is_connected ) {
			$config->is_connected = false;
		}

		$config->hide_mobile_qr  = false;
		$config->hide_pay_button = true;
		
		return $config;
	}
	
	/**
	 * Save post.
	 *
	 * @param int $post_id Post ID.
	 * @return void
	 */
	public function save_post( $config_id ) {
		parent::save_post( $config_id );
		
		$config = $this->get_config( $config_id );

		// Don't do anything if already connected.
		if ( $config->is_connected ) {
			return;
		}

		if ( '' === $config->cookie ) {
			$api_client = new API( $config );
			$api_client->init_session();
		}

		$new_phone_number = isset( $_POST['_pronamic_gateway_upi_qr_freecharge_phone_number'] ) ? sanitize_text_field( $_POST['_pronamic_gateway_upi_qr_freecharge_phone_number'] ) : '';
		if ( $new_phone_number !== $config->phone_number && '' !== $new_phone_number ) {
			update_post_meta( $config_id, '_pronamic_gateway_upi_qr_freecharge_phone_number', $new_phone_number );
		}
		
		$otp = isset( $_POST['_pronamic_gateway_upi_qr_freecharge_otp'] ) ? sanitize_text_field( $_POST['_pronamic_gateway_upi_qr_freecharge_otp'] ) : '';
		if ( '' !== $otp ) {
			try {
				$api        = new API( $config );
				$login_data = $api->verify_otp( $otp );
				update_post_meta( $config_id, '_pronamic_gateway_upi_qr_payee_name', $login_data->firstName . ' ' . $login_data->lastName );
				update_post_meta( $config_id, '_pronamic_gateway_upi_qr_freecharge_is_connected', true );
				delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_freecharge_otp' );
				delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_freecharge_otp_id' );
			} catch ( Exception $e ) {
				$this->knit_pay_post_save_notice( $e->getMessage() );
				return;
			}

			return;
		}

		if ( ! $config->is_connected ) {
			$config = $this->get_config( $config_id );
			try {
				$api      = new API( $config );
				$otp_data = $api->send_otp();
			} catch ( Exception $e ) {
				$this->knit_pay_post_save_notice( $e->getMessage() );
				return;
			}

			if ( isset( $otp_data->otpId ) ) {
				update_post_meta( $config_id, '_pronamic_gateway_upi_qr_freecharge_otp_id', $otp_data->otpId );
			}
			return;
		}
	}

	protected function is_connected() {
		// Check connection.
		$api = new API( $this->config );
		$api->check_connection();
	}

	/**
	 * Field Enabled Payment Methods.
	 *
	 * @param array<string, mixed> $field Field.
	 * @return void
	 */
	public function field_send_phone_otp( $field ) {
		$config_id = KnitPayUtils::get_gateway_config_id();
		
		$input_phone_number = new Element(
			'input',
			[
				'id'        => '_pronamic_gateway_upi_qr_freecharge_phone_number',
				'name'      => '_pronamic_gateway_upi_qr_freecharge_phone_number',
				'type'      => 'text',
				'value'     => $this->get_meta( $config_id, 'upi_qr_freecharge_phone_number' ),
				'inputmode' => 'numeric',
				'pattern'   => '\d*',
			]
		);
		$input_phone_number->output();
		
		$button_send_otp           = new Element(
			'a',
			[
				'id'    => 'freecharge-send-phone-otp',
				'class' => 'button button-primary button-large',
				'role'  => 'button',
			]
		);
		$button_send_otp->children = [ 'Click to Send OTP' ];
		$button_send_otp->output();

		printf( '<br>Enter the 10-digit Phone number registered at Freecharge.' );
	}
	
	/**
	 * Field Enabled Payment Methods.
	 *
	 * @param array<string, mixed> $field Field.
	 * @return void
	 */
	public function field_submit_otp( $field ) {
		$input_otp = new Element(
			'input',
			[
				'id'        => '_pronamic_gateway_upi_qr_freecharge_otp',
				'name'      => '_pronamic_gateway_upi_qr_freecharge_otp',
				'type'      => 'text',
				'inputmode' => 'numeric',
				'pattern'   => '\d*',
			]
		);
		$input_otp->output();
		
		$button_submit_otp           = new Element(
			'a',
			[
				'id'    => 'freecharge-submit-otp',
				'class' => 'button button-primary button-large',
				'role'  => 'button',
			]
		);
		$button_submit_otp->children = [ 'Submit OTP' ];
		$button_submit_otp->output();
		
		printf( '<br>Enter OTP received on phone number.' );
	}

	public static function clear_config( $config_id ) {
		update_post_meta( $config_id, '_pronamic_gateway_upi_qr_freecharge_is_connected', false );
		update_post_meta( $config_id, '_pronamic_gateway_upi_qr_freecharge_cookie', '' );
	}
}
