<?php
add_action( 'wp_enqueue_scripts', 'mintcsr_enqueue_scripts_cb' );
function mintcsr_enqueue_scripts_cb(){
	wp_register_script('tokenmint-abi', plugin_dir_url( __FILE__ ). 'tokenmint-abi.js', '','1.0.0', true);
}

function get_mint_csr_web3_callback(){
	wp_enqueue_script('tokenmint-abi');
	global $wpdb;
	$currentUserData = wp_get_current_user();
    ob_start();
    $html = "";
	$microNonce = base64_encode($currentUserData->id . md5('025CipTokenMintCip025'));
    ?>
    <div class="row">
        <div class="col-md-12">
            <button id="connectWallet">Connect Wallet</button>
            <p id="walletAddress"></p>

			<div class="mint_section" style="display: none;">
				<div class="form-group">
					<label for="amount">Amount to Mint:</label>
					<input class="form-control" type="text" name="amount" id="amount" min="1" placeholder="Enter amount">
				</div>
				<button id="mintButton" disabled>Mint Tokens</button>
				<input type="hidden" name="microNonce" value="<?php echo $microNonce; ?>" />
			</div>
        </div>
    </div>
    <?php
    $html .= ob_get_clean();
    return $html;
}
add_action('wp_footer', 'minting_token_script');
function minting_token_script(){
?><script>jQuery(document).ready(function($){
	if( $('#mintButton').length > 0 ){

		let web3;
		let userAccount;
		var block_config_mint = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };

		if (typeof window.ethereum !== 'undefined') {
			const provider = window.ethereum;
			provider.on('accountsChanged', (accounts) => {
				$('.mint_section').hide();
				$('.mint_section input[name=amount]').val('');
				document.getElementById('walletAddress').innerText = '';
				document.getElementById('mintButton').disabled = true;
			});
		}

		async function connectWallet() {

			$.blockUI(block_config_mint);

			if (typeof window.ethereum !== 'undefined') {
				try {
					await window.ethereum.request({ method: 'eth_requestAccounts' });
					web3 = new Web3(window.ethereum);
					const accounts = await web3.eth.getAccounts();
					userAccount = accounts[0];
					document.getElementById('walletAddress').innerText = `Connected: ${userAccount}`;
					document.getElementById('mintButton').disabled = false;
					$('.mint_section').show();
					$.unblockUI();
				} catch (error) {
					Swal.fire({ type: 'error', title: 'Error connecting to MetaMask', 'text' : error });
					$.unblockUI();
				}
			} else {
				Swal.fire({ type: 'error', title: 'MetaMask is not installed. Please install it to continue.' });
				$.unblockUI();
			}
		}



		function mintTokens() {
			if (!userAccount) {
				Swal.fire({ type: 'error', title: 'Please connect your wallet first.' });
				return;
			}

			const amountInput = document.getElementById('amount').value;
			if (!amountInput || amountInput <= 0) {
				Swal.fire({ type: 'error', title: 'Please enter a valid amount to mint.' });
				return;
			}

			$.blockUI(block_config_mint);

			$.ajax({
				method: "POST",
				url: cipscript.ajax_url,
				data: { 'action' : 'checkTokenMintingData', 'userAccount' : userAccount, 'amountInput' : amountInput, 'microNonce': $('input[name=microNonce]').val() },
				success: async function (response) {

					var obj = JSON.parse( response );
					if( obj.error == 0 ){
						const mintAmount = web3.utils.toWei(amountInput, 'ether');
			
						const tokenAddress = obj.data.tokenEthAddress;
						const tokenContract = new web3.eth.Contract(tokenMintABI, tokenAddress);
			
						try {
							const gasEstimate = await tokenContract.methods.mint(userAccount, mintAmount).estimateGas({ from: userAccount });
							
							const receipt = await tokenContract.methods.mint(userAccount, mintAmount)
							.send({ from: userAccount, gas: gasEstimate });
							
							if( receipt.transactionHash ){

								$.blockUI(block_config_mint);

								$.ajax({
									method: "POST",
									url: cipscript.ajax_url,
									data: {'action':'saveMintTransactionData', 'amountInput' : amountInput, 'microNonce': $('input[name=microNonce]').val(), 'mode': obj.data.mode, 'transHash' : receipt.transactionHash},
									success: function (response) {
										var obj = JSON.parse( response );
										if( obj.error == 0 ){
											Swal.fire({ type: 'success', title: 'Minting successful! Transaction Hash', 'text' : receipt.transactionHash, allowOutsideClick: false, onClose: function(){
												window.location.reload();
											} });
										}else{
											Swal.fire({ type: 'error', title: 'Minting successful! But Transaction Hash not saved in logs', 'text' : receipt.transactionHash, allowOutsideClick: false});
										}
										$.unblockUI();
									},
									error: function () {
										Swal.fire({ type: 'error', title: 'An error was encountered.', text: ''});
										$.unblockUI();
										return false;
									}
								});

							}
							
						} catch (error) {
							Swal.fire({ type: 'error', title: 'Minting failed.', 'text' : error });
							$.unblockUI();
						}
					}else{
						Swal.fire({ type: 'error', title: obj.msg, text: ''});
						$.unblockUI();
					}


				},
				error: function () {
					Swal.fire({ type: 'error', title: 'An error was encountered.', 'text' : error });
					$.unblockUI();
					return false;
				}
			});

		}

		document.getElementById('connectWallet').onclick = connectWallet;
		document.getElementById('mintButton').onclick = mintTokens;

		$(".mint_section input[name=amount]").bind("input", function () {
			var c = this.selectionStart,
			r = /[^0-9]/gi,
			v = $(this).val();
			if( r.test(v) ){
				$(this).val(v.replace(r, ""));
				c--;
			}
			this.setSelectionRange(c, c);
		});

	}

});</script><?php
}
add_action('wp_ajax_checkTokenMintingData', 'cip_checkTokenMintingData_callback');
function cip_checkTokenMintingData_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableMintCsr = $wpdb->prefix.'mint_csr';
	$currentUserData = wp_get_current_user();
	$isError = false;
	$data = array();
	$csr25_wallet_api_mode = ( !empty( get_option('csr25_wallet_api_mode') ) ) ? get_option('csr25_wallet_api_mode') : 'test';
	$tokenEthAddress = ( $csr25_wallet_api_mode == 'live' ) ? get_option('csr25_wallet_api_mode_live_tkn') : get_option('csr25_wallet_api_mode_test_tkn');


	$microNonceRaw = base64_decode( $_POST['microNonce'] );
	$decryptedUserId = preg_replace(sprintf('/%s/', md5('025CipTokenMintCip025') ), '', $microNonceRaw);

	if( $decryptedUserId != $currentUserData->id ){
		$out = array( "error" => 1, 'msg' => __('Unauthorized request.', CIP_TXTDOMAIN) );
		$isError = true;
		echo wp_json_encode($out);
		exit;
	}

	$getMintPermissionUsers = $wpdb->get_row("SELECT * FROM $tableMintCsr WHERE 1 AND `email` = '".$currentUserData->user_email."' AND `user_id` = ".$currentUserData->id."");
	if( !$getMintPermissionUsers ){
		$out = array( "error" => 1, 'msg' => __('You don\'t have permission for mint.', CIP_TXTDOMAIN) );
		$isError = true;
		echo wp_json_encode($out);
		exit;
	}


	$liveTokenCreator = '0x126679944d8e07C02073684d67a88abc82D9BEe5';
	$testTokenCreator = '0xd331b48da03A3021904F08E641106FCe8B973cA6';

	if( $csr25_wallet_api_mode == 'live' ){
		if( strtolower( $_POST['userAccount'] ) != strtolower( $liveTokenCreator ) ){
			$out = array( "error" => 1, 'msg' => __('Invalid Account connected to MetaMask.', CIP_TXTDOMAIN) );
			$isError = true;
			echo wp_json_encode($out);
			exit;
		}
	}else if( $csr25_wallet_api_mode == 'test' ){
		if( strtolower( $_POST['userAccount'] ) != strtolower( $testTokenCreator ) ){
			$out = array( "error" => 1, 'msg' => __('Invalid account connected to MetaMask.', CIP_TXTDOMAIN) );
			$isError = true;
			echo wp_json_encode($out);
			exit;
		}
	}else{
		$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
		$isError = true;
		echo wp_json_encode($out);
		exit;
	}

	if( !is_numeric( $_POST['amountInput'] ) ){
		$out = array( "error" => 1, 'msg' => __('Invalid Amount to Mint.', CIP_TXTDOMAIN) );
		$isError = true;
		echo wp_json_encode($out);
		exit;
	}

	if( $_POST['amountInput'] > 10000000 ){
		$out = array( "error" => 1, 'msg' => __('Minting are not allow more then 10 Million.', CIP_TXTDOMAIN) );
		$isError = true;
		echo wp_json_encode($out);
		exit;
	}


	if( !$isError ){
		$data = [
			'mintAmount'		=>	$_POST['amountInput'],
			'tokenEthAddress'	=>	$tokenEthAddress,
			'mode'				=>	$csr25_wallet_api_mode,
		];
		$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN), 'data' => $data );
	}

	echo wp_json_encode($out);
	exit;
}
add_action('wp_ajax_saveMintTransactionData', 'cip_saveMintTransactionData_callback');
function cip_saveMintTransactionData_callback(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableMintTransaction = $wpdb->prefix.'mint_transaction';
	$tableMintCsr = $wpdb->prefix.'mint_csr';
	$currentUserData = wp_get_current_user();

	$microNonceRaw = base64_decode( $_POST['microNonce'] );
	$decryptedUserId = preg_replace(sprintf('/%s/', md5('025CipTokenMintCip025') ), '', $microNonceRaw);

	if( $decryptedUserId != $currentUserData->id ){
		$out = array( "error" => 1, 'msg' => __('Unauthorized request.', CIP_TXTDOMAIN) );

		create_cip_logs_entery( $currentUserData->ID, 'mint', '','sa', 'Error on saving mint transaction. TxnHash : ' .$_POST['transHash'] , true );
		echo wp_json_encode($out);
		exit;
	}

	$getMintPermissionUsers = $wpdb->get_row("SELECT * FROM $tableMintCsr WHERE 1 AND `email` = '".$currentUserData->user_email."' AND `user_id` = ".$currentUserData->id."");
	if( !$getMintPermissionUsers ){
		$out = array( "error" => 1, 'msg' => __('You don\'t have permission for mint.', CIP_TXTDOMAIN) );
		create_cip_logs_entery( $currentUserData->ID, 'mint', '','sa', 'Error on saving mint transaction. TxnHash : ' .$_POST['transHash'] , true );
		echo wp_json_encode($out);
		exit;
	}

	$insert = $wpdb->insert( $tableMintTransaction, [ 'userId' => $currentUserData->id, 'userEmail' => $currentUserData->user_email, 'mintAmount' => $_POST['amountInput'], 'mintTransactionHash' => $_POST['transHash'], 'mode' => $_POST['mode'], '_date' => date_i18n('Y-m-d H:i:s') ] );
	if( $insert ){
		$out = array( "error" => 0, 'msg' => __('Success', CIP_TXTDOMAIN) );
		create_cip_logs_entery( $currentUserData->ID, 'mint', '','sa', 'Mint transaction saved by ' . $currentUserData->user_email .' at '. date_i18n('d/m/Y H:i A') .'. TxnHash : ' .$_POST['transHash'] . 'Amount: '. $_POST['amountInput'], true );
	}else{
		create_cip_logs_entery( $currentUserData->ID, 'mint', '','sa', 'Error on saving mint transaction. TxnHash : ' .$_POST['transHash'] , true );
	}
	

	echo wp_json_encode($out);
	exit;
}