<?php

namespace KnitPayUPI\Gateways\UpiQR\HdfcSmartHubVyapar;

use KnitPay\Utils;
use KnitPayUPI\Gateways\UpiQR\KnitPayUPIIntegration;
use Pronamic\WordPress\Html\Element;
use Pronamic\WordPress\Pay\Admin\AdminGatewayPostType;
use Exception;
use Zxing\QrReader;
use KnitPay\Utils as KnitPayUtils;

/**
 * Title: HDFC SmartHub Vyapar Integration
 * Copyright: 2020-2026 Knit Pay
 *
 * @author  Knit Pay
 * @version 1.4.0.0
 * @since   1.4.0.0
 */
class Integration extends KnitPayUPIIntegration {
	private $config;

	/**
	 * Construct HDFC SmartHub Vyapar integration.
	 *
	 * @param array $args Arguments.
	 */
	public function __construct( $args = [] ) {
		$args = wp_parse_args(
			$args,
			[
				'id'           => 'hdfc-smart-hub-vyapar',
				'name'         => 'UPI/QR - HDFC SmartHub Vyapar',
				'product_url'  => 'https://play.google.com/store/apps/details?id=com.hdfc.smarthub',
				'provider'     => 'hdfc-smart-hub-vyapar',
				'gateway_name' => 'HDFC SmartHub Vyapar',
			]
		);
		
		parent::__construct( $args );
	}
	
	/**
	 * Get about settings fields.
	 *
	 * @return array
	 */
	public function get_about_settings_fields( $fields ) {
		$fields = parent::get_about_settings_fields( $fields );

		// Integration Steps.
		$fields[] = [
			'section'  => 'general',
			'type'     => 'custom',
			'title'    => 'Steps to create cashier role',
			'callback' => function () {
				echo '
                <style>
                /* Container and row styling */
                .knitpay-hdfc-smart-hub-vyapar-admin-card {
                    padding: 20px;
                    background-color: #ffffff;
                    border: 1px solid #e0e0e0;
                    border-radius: 4px;
                }

                .knitpay-hdfc-smart-hub-vyapar-admin-row {
                    display: flex;
                    flex-wrap: wrap;
                    justify-content: space-around;
                    margin-bottom: 20px;
                }

                /* Column styling */
                .knitpay-hdfc-smart-hub-vyapar-admin-col {
                    flex: 1 1 200px;
                    max-width: 250px;
                    margin: 10px;
                    text-align: center;
                }

                /* Image styling */
                .knitpay-hdfc-smart-hub-vyapar-admin-col img {
                    max-width: 100%;
                    height: auto;
                    border-radius: 4px;
                }

                /* Text styling */
                .knitpay-hdfc-smart-hub-vyapar-admin-text {
                    margin-top: 15px;
                    color: #6c757d;
                    font-size: 14px;
                }

                .knitpay-hdfc-smart-hub-vyapar-admin-text a {
                    font-weight: 500;
                    color: #007bff;
                    text-decoration: none;
                }

                .knitpay-hdfc-smart-hub-vyapar-admin-text a:hover {
                    text-decoration: underline;
                }

                /* Alert box styling */
                .knitpay-hdfc-smart-hub-vyapar-admin-alert {
                    display: flex;
                    align-items: center;
                    padding: 15px;
                    background-color: #d4edda;
                    border-color: #c3e6cb;
                    border-radius: 4px;
                    color: #155724;
                    margin-top: 20px;
                }

                .knitpay-hdfc-smart-hub-vyapar-admin-alert svg {
                    margin-right: 10px;
                }
                </style>
                ';

				$steps = [
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_step_1.png',
						'description' => 'Download <a class="fw-medium" href="https://play.google.com/store/apps/details?id=com.hdfc.smarthub&amp;hl=en_IN&amp;gl=US" target="_blank">HDFC Bank SmartHub Vyapar App </a>on playstore. Login or Create an account in HDFC Bank SmartHub Vyapar App.',
					],
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_step_2.png',
						'description' => 'Click "More" button on navigation bar and select "Profile".',
					],
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_step_3.png',
						'description' => 'Now click on the "User Access" or "Add staff".',
					],
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_step_4.png',
						'description' => 'Click on the "+" button.',
					],
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_step_5.png',
						'description' => 'Enter basic details for cashier role',
					],
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_step_6.png',
						'description' => 'Scroll down and "Add Cashier Role".',
					],
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_step_7.png',
						'description' => 'Select company, city, location and Assign the cashier.',
					],
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_step_8.png',
						'description' => 'Cashier role assign successfully now click on "Save" button. Logout from HDFC Bank SmartHub Vyapar App.',
					],
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_pin_step_1.png',
						'description' => 'Now enter Cashier phone number and login to app.',
					],
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_pin_step_2.png',
						'description' => 'Enter & Verify OTP.',
					],
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_pin_step_3.png',
						'description' => 'Set 4 Digit mPIN (this mPIN required at login time in Knit Pay UPI).',
					],
					[
						'image'       => 'HdfcSmartHubVyapar/images/hdfc_pin_step_4.png',
						'description' => 'Cashier role account active successfully. Now logout Cashier role account from the app.',
					],
				];

				echo '<div class="knitpay-hdfc-smart-hub-vyapar-admin-card">
                    <div class="knitpay-hdfc-smart-hub-vyapar-admin-row">';

				foreach ( $steps as $key => $value ) {
					echo '<div class="knitpay-hdfc-smart-hub-vyapar-admin-col">
                            <img src="' . KNIT_PAY_UPI_URL . '/gateways/UpiQR/' . $value['image'] . '" alt="">
                            <p class="knitpay-hdfc-smart-hub-vyapar-admin-text">' . $key + 1 . '. ' . $value['description'] . '</p>
                        </div>';
				}

				echo '</div>
                    <div class="knitpay-hdfc-smart-hub-vyapar-admin-alert">
                        <span class="dashicons dashicons-admin-users" style="margin-right: 8px;"></span>
                        <p>Use this HDFC SmartHub Vyapar Cashier account to accept payments at Knit Pay. Please don\'t use this account on your phone else it will get logout from Knit Pay.</p>
                    </div>
                </div>';
			},
		];

		return $fields;
	}
	
	public function get_setup_settings_fields( $fields ) {
		if ( version_compare( PHP_VERSION, '8.1', '<' ) ) {
			$fields[] = [
				'section'  => 'general',
				'type'     => 'custom',
				'title'    => 'Incompatible',
				'callback' => function () {
					echo '<h1>' . __( 'Your current PHP version is incompatible with HDFC SmartHub integration. It requires PHP version 8.1 or above.', 'knit-pay-lang' ) . '</h1>';
				},
			];
			return $fields;
		}

		// TODO: ask pin if not in login logout fields.
		// Login mPIN.
		$fields[] = [
			'section'  => 'general',
			'meta_key' => '_pronamic_gateway_upi_qr_hdfc_smarthub_pin',
			'title'    => __( 'mPIN', 'knit-pay-upi' ),
			'type'     => 'password',
			'classes'  => [ 'regular-text', 'code' ],
			'required' => true,
		];
		
		$fields = $this->get_login_logout_fields( $fields );

		// If connected, show other setting fields.
		if ( isset( $this->config ) && '' !== $this->config->tid ) {
			$fields = parent::get_setup_settings_fields( $fields );

			unset( $fields['qr_code_scanner'] );
			unset( $fields['transaction_id_field'] );
		}

		// We don't want to save TID automatically, we want to handle it later in save_post function.
		if ( doing_action( 'save_post_' . AdminGatewayPostType::POST_TYPE ) ) {
			unset( $fields['hdfc_smarthub_tid'] );
		}
		
		return $fields;
	}
	
	private function get_login_logout_fields( $fields ) {      
		// Callback URL.
		$config_id = Utils::get_gateway_config_id();
		if ( ! empty( $config_id ) ) {
			$this->config = $this->get_config( $config_id );
		}

		if ( ! isset( $this->config ) || '' !== $this->config->tid ) {
			try {
				$api                = new API( $this->config );
				$user_terminal_info = $api->get_user_terminal_info();
				$terminal_array     = [];
				foreach ( reset( $user_terminal_info->terminalInfo ) as $key => $value ) {
					if ( 'Active' !== $value->tidStatus ) {
						continue;
					}
					$terminal_array[ $key ] = $value->companyName . " ({$key})";
				}
				$fields['hdfc_smarthub_tid'] = [
					'section'  => 'general',
					'meta_key' => '_pronamic_gateway_upi_qr_hdfc_smarthub_tid',
					'title'    => __( 'Terminal (TID)', 'knit-pay-upi' ),
					'type'     => 'select',
					'options'  => $terminal_array,
				];
			} catch ( Exception $e ) {

			}

			// TODO Show logout button
			return $fields;
		}
		
		// Registered Phone.
		$fields[] = [
			'section'  => 'general',
			'title'    => __( 'Cashier Phone Number', 'knit-pay-upi' ),
			'type'     => 'description',
			'callback' => [ $this, 'field_send_phone_otp' ],
			'tooltip'  => __( 'Phone number of HDFC Cashier', '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->hide_mobile_qr  = false;
		$config->hide_pay_button = true;

		$config->device_id      = $this->get_meta( $post_id, 'upi_qr_hdfc_smarthub_device_id' );
		$config->session_id     = $this->get_meta( $post_id, 'upi_qr_hdfc_smarthub_session_id' );
		$config->pin            = $this->get_meta( $post_id, 'upi_qr_hdfc_smarthub_pin' );
		$config->tid            = $this->get_meta( $post_id, 'upi_qr_hdfc_smarthub_tid' );
		$config->phone_number   = $this->get_meta( $post_id, 'upi_qr_hdfc_smarthub_phone_number' );
		$config->app_version    = $this->get_meta( $post_id, 'upi_qr_hdfc_smarthub_app_version' );
		$config->encryption_key = $this->get_meta( $post_id, 'upi_qr_hdfc_smarthub_encryption_key' );

		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 );

		if ( '' === $config->device_id ) {
			$device_id = self::generate_random_string( 16 );
			update_post_meta( $config_id, '_pronamic_gateway_upi_qr_hdfc_smarthub_device_id', $device_id );
		}
		
		// Fetch Encrytion Key and App Version.
		if ( '' === $config->encryption_key ) {
			try {
				$api = new API( $config );
				$api->encrypt_key_rapid();
			} catch ( Exception $e ) {
				echo $e->getMessage();
				exit;
			}
		}

		$new_phone_number = isset( $_POST['_pronamic_gateway_upi_qr_hdfc_smarthub_phone_number'] ) ? sanitize_text_field( $_POST['_pronamic_gateway_upi_qr_hdfc_smarthub_phone_number'] ) : '';
		if ( $new_phone_number !== $config->phone_number && '' !== $new_phone_number ) {
			update_post_meta( $config_id, '_pronamic_gateway_upi_qr_hdfc_smarthub_phone_number', $new_phone_number );
		}

		$otp = isset( $_POST['_pronamic_gateway_upi_qr_hdfc_smarthub_otp'] ) ? sanitize_text_field( $_POST['_pronamic_gateway_upi_qr_hdfc_smarthub_otp'] ) : '';
		if ( '' !== $otp ) {
			try {
				$api = new API( $config );
				$api->verify_otp( $otp );
				$this->update_terminal( $config_id );
			} catch ( Exception $e ) {
				echo $e->getMessage();
				exit;
			}

			return;
		}

		// Send OTP.
		if ( '' === $config->tid ) {
			$config = $this->get_config( $config_id );
			try {
				$api             = new API( $config );
				$send_otp_result = $api->validate_user();
			} catch ( Exception $e ) {
				self::clear_config( $config_id );
				echo $e->getMessage();
				exit;
			}

			if ( 'Success' === $send_otp_result->status ) {
				update_post_meta( $config_id, '_pronamic_gateway_upi_qr_hdfc_smarthub_session_id', $send_otp_result->sessionId );
			}
			return;
		}

		// Update Terminal if changed by admin.
		$this->update_terminal( $config_id );
	}

	// Update Terminal.
	private function update_terminal( $config_id ) {
		$config = $this->get_config( $config_id );

		$new_tid = isset( $_POST['_pronamic_gateway_upi_qr_hdfc_smarthub_tid'] ) ? sanitize_text_field( $_POST['_pronamic_gateway_upi_qr_hdfc_smarthub_tid'] ) : '';
		if ( '' !== $config->tid ) {
			if ( '' === $new_tid || $new_tid === $config->tid ) {
				return;
			}
		}

		try {
			$api                = new API( $config );
			$user_terminal_info = $api->get_user_terminal_info();
		} catch ( Exception $e ) {
			echo $e->getMessage();
			exit;
		}

		if ( 'Success' !== $user_terminal_info->status ) {
			return;
		}

		// If TID is not selected, select first TID.
		if ( $new_tid === '' ) {
			$new_tid = key( reset( $user_terminal_info->terminalInfo ) );
		}

		$terminal_info = reset( $user_terminal_info->terminalInfo )->$new_tid;
		$this->get_vpa( $config_id, $api, $terminal_info );

		update_post_meta( $config_id, '_pronamic_gateway_upi_qr_hdfc_smarthub_tid', $new_tid );
		delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_hdfc_smarthub_otp' );
	}

	private function get_vpa( $config_id, $api, $terminal_info ) {
		try {
			$qr_url = $terminal_info->payments->qr->digitalStaticQRPath;
			if ( empty( $qr_url ) ) {
				return;
			}

			$qrcode  = new QrReader( $qr_url, QrReader::SOURCE_TYPE_FILE, false );
			$qr_data = $api->decode_emv_qr( $qrcode->text() );

			update_post_meta( $config_id, '_pronamic_gateway_upi_qr_payee_name', $terminal_info->companyName );
			update_post_meta( $config_id, '_pronamic_gateway_upi_qr_merchant_category_code', $terminal_info->mccCode );
			update_post_meta( $config_id, '_pronamic_gateway_upi_qr_vpa', $qr_data['26']['01'] );
		} catch ( Exception $e ) {
			// It's okay if we don't not get the vpa, admin will enter manually, don't do anything.
		}
	}
	
	public static function clear_config( $config_id ) {
		delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_hdfc_smarthub_tid' );
		// delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_hdfc_smarthub_device_id' );
		delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_hdfc_smarthub_encryption_key' );
		delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_hdfc_smarthub_app_version' );
		delete_post_meta( $config_id, '_pronamic_gateway_upi_qr_hdfc_smarthub_session_id' );
		
		// TODO send warning email to WordPress Admin.
	}

	/**
	 * 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_hdfc_smarthub_phone_number',
				'name'      => '_pronamic_gateway_upi_qr_hdfc_smarthub_phone_number',
				'type'      => 'text',
				'value'     => $this->get_meta( $config_id, 'upi_qr_hdfc_smarthub_phone_number' ),
				'inputmode' => 'numeric',
				'pattern'   => '\d*',
			]
		);
		$input_phone_number->output();

		$button_send_otp           = new Element(
			'a',
			[
				'id'    => 'hdfc-smarthub-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 Cashier Phone number registered at HDFC SmartHub Vyapar. Read the steps above to know how to create a cashier account.' );
	}
	
	/**
	 * 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_hdfc_smarthub_otp',
				'name'      => '_pronamic_gateway_upi_qr_hdfc_smarthub_otp',
				'type'      => 'text',
				'inputmode' => 'numeric',
				'pattern'   => '\d*',
			]
		);
		$input_otp->output();
		
		$button_submit_otp           = new Element(
			'a',
			[
				'id'    => 'hdfc-smarthub-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 cashier phone number' );
	}
	
	public static function generate_random_string( $length = 16 ) {
		$characters    = '0123456789abcdef';
		$random_string = '';
		
		for ( $i = 0; $i < $length; $i++ ) {
			$random_string .= $characters[ rand( 0, strlen( $characters ) - 1 ) ];
		}
		
		return $random_string;
	}
}
