<?php

function get_sa_member_to_member_transfer(){

    $html = "";

    ob_start();

    ?>

    <form name="mtom_transfer_frm" id="mtom_transfer_frm" class="shadow m-t-3 p-3 bg-white rounded">

    <div class="row">

        <div class="col-md-6 pb-2">

            <h6 for="token"><?php _e('Token', CIP_TXTDOMAIN); ?></h6>

            <select name="token" id="token" class="form-control">

                <option value="CSR">CSR</option>

                <option value="CSR25">CSR25</option>

            </select>

        </div>

        <div class="col-md-6">

            <div class="form-group mb-1">

                <h6 for="from_member"><?php _e('From member', CIP_TXTDOMAIN); ?></h6>

                <select class="regular-text"  class="form-control" id="from_member" name="from_member"></select>

            </div>

            <div class="from_member_wallet_amount"></div>

        </div>

        <div class="col-md-6">

            <div class="form-group">

                <h6 for="mtom_amount"><?php _e('Amount', CIP_TXTDOMAIN); ?></h6>

                <input type="text" class="form-control" name="mtom_amount" id="mtom_amount" />

                <span id="error-message" style="color: red; display: none;">Amount exceeds the balance!</span>

            </div>

        </div>
        <div class="col-md-6">

            <div class="form-group">

                <h6 for="to_member"><?php _e('To member', CIP_TXTDOMAIN); ?></h6>

                <select class="regular-text"  class="form-control" id="to_member" name="to_member"></select>

            </div>

        </div>

    </div>

    <div class="row">

        <div class="col-md-12">

            <div class="form-group">

                <h6 for="description"><?php _e('Description', CIP_TXTDOMAIN); ?></h6>

                <textarea class="form-control" name="description" id="description"></textarea>

            </div>

        </div>

    </div>

    <button type="button" class="btn btn-primary checkMtoMTransferConfirmation"><?php _e('Submit', CIP_TXTDOMAIN); ?></button>

    <input type="hidden" name="action" value="cip_sa_mtomtransfer_act" />

    <input type="hidden" name="_micro" value="<?php echo wp_create_nonce('_CIPxMtoMTransferxCIP_'); ?>" />

    <div class="modal fade" id="csrMtoMTransferModal" tabindex="-1" role="dialog" aria-hidden="true">

        <div class="modal-dialog modal-dialog-centered" role="document">

            <div class="modal-content">

                <div class="modal-body">

                    <div class="container-fluid">

                        <span class="withdrawal_close_btn close" data-dismiss="modal">&times;</span>

                        <h4><?php _e('Member to Member Transfer', CIP_TXTDOMAIN); ?></h4>

                        <div class="csrcsrMtoMTransferBody"></div>

                    </div>

                </div>

            </div>

        </div>

    </div>

    </form>

    <?php

    $html .= ob_get_clean();

	return $html;

}

add_action('wp_footer','member_to_member_transfer_script');

function member_to_member_transfer_script(){

?>

<script>

jQuery(document).ready(function($){

    if( $('#mtom_transfer_frm').length > 0 ){

        var $form = $('#mtom_transfer_frm');

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

        $('#from_member').select2({

			placeholder: 'From Member',

			minimumInputLength: 2,

			ajax: {

				url: cipscript.ajax_url,

				dataType: 'json',

				data: function (params) {

					var query = {

						search: params.term,

						action: 'wp_users_fetch_act'

					}

					return query;

				}

			},

			processResults: function (response) {

				return {

				   results: response

				};

			},

			selectionCssClass: 'select2_from_member',

            allowClear: true

		});

        $('#to_member').select2({

			placeholder: 'To Member',

			minimumInputLength: 2,

			ajax: {

				url: cipscript.ajax_url,

				dataType: 'json',

				data: function (params) {

					var query = {

						search: params.term,

						action: 'wp_users_fetch_act'

					}

					return query;

				}

			},

			processResults: function (response) {

				return {

				   results: response

				};

			},

			selectionCssClass: 'select2_to_member',

            allowClear: true

		});

        function checkUserWalletBalence(){

            var thisVal = $('#from_member').val();

            var token = $('#token').val();

            if( thisVal != "" ){

                var data = { 'action' : 'checkUserWalletDetailsAct', 'value' : thisVal, 'token' : token, '_micro' : "<?php echo wp_create_nonce('_XycheckUserWalletAmountDetailsyX_'); ?>" };

                $form.block( block_config );

                $('.from_member_wallet_amount').html('');

                $.post(cipscript.ajax_url, data, function(response) {

                    var obj = JSON.parse( response );

                    if( obj.error == 0 ){

                        $('.from_member_wallet_amount').html( obj.html );

                    }else{

                        swalToast({ type: 'error', title: obj.msg });

                    }

                    $form.unblock();

                });

            }

        }

        $('#from_member').on('select2:select', function (e) {

            checkUserWalletBalence();

            // var thisVal = $(this).val();

            // var token = $('#token').val();

            // if( thisVal != "" ){

            //     var data = { 'action' : 'checkUserWalletDetailsAct', 'value' : thisVal, 'token' : token, '_micro' : "<?php echo wp_create_nonce('_XycheckUserWalletAmountDetailsyX_'); ?>" };

            //     $form.block( block_config );

            //     $('.from_member_wallet_amount').html('');

            //     $.post(cipscript.ajax_url, data, function(response) {

            //         var obj = JSON.parse( response );

            //         console.log(response);

            //         if( obj.error == 0 ){

            //             $('.from_member_wallet_amount').html( obj.html );

            //         }else{

            //             swalToast({ type: 'error', title: obj.msg });

            //         }

            //         $form.unblock();

            //     });

            // }

        });

        $('#token').on('change', function() {

            var divText = $('.from_member_wallet_amount').text().trim();

            if (divText.includes('Balance')) {

                checkUserWalletBalence();

            }

        });

        //check amount is not more then balance

        $('#mtom_amount').on('input', function() {

            var balanceText = $('.from_member_wallet_amount').text().trim();

            var match = balanceText.match(/Balance:\s?([\d,]+)/);

            var balanceAmount = parseInt(match[1].replace(/,/g, ''), 10);

            var enteredAmount = parseFloat($(this).val());

            if (enteredAmount > balanceAmount) {

                $('#error-message').show();

                $('.checkMtoMTransferConfirmation').prop('disabled', true);

            } else {

                $('#error-message').hide();

                $('.checkMtoMTransferConfirmation').prop('disabled', false);

            }

        });

        $("input[name='mtom_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);

        });

        $('body').on('click', '.checkMtoMTransferConfirmation', function(){

            var $form = $('#mtom_transfer_frm');

            var from_member = $form.find('select[name=from_member]').val();

            var to_member = $form.find('select[name=to_member]').val();

            var mtom_amount = $form.find('input[name=mtom_amount]').val();

            var description = $form.find('textarea[name=description]').val();

            if( from_member == "" || from_member == null ){

                swalToast({ type: 'error', title: 'Please select From Member' });

                return false;

            }

            if( to_member == "" || to_member == null ){

                swalToast({ type: 'error', title: 'Please select To Member' });

                return false;

            }

            if( mtom_amount == "" || mtom_amount <= 0 ){

                swalToast({ type: 'error', title: 'Please enter Amount' });

                return false;

            }

            if( description == "" ){

                swalToast({ type: 'error', title: 'Please enter Description' });

                return false;

            }

            $form.block( block_config );

            var data = $form.serialize() + '&checkmtmconfirmation=yes';

            $.post(cipscript.ajax_url, data, function(response) {

                var obj = JSON.parse( response );

                if( obj.error == 0 ){

                    $('#csrMtoMTransferModal .csrcsrMtoMTransferBody').html( obj.html );

                    $('#csrMtoMTransferModal').modal({backdrop: 'static',keyboard: false});

                }else{

				    swalToast({ type: 'error', title: obj.msg });

			    }

                $form.unblock();

            });

            return false;

        });

        $('body').on('submit', '#mtom_transfer_frm', function(e){

            e.preventDefault();

            $form = $(this);

            if( $(this).find('input[name="user_ga_otp"]').val() == "" ){

                swalToast({ type: 'error', title: 'Please enter the authentication code' });

                return false;

            }

            var data = $(this).serialize() + '&mtmconfirmation=yes';

            $.blockUI(block_config);

            $.post(cipscript.ajax_url, data, function(response) {

                var obj = JSON.parse( response );

                if( obj.error == 0 ){

                    swalToast({ type: 'success', title: obj.msg });

                    $("#csrMtoMTransferModal").modal('hide');

                    $form[0].reset();

                    window.location.reload();

                }else{

                    swalToast({ type: 'error', title: obj.msg });

                }

                $.unblockUI();

            });

            return false;

        });

    }

});

</script>

<?php

}

add_action( 'wp_ajax_wp_users_fetch_act', 'cip_wp_users_fetch_act_callback' );

function cip_wp_users_fetch_act_callback(){

	$out = array();

    $args = array(

		'role' 		=> 'member',

		'number' 	=> 100,

		'orderby'	=> 'login',

		'order'		=> 'asc',

	);

    $args = wp_parse_args( ['search' => "*{$_REQUEST['search']}*", 'search_columns' => ['user_login', 'user_email'] ], $args );

    $get_users = new WP_User_Query( $args );

    $memberData = $get_users->get_results();

	if( $memberData ){

		foreach( $memberData as $get_user ){

            $encryptID = base64_encode($get_user->ID . md5('MtoMTransferUserId'));

			$out[] = array(

				'id'	=>	$encryptID,

				'text'	=>	$get_user->user_email,

			);

		}

	}

	echo wp_json_encode( array( 'results' => $out ) );

	exit;

}

add_action( 'wp_ajax_checkUserWalletDetailsAct', 'cip_checkUserWalletDetailsAct_callback' );

function cip_checkUserWalletDetailsAct_callback(){

	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );

	$html = "";

    if( current_user_can( 'supportagent' ) && wp_verify_nonce( $_POST['_micro'], '_XycheckUserWalletAmountDetailsyX_' ) ){

        $selected_token = $_POST['token'];

        $decryptedId_raw = base64_decode( $_POST['value'] );

		$user_id = preg_replace(sprintf('/%s/', md5('MtoMTransferUserId') ), '', $decryptedId_raw);

        $userData = get_user_by( 'id', $user_id );

        if( $userData ){

            $refAccount = $userData->user_email;

            $csr_balance_total = get_user_csr_balance( $refAccount, 'total', $selected_token );

            $csr_balance = get_user_csr_balance( $refAccount,'available', $selected_token);

            ob_start();

            ?>

            <!-- <p class="mb-0"><?php echo sprintf( __('CSR Balance: %s', CIP_TXTDOMAIN), number_format( $csr_balance ) ); ?></p> -->

            <?php

            if ($selected_token === 'CSR25') {

                echo sprintf(__('CSR25 Balance: %s', CIP_TXTDOMAIN), number_format($csr_balance));

            } else {

                echo sprintf(__('CSR Balance: %s', CIP_TXTDOMAIN), number_format($csr_balance));

            }

            ?>

            <?php

            $html .= ob_get_clean();

            $out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );

        }else{

            $out = array( "error" => 1,'msg' => __('Member not found.',CIP_TXTDOMAIN) );

        }

    }

    echo wp_json_encode( $out );

	exit;

}

add_action( 'wp_ajax_cip_sa_mtomtransfer_act', 'cip_sa_mtomtransfer_act_callback' );

function cip_sa_mtomtransfer_act_callback(){

    global $wpdb;

    $tableTransactionHistory = $wpdb->prefix.'csr_delivery_transaction_history';

    $tableTnternalTransfer = $wpdb->prefix.'internaltransfer';

	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );

	$html = "";

    if( current_user_can( 'supportagent' ) && wp_verify_nonce( $_POST['_micro'], '_CIPxMtoMTransferxCIP_' ) ){

        $decryptedId_from_raw = base64_decode( $_POST['from_member'] );

        $decryptedId_to_raw = base64_decode( $_POST['to_member'] );

		$from_user_id = preg_replace( sprintf('/%s/', md5('MtoMTransferUserId') ), '', $decryptedId_from_raw );

		$to_user_id = preg_replace( sprintf('/%s/', md5('MtoMTransferUserId') ), '', $decryptedId_to_raw );

        $fromUserData = get_user_by( 'id', $from_user_id );

        $toUserData = get_user_by( 'id', $to_user_id );

        $current_user = wp_get_current_user();

		$user_id = $current_user->ID;

        $google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );

		$google_auth_key_walletdelivery = get_user_meta( $user_id, 'google_auth_key_walletdelivery', true );

		$ga2fa_delivery_enabled = ( !empty( $google_auth_key ) && $google_auth_key_walletdelivery == 1 ) ? 1 : 0;

		if( $ga2fa_delivery_enabled != 1 ){

			$out = array( "error" => 1,'msg' => __('Please enable Google Authenticator 2FA in your Profile to complete this task.',CIP_TXTDOMAIN) );

			echo wp_json_encode( $out );

			exit;

		}

        if( $fromUserData->ID == $toUserData->ID ){

            $out = array( "error" => 1,'msg' => __('Not allow member to member transfer on same member.',CIP_TXTDOMAIN) );

			echo wp_json_encode( $out );

			exit;

        }

        $csr_balance = get_user_csr_balance( $fromUserData->user_email, 'available', strtolower( $_POST['token'] ) );

        if( $_POST['mtom_amount'] > $csr_balance ){

            $out = array( "error" => 1,'msg' => __('You can not transfer more then user balance.',CIP_TXTDOMAIN) );

			echo wp_json_encode( $out );

			exit;

        }

        if( isset( $_POST['checkmtmconfirmation'] ) && $_POST['checkmtmconfirmation'] == 'yes' ){

            ob_start();

            ?>

            <div class="table-responsive">

            <table>

                <tbody>

                    <!-- <tr><td><?php echo __('Transfer amount:', CIP_TXTDOMAIN); ?></td><td><?php echo sprintf( __('%s CSR', CIP_TXTDOMAIN), number_format( $_POST['mtom_amount'] ) ); ?></td></tr> -->

                    <?php

                    if ($_POST['token'] === 'CSR25') { ?>

                        <tr><td><?php echo __('Transfer amount:', CIP_TXTDOMAIN); ?></td>

                        <td><?php echo sprintf( __('%s CSR25', CIP_TXTDOMAIN), number_format($_POST['mtom_amount'])); ?></td></tr>

                    <?php } else { ?>

                        <tr><td><?php echo __('Transfer amount:', CIP_TXTDOMAIN); ?></td>

                        <td><?php echo sprintf( __('%s CSR', CIP_TXTDOMAIN), number_format($_POST['mtom_amount'])); ?></td></tr>

                    <?php } ?>

                    <tr><td><?php echo __('From:', CIP_TXTDOMAIN); ?></td><td><?php echo $fromUserData->user_email; ?></td></tr>

                    <tr><td><?php echo __('To:', CIP_TXTDOMAIN); ?></td><td><?php echo $toUserData->user_email; ?></td></tr>

                </tbody>

            </table>

            </div>

            <hr class="mt-3 mb-3">

            <div class="otp_section pb-3">

                <label for="user_ga_otp"><?php echo __('Please enter the authentication code', CIP_TXTDOMAIN); ?></label>

                <input type="text" name="user_ga_otp" id="user_ga_otp" class="input mb-1" maxlength="6" pattern="{0-9}+" />

                <small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>

            </div>

            <button type="submit" class="btn btn-secondary"><?php _e('Submit', CIP_TXTDOMAIN); ?></button>

            <button type="button" class="btn btn-secondary" data-dismiss="modal"><?php _e('Cancel', CIP_TXTDOMAIN) ?></button>

            <?php

            $html .= ob_get_clean();

            $out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );

        }else if( isset( $_POST['mtmconfirmation'] ) && $_POST['mtmconfirmation'] == 'yes' ){

            if( $fromUserData && $toUserData && ( !empty( $_POST['mtom_amount'] ) && $_POST['mtom_amount'] > 0 ) ){

                if( !empty( $_POST['user_ga_otp'] ) ){

                    $google2fa = new \PragmaRX\Google2FA\Google2FA();

                    if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){

                        $withdrawal_id = uniqidReal();

                        $insertTransferData = array(

                            'ref_no'            =>  $withdrawal_id,

                            'short_description' =>  $_POST['description'],

                            'from_user'         =>  $fromUserData->user_email,

                            'to_user'           =>  $toUserData->user_email,

                            'amount'            =>  $_POST['mtom_amount'],

                            '_date'             =>  date_i18n('Y-m-d H:i:s'),

                            'token'              =>$_POST['token']

                        );

                        $internalTransferInsert = $wpdb->insert( $tableTnternalTransfer, $insertTransferData );

                        if( $internalTransferInsert ){

                            $logs = sprintf( __('%s CSR Withdraw, member to meber transfer from %s to %s, Withdrawal-ID: %s by %s at %s', CIP_TXTDOMAIN), number_format( $_POST['mtom_amount'] ), $fromUserData->user_email, $toUserData->user_email, $withdrawal_id, $current_user->user_email, date_i18n('d/m/Y H:i A') );

                            $short_description_withdrawal = sprintf( __('%s transfer to %s', CIP_TXTDOMAIN), $_POST['token'], $toUserData->user_email );

                            $transactionData = array(

                                'user_id'			=>	$fromUserData->ID,

                                'txn_id'			=>	$withdrawal_id,

                                'txn_id_ref'		=>	$withdrawal_id,

                                'email'				=>	$fromUserData->user_email,

                                'username'			=>	$fromUserData->user_login,

                                'withdrawal_amount'	=>	$_POST['mtom_amount'],

                                'received_amount'	=>	$_POST['mtom_amount'],

                                'withdrawal_fee'	=>	0,

                                'type'				=>	'withdrawal',

                                'description'		=>	sprintf( __('%s %s Withdraw, member to meber transfer to %s', CIP_TXTDOMAIN), number_format( $_POST['mtom_amount'] ), $_POST['token'], $toUserData->user_email ),

                                'short_description' =>  $short_description_withdrawal,

                                '_date'				=>	date_i18n('Y-m-d H:i:s'),

                                'status'			=>	2,

                                'token'              => $_POST['token'],

                            );

                            $withdrawTransInsert = $wpdb->insert( $tableTransactionHistory, $transactionData );

                            if( $withdrawTransInsert ){

                                create_cip_logs_entery( $current_user->ID, 'withdraw', '','sm', $logs, true );

                            }else{

                                $logs = sprintf( __('Failed member to meber transfer withdrawal: %s. %s %s, from %s to %s by %s at %s', CIP_TXTDOMAIN), $wpdb->last_error, number_format( $_POST['mtom_amount'] ), $_POST['token'], $fromUserData->user_email, $toUserData->user_email, $current_user->user_email, date_i18n('d/m/Y H:i A') );

                                create_cip_logs_entery( $current_user->ID, 'withdraw', '','sm', $logs, true );

                            }

                            $deposit_id = uniqidReal();

                            $logsDeposit = sprintf( __('%s %s Deposit, member to meber transfer from %s to %s, Ref-ID: %s by %s at %s', CIP_TXTDOMAIN), number_format( $_POST['mtom_amount'] ), $_POST['token'], $fromUserData->user_email, $toUserData->user_email, $withdrawal_id, $current_user->user_email, date_i18n('d/m/Y H:i A') );

                            $short_description_deposit = sprintf( __('%s transfer from %s', CIP_TXTDOMAIN), $_POST['token'], $fromUserData->user_email );

                            $depositTransactionData = array(

                                'user_id'			=>	$toUserData->ID,

                                'txn_id'			=>	$deposit_id,

                                'txn_id_ref'		=>	$withdrawal_id,

                                'email'				=>	$toUserData->user_email,

                                'username'			=>	$toUserData->user_login,

                                'withdrawal_amount'	=>	0,

                                'received_amount'	=>	$_POST['mtom_amount'],

                                'withdrawal_fee'	=>	0,

                                'type'				=>	'deposit',

                                'description'		=>	sprintf( __('%s %s Deposit, member to meber transfer from %s', CIP_TXTDOMAIN), number_format( $_POST['mtom_amount'] ), $_POST['token'], $fromUserData->user_email ),

                                'short_description'	=>	$short_description_deposit,

                                '_date'				=>	date_i18n('Y-m-d H:i:s'),

                                'status'			=>	0,

                                'token'              =>$_POST['token'],

                            );

                            $depositTransInsert = $wpdb->insert( $tableTransactionHistory, $depositTransactionData );

                            if( $depositTransInsert ){

                                create_cip_logs_entery( $current_user->ID, 'deposit', '','sm', $logsDeposit, true );

                            }else{

                                $logs = sprintf( __('Failed member to meber transfer deposit: %s. %s %s, from %s to %s by %s at %s', CIP_TXTDOMAIN), $wpdb->last_error, number_format( $_POST['mtom_amount'] ), $_POST['token'], $fromUserData->user_email, $toUserData->user_email, $current_user->user_email, date_i18n('d/m/Y H:i A') );

                                create_cip_logs_entery( $current_user->ID, 'withdraw', '','sm', $logs, true );

                            }

                            $out = array( "error" => 0,'msg' => __('Transfer completed successfully.',CIP_TXTDOMAIN), 'html' => '' );

                        }else{

                            $logs = sprintf( __('Failed Member to Member Transfer. Error: %s', CIP_TXTDOMAIN), $wpdb->last_error );

                            $out = array( "error" => 1,'msg' => __('Failed Member to Member Transfer.',CIP_TXTDOMAIN) );

                        }

                    }else{

                        $out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );

                        echo wp_json_encode( $out );

                        exit;

                    }

                }else{

                    $out = array( "error" => 1,'msg' => __('Please enter the authentication code',CIP_TXTDOMAIN) );

                    echo wp_json_encode( $out );

                    exit;

                }

            }

        }

    }

    echo wp_json_encode( $out );

	exit;

}