<?php
function get_csr_remaining_dashboard(){
    $html = "";
    ob_start();
    $refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
    $csr_remaining_total_supply = ( !empty( get_option('csr_remaining_total_supply') ) ) ? get_option('csr_remaining_total_supply') : 0;
    ?>
    <div id="csr_remaining_custom_toolbar" class="mr-2">
        <!-- make banner at 1 place -->
        <label class="csr_remaning_amount_label" for="csr_remaning_amount">CSR remaining total supply : <span id="csr_remaning_amount"><?php echo number_format($csr_remaining_total_supply); ?></span> </label>
        <i class="fa fa-edit csr_remaming_edit_icon" data-toggle="modal" data-target="#update_csr_remaining_btn_modal" style="cursor: pointer;" title="Edit"></i>
        <!-- make banner at 1 place END -->

        <button id="add_csr_remaining_address_btn" class="btn btn-primary" data-toggle="modal" data-target="#add_csr_remaining_address_btn_modal"><?php _e('Add Address', CIP_TXTDOMAIN); ?></button>
        <button id="refresh_csr_remaining_btn" class="btn btn-primary" data-micro="<?php echo wp_create_nonce( $refAccount ); ?>"><i class="fas fa-sync-alt"></i></button>
    </div>
    <table id="sa_csr_remaining_address_list" data-filter-control="true" data-show-search-clear-button="true" data-pagination="true" data-toggle="table" data-show-columns="false" data-show-toggle="false" data-click-to-select="false" data-show-columns-toggle-all="false" data-show-export="false" data-click-to-select="false" class="table table-bordered" data-side-pagination="server" data-pagination="true" data-page-list="[10, 20, 50, 100]">
        <thead>
            <tr>
                <th data-field="id" class="id"><?php _e('ID', CIP_TXTDOMAIN); ?></th>
                <th data-field="wallet_address" class="wallet_address" data-filter-control="input"><?php _e('Address', CIP_TXTDOMAIN); ?></th>
                <th data-field="description" class="description" data-filter-control="input"><?php _e('Description', CIP_TXTDOMAIN); ?></th>
                <th data-field="amount" class="amount" data-filter-control="input"><?php _e('Amount', CIP_TXTDOMAIN); ?></th>
                <th data-field="action" class="action"><?php _e('Action', CIP_TXTDOMAIN); ?></th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
    <!-- make banner at 1 place -->
    <div class="modal fade" id="update_csr_remaining_btn_modal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">CSR remaining</h5>
                    <span class="withdrawal_close_btn close" data-dismiss="modal">&times;</span>
                </div>
                <?php echo do_shortcode('[CSR-REMAINING-TOTAL-SUPPLY-SETTING]'); ?>
            </div>
        </div>
    </div>
    <!-- make banner at 1 place END -->

    <div class="modal fade" id="add_csr_remaining_address_btn_modal" tabindex="-1" role="dialog">
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Add CSR Remaining Address</h5>
                    <span class="withdrawal_close_btn close" data-dismiss="modal">&times;</span>
                </div>
                <form id="AddCsrRemainingAddressForm" class="AddCsrRemainingAddressForm">
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="wallet_address">Wallet Address</label>
                            <input type="text" name="wallet_address" id="wallet_address" class="form-control" placeholder="Enter Wallet Address">
                        </div>
                        <div class="form-group">
                            <label for="description">Description</label>
                            <input type="text" name="description" id="description" class="form-control" placeholder="Enter description">
                        </div>
                        <div class="form-group">
                            <label for="user_ga_otp"><?php echo __('Authentication code', CIP_TXTDOMAIN); ?></label>
                            <input type="text" name="user_ga_otp" id="user_ga_otp" class="form-control mb-1" maxlength="6" pattern="{0-9}+" placeholder="Enter authentication code" />
                            <small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
                        </div>
                    </div>
                    <input type="hidden" name="action" value="addNewCsrRemainingWalletAddressAct" />
                    <input type="hidden" name="_micro" value="<?php echo wp_create_nonce( $refAccount ); ?>" />
                    <div class="modal-footer justify-content-start">
                        <button type="submit" class="btn btn-primary">Add Address</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
    <div class="modal fade" id="edit_csr_remaining_address_btn_modal" tabindex="-1" role="dialog">
		  <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
		    <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Edit CSR Remaining Address</h5>
                    <span class="withdrawal_close_btn close" data-dismiss="modal">&times;</span>
                </div>
                <div class="modal-edit-response"></div>
		    </div>
		  </div>
	</div>
    <?php
    $html .= ob_get_clean();
    return $html;
}
add_shortcode('CSR-REMAINING-TOTAL-SUPPLY-SETTING','csr_remaining_total_supply_setting_callback');
function csr_remaining_total_supply_setting_callback(){
    $html = "";
    ob_start();
    $csr_remaining_total_supply = ( !empty( get_option('csr_remaining_total_supply') ) ) ? get_option('csr_remaining_total_supply') : 0;
    ?>
    <div class="row">
		<div class="col-md-12">
			<div class="shadow p-3 bg-white rounded h-100">
				<form id="csr_remaining_total_supply_setting_frm" name="csr_remaining_total_supply_setting_frm">
					<h6><?php _e('CSR remaining total supply', CIP_TXTDOMAIN); ?></h6>
					<input type="text" name="csr_remaining_total_supply" id="csr_remaining_total_supply" value="<?php echo $csr_remaining_total_supply; ?>" class="form-control">
					<input type="hidden" name="action" value="csr_remaining_total_supply_setting_act">
					<input type="hidden" name="_micro" id="_micro" value="<?php echo wp_create_nonce('_ZyxcsrRemainingTotalSupplyxyZ_'); ?>">
					<br/>
					<button type="submit" class="form-control btn btn-primary"><?php _e('Submit', CIP_TXTDOMAIN); ?></button>
				</form>
			</div>
		</div>
	</div>
    <?php
    $html .= ob_get_clean();
    return $html;
}
add_action('wp_footer', 'csr_remaining_scripts');
function csr_remaining_scripts(){
    $sa_csr_remaining_address_list_url = add_query_arg( [
		'action'	=>	'sa_csr_remaining_address_list_loader',
		'pageid'	=>	get_the_ID(),
	], admin_url( 'admin-ajax.php' ) );
?><script>jQuery(document).ready(function($){
    var blockConfigSetting = { css: { backgroundColor: 'transparent', border: 'none' }, message: '<div class="blockUIspinner"></div>', baseZ: 1500, overlayCSS: { backgroundColor: '#FFFFFF', opacity: 0.8, cursor: 'wait' } };
    $('body').on('submit', '#csr_remaining_total_supply_setting_frm', function(){
		$form = $(this);
		if( parseInt( $form.find('#csr_remaining_total_supply').val() ) <= 0 ){
			swalToast({ type: 'error', title: 'Please enter CSR remaining total supply' });
			return false;
		}
		var data = $(this).serialize();
		$form.block( blockConfigSetting );
		$.post(cipscript.ajax_url, data, function(response) {
			var obj = JSON.parse( response );
			$form.unblock();
			if( obj.error == 0 ){
				swalToast({ type: 'success', title: obj.msg });
			}else{
				swalToast({ type: 'error', title: obj.msg });
			}
            $('#update_csr_remaining_btn_modal').modal('hide');
            location.reload();
		});
		return false;
	});
    $('#csr_remaining_total_supply_setting_frm input[name="csr_remaining_total_supply"]').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('input', '.AddCsrRemainingAddressForm input[name="wallet_address"], .AddCsrRemainingAddressForm input[name="description"], .EditCsrRemainingAddressForm input[name="wallet_address"], .EditCsrRemainingAddressForm input[name="description"]', function(){
		var c = this.selectionStart,
          r = /[^a-z0-9-_(). ]/gi,
		  v = $(this).val();
		if( r.test(v) ){
		  $(this).val(v.replace(r, ""));
		  c--;
		}
		this.setSelectionRange(c, c);
	});

    if( $('#sa_csr_remaining_address_list').length > 0 ){
        var sa_csr_remaining_address_list_url = "<?php echo $sa_csr_remaining_address_list_url ?>";
        var $tableCSRRemainingAddressList = $('#sa_csr_remaining_address_list');
        $tableCSRRemainingAddressList.bootstrapTable({
            method: 'post',
            contentType: 'application/x-www-form-urlencoded',
            url: sa_csr_remaining_address_list_url,
            queryParams: function (p) {
                return {
                    columnfilter: p.filter,
                    limit: p.limit,
                    offset: p.offset,
                    sort: p.sort,
                    order: p.order,
                };
            },
            stickyHeader: false,
            onPostBody: function (){
                $('.filter-control input.search-input').prop('readonly',false);
            },
            onSearch: function( search ){
                $('.filter-control input.search-input').prop('readonly',true);
            },
            toolbar: '#csr_remaining_custom_toolbar'
        });

        $('body').on('submit', '#AddCsrRemainingAddressForm', function(){
            $form = $(this);
            var wallet_address = $(this).find('input[name=wallet_address]').val();
            var description = $(this).find('input[name=description]').val();
            var user_ga_otp = $(this).find('input[name=user_ga_otp]').val();
            
            if( wallet_address == "" ){
                swalToast({ type: 'error', title: 'Please enter wallet address' });
                return false;
            }
            if( !web3.utils.isAddress( wallet_address ) ){
                swalToast({ type: 'error', title: 'Please enter valid wallet address' });
                return false;
            }
            if( description == "" ){
                swalToast({ type: 'error', title: 'Please enter description' });
                return false;
            }
            if( user_ga_otp == "" ){
                swalToast({ type: 'error', title: 'Please enter authentication code' });
                return false;
            }

            var data = $(this).serialize();
            $form.block( blockConfigSetting );
            $.post(cipscript.ajax_url, data, function(response) {
                var obj = JSON.parse( response );
                if( obj.error == 0 ){
                    swalToast({ type: 'success', title: obj.msg });
                    $('#add_csr_remaining_address_btn_modal').modal('hide');
                    $('#AddCsrRemainingAddressForm')[0].reset();
                    $tableCSRRemainingAddressList.bootstrapTable('refresh');
                }else{
                    swalToast({ type: 'error', title: obj.msg });
                }
                $form.unblock();
            });
            return false;
        });

        $('body').on('click', '#refresh_csr_remaining_btn', function(){
            var data = {'action' : 'refresh_csr_remaining_data', 'micro' : $(this).attr('data-micro')};
            Swal({
                title: 'Are you sure?',
                text: "Do you want to refresh CSR remaining data?",
                type: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes'
            }).then((result) => {
                if (result.value) {
                    $.blockUI( blockConfigSetting );
                    jQuery.ajax({ 
                        type: "post",
                        data: data,
                        cache: false,
                        url: cipscript.ajax_url,
                        success: function(response){
                            var obj = JSON.parse( response );
                            if( obj.error == 0 ){
                                swalToast({ type: 'success', title: obj.msg });
                            }else{
                                swalToast({ type: 'error', title: obj.msg });
                            }
                            $.unblockUI();
                        }
                    });
                }
            });
            return false;
        });
        
        $('body').on('click', '.editCsrRemainingWalletAddressBtn', function(e){
            var thisId = $(this).attr('data-edit');
            var micro = $(this).attr('data-micro');
            var data = { 'action' : 'get_csr_remaining_address_action', 'thisId' : thisId, '_micro' : micro };
            var thisTr = $(this).closest('tr');
            thisTr.block( blockConfigSetting );
            $.post(cipscript.ajax_url, data, function(response) {
                var obj = JSON.parse( response );
                if( obj.error == 0 ){
                    $('#edit_csr_remaining_address_btn_modal .modal-edit-response').html( obj.html );
                    $('#edit_csr_remaining_address_btn_modal').modal('show');
                }else{
                    swalToast({ type: 'error', title: obj.msg });
                }
                thisTr.unblock();
            });
        });

        $('#edit_csr_remaining_address_btn_modal').on('hide.bs.modal', function (event) {
            var modal = $(this);
            modal.find('.modal-edit-response').html('');
        });

        $('body').on('submit', '#EditCsrRemainingAddressForm', function(){
            $form = $(this);
            var wallet_address = $(this).find('input[name=wallet_address]').val();
            var description = $(this).find('input[name=description]').val();
            var user_ga_otp = $(this).find('input[name=user_ga_otp]').val();
            
            if( wallet_address == "" ){
                swalToast({ type: 'error', title: 'Please enter wallet address' });
                return false;
            }
            if( !web3.utils.isAddress( wallet_address ) ){
                swalToast({ type: 'error', title: 'Please enter valid wallet address' });
                return false;
            }
            if( description == "" ){
                swalToast({ type: 'error', title: 'Please enter description' });
                return false;
            }
            if( user_ga_otp == "" ){
                swalToast({ type: 'error', title: 'Please enter authentication code' });
                return false;
            }

            var data = $(this).serialize();
            $form.block( blockConfigSetting );
            $.post(cipscript.ajax_url, data, function(response) {
                var obj = JSON.parse( response );
                if( obj.error == 0 ){
                    swalToast({ type: 'success', title: obj.msg });
                    $('#edit_csr_remaining_address_btn_modal').modal('hide');
                    $tableCSRRemainingAddressList.bootstrapTable('refresh');
                }else{
                    swalToast({ type: 'error', title: obj.msg });
                }
                $form.unblock();
            });
            return false;
        });

        $('body').on('click', '.deleteCsrRemainingAddressBtn', function(e){
            var thisId = $(this).attr('data-delete');
            var micro = $(this).attr('data-micro');
            var thisTr = $(this).closest('tr');
            
            Swal({
                title: 'Are you sure?',
                text: "Do you want to remove address?",
                type: 'warning',
                showCancelButton: true,
                confirmButtonText: 'Yes'
            }).then((result) => {
                if (result.value) {
                    var data = { 'action' : 'delete_csr_remaining_address_action', 'thisId' : thisId, '_micro' : micro };
                    thisTr.block( blockConfigSetting );
                    $.post(cipscript.ajax_url, data, function(response) {
                        var obj = JSON.parse( response );
                        if( obj.error == 0 ){
                            swalToast({ type: 'success', title: obj.msg });
                            $tableCSRRemainingAddressList.bootstrapTable('refresh');
                        }else{
                            swalToast({ type: 'error', title: obj.msg });
                        }
                        thisTr.unblock();
                    });
                }
            });

        });
    }
});</script><?php
}
add_action( 'wp_ajax_csr_remaining_total_supply_setting_act', 'cip_csr_remaining_total_supply_setting_act_callback' );
function cip_csr_remaining_total_supply_setting_act_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	if( wp_verify_nonce( $_POST['_micro'],'_ZyxcsrRemainingTotalSupplyxyZ_' ) && (current_user_can( 'supportmanager' ) || current_user_can( 'supportagent' )) ){
		$current_user = wp_get_current_user();
		$csr_remaining_total_supply = ( is_numeric(	$_POST['csr_remaining_total_supply']) && $_POST['csr_remaining_total_supply'] > 0 ) ? $_POST['csr_remaining_total_supply'] : 0;
		$oldValue = ( !empty( get_option('csr_remaining_total_supply') ) ) ? get_option('csr_remaining_total_supply') : 0;
		$logs = sprintf( __('CSR remaining total supply update from %s to %s. by %s at %s.', CIP_TXTDOMAIN), $oldValue, $csr_remaining_total_supply, $current_user->user_email, date_i18n('d/m/Y H:i A') );
		create_cip_logs_entery( $current_user->ID, 'setting', '','sm', $logs, true );
		update_option( 'csr_remaining_total_supply', $csr_remaining_total_supply );
		$out = array( "error" => 0,'msg' => __('Saved',CIP_TXTDOMAIN) );
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_addNewCsrRemainingWalletAddressAct','cip_addNewCsrRemainingWalletAddressAct_callback');
function cip_addNewCsrRemainingWalletAddressAct_callback(){
	$out = array( "error" => 1, 'msg' => __('Something Went Wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableCsrRemainingAddress = $wpdb->prefix.'csr_remaining_address';

	$current_user = wp_get_current_user();
	$user_id = $current_user->ID;
	$user_email = $current_user->user_email;
	$username = $current_user->user_login;
	$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';

    $gaOTPValid = false;
    $google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
    if( !empty( $_POST['user_ga_otp'] ) ){
        $google2fa = new \PragmaRX\Google2FA\Google2FA();
        if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
            $gaOTPValid = true;
        }
    }
    if( $gaOTPValid === false ){
        $out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
        echo wp_json_encode( $out );
        exit;
    }

    $getAlreadyHave = $wpdb->get_row("SELECT `wallet_address` FROM $tableCsrRemainingAddress WHERE `wallet_address`='".$_POST['wallet_address']."' LIMIT 1");
    if( $getAlreadyHave ){
        $out = array( "error" => 1,'msg' => __('Wallet address already exists.',CIP_TXTDOMAIN) );
        echo wp_json_encode( $out );
        exit;
    }
	
	if( wp_verify_nonce( $_POST['_micro'], $refAccount ) ){
		if( !empty( $_POST['wallet_address'] ) && !empty( $_POST['description'] ) ){

            $csrAmount = cip_get_ether_balance( $_POST['wallet_address'], 'csr' );

            $csrAmount = floatval( bcadd($csrAmount, 0, 2) );

            $insertData = ['wallet_address' => $_POST['wallet_address'], 'description' => stripslashes( $_POST['description'] ), 'amount' => round( $csrAmount ), 'create_date' => date_i18n('Y-m-d H:i:s'), 'last_update' => date_i18n('Y-m-d H:i:s') ];
            $insert = $wpdb->insert( $tableCsrRemainingAddress, $insertData );
            if( $insert ){
                $logs = sprintf( __('Add CSR Remaining wallet address by %s at %s.
                Address: %s
                Description: %s
                Amount: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $_POST['wallet_address'], $_POST['description'], floatval( bcadd($csrAmount, 0, 2) ) );
                create_cip_logs_entery( $current_user->ID, 'csr_remaining_address', '','sa', $logs, true  );
                $out = array( "error" => 0, 'msg' => __('CSR Remaining Wallet Address added successfully', CIP_TXTDOMAIN) );
            }else{
                $out = array( "error" => 1,'msg' => __('Failed to add CSR Remaining Wallet Address',CIP_TXTDOMAIN) );
            }
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_sa_csr_remaining_address_list_loader','sa_csr_remaining_address_list_loader_cb');
function sa_csr_remaining_address_list_loader_cb(){
	global $wpdb;

	$tableCsrRemainingAddress = $wpdb->prefix.'csr_remaining_address';

	$limit = isset( $_POST['limit'] ) ? $_POST['limit'] : 10;
	$offset = isset( $_POST['offset'] ) ? $_POST['offset'] : 0;
	$orderby = isset( $_POST['sort'] ) ? $_POST['sort'] : 'id';
	$order = (isset($_POST['order']) && in_array($_POST['order'], array('asc', 'desc'))) ? $_POST['order'] : 'desc';

	$filter_qry = "";
	$filters = json_decode( stripslashes( $_REQUEST['columnfilter'] ), true );
	if( !empty( $filters ) ){
		foreach( $filters as $filterKey => $filterData ){
			if( $filterKey == 'wallet_address'  ){
				$filter_qry .= " AND `$filterKey` = '" . $filterData . "'";
			}else{
				$filter_qry .= " AND `$filterKey` like '%" . $filterData . "%'";
			}
		}
	}
    $total_items = $wpdb->get_var("SELECT COUNT(id) FROM $tableCsrRemainingAddress WHERE 1 $filter_qry");

	$getRecords = $wpdb->get_results( "SELECT * FROM $tableCsrRemainingAddress WHERE 1 $filter_qry ORDER BY `$orderby` $order LIMIT $limit OFFSET $offset" );

	$rows = array();
	if( $getRecords ){
		
        $sno= $_REQUEST['offset'] + 1;
		foreach( $getRecords as $getRecord ){

            $encryptId = base64_encode( $getRecord->id . md5('CIP_CSRRemainingEditAddress_CIP') );
            $data_micro = wp_create_nonce( $getRecord->id . md5('CIP_CSRRemainingEditAddress_CIP') );

			$row = array(
				'id' => $sno,
				'wallet_address' => '<div class="eth_address"><a href="javascript:void(0);">' . $getRecord->wallet_address . '</a></div>',
				'amount' => number_format( $getRecord->amount ),
				'description' => $getRecord->description,
				'action' => '<div class="d-flex justify-content-around"><a href="javascript:void(0);" class="editCsrRemainingWalletAddressBtn" data-edit="'. $encryptId .'" data-micro="'.$data_micro.'" class="mr-1" ><i class="fa fa-edit"></i></a><a href="javascript:void(0);" class="deleteCsrRemainingAddressBtn" data-delete="'. $encryptId .'" data-micro="'.$data_micro.'"><i class=" fa fa-trash"></i></a></div>'
			);

			$rows[] = $row;
            $sno=$sno+1;
		}
	}
	$out = array(
		'total'		=>	$total_items,
		'rows'		=>	$rows
	);
	echo wp_json_encode( $out );
	exit;
}
add_action('wp_ajax_refresh_csr_remaining_data', 'refresh_csr_remaining_data_callback');
function refresh_csr_remaining_data_callback(){
    global $wpdb;
	$tableCsrRemainingAddress = $wpdb->prefix.'csr_remaining_address';

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

	$current_user = wp_get_current_user();
	$user_id = $current_user->ID;
	$user_email = $current_user->user_email;
	$username = $current_user->user_login;
	$refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';

    if( wp_verify_nonce( $_POST['micro'], $user_email ) && ( current_user_can('supportmanager') || current_user_can('supportagent') ) ){

        $wpdb->query( $wpdb->prepare( "UPDATE $tableCsrRemainingAddress SET `updated` = %d", 0 ) );

        $url = site_url() . '/wp-admin/admin-ajax.php?action=refresh_csr_remaining_data_background_process';
        $cmd = "curl -s $url > /dev/null 2>&1 &";
        exec($cmd, $output, $return_var);

        $logFile = CIP_PLUGIN_BASE.'/'.'task_log.log';
        file_put_contents($logFile, "CSR Remaining refreshing background process triggered: Return code $return_var at " . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
        $out = array( "error" => 0,'msg' => __('Refreshing started in background',CIP_TXTDOMAIN) );
    }
    echo wp_json_encode( $out );
    exit;
}
/**
 * Cron to refresh csr remaining address amount
 */
add_action('wp_ajax_refresh_cron_csr_remaining_data','cip_refresh_cron_csr_remaining_data_cb');
add_action('wp_ajax_nopriv_refresh_cron_csr_remaining_data','cip_refresh_cron_csr_remaining_data_cb');
function cip_refresh_cron_csr_remaining_data_cb(){
	$out = array( "error" => 1, 'msg' => __('Something went wrong.', CIP_TXTDOMAIN) );
	global $wpdb;
	$tableCsrRemainingAddress = $wpdb->prefix.'csr_remaining_address';

	if( isset( $_GET['cronmicro'] ) && str_rot13( $_REQUEST['cronmicro'] ) === 'CIPCsrRemainingAddressCIP'  ){ //PVCPfeErznvavatNqqerffPVC
        $wpdb->query( $wpdb->prepare( "UPDATE $tableCsrRemainingAddress SET `updated` = %d", 0 ) );

        $url = site_url() . '/wp-admin/admin-ajax.php?action=refresh_csr_remaining_data_background_process';
        $cmd = "curl -s $url > /dev/null 2>&1 &";
        exec($cmd, $output, $return_var);

        $logFile = CIP_PLUGIN_BASE.'/'.'task_log.log';
        file_put_contents($logFile, "CSR Remaining refreshing background process triggered from cron job at " . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
        $out = array( "error" => 0,'msg' => __('Refreshing started in background',CIP_TXTDOMAIN) );
    }
    exit;
}
add_action('refresh_csr_remaining_data_from_retirement_confirm', 'refresh_csr_remaining_data_from_retirement_confirm_callback');
function refresh_csr_remaining_data_from_retirement_confirm_callback( $args ){
    global $wpdb;
	$tableCsrRemainingAddress = $wpdb->prefix.'csr_remaining_address';

    if( $args == 'retirement_confirm' ){

        $wpdb->query( $wpdb->prepare( "UPDATE $tableCsrRemainingAddress SET `updated` = %d", 0 ) );

        $url = site_url() . '/wp-admin/admin-ajax.php?action=refresh_csr_remaining_data_background_process';
        $cmd = "curl -s $url > /dev/null 2>&1 &";
        exec($cmd, $output, $return_var);

        $logFile = CIP_PLUGIN_BASE.'/'.'task_log.log';
        file_put_contents($logFile, "CSR Remaining refreshing background process triggered from retirement confirm at " . date('Y-m-d H:i:s') . "\n", FILE_APPEND);
    }
}
add_action('wp_ajax_refresh_csr_remaining_data_background_process', 'refresh_csr_remaining_data_background_process_callback');
add_action('wp_ajax_nopriv_refresh_csr_remaining_data_background_process', 'refresh_csr_remaining_data_background_process_callback');
function refresh_csr_remaining_data_background_process_callback(){
    global $wpdb;
	$tableCsrRemainingAddress = $wpdb->prefix.'csr_remaining_address';

    $getRecords = $wpdb->get_results("SELECT * FROM $tableCsrRemainingAddress WHERE `updated`=0");
    
    $logFile = CIP_PLUGIN_BASE.'/'.'task_log.log';
    file_put_contents($logFile, "CSR Remaining refreshing task started at " . date('Y-m-d H:i:s') . "\n", FILE_APPEND);

    if( $getRecords ){
        foreach( $getRecords as $getRecord ){

            $csrAmount = cip_get_ether_balance( $getRecord->wallet_address, 'csr' );

            $csrAmount = floatval( bcadd($csrAmount, 0, 2) );

            $updatedata = ['amount' => round( $csrAmount ), 'updated' => 1, 'last_update' => date_i18n('Y-m-d H:i:s')];
            $where_data = ['id' => $getRecord->id];
            $wpdb->update( $tableCsrRemainingAddress, $updatedata, $where_data );

            if( $csrAmount <= 0 ){
                $logs = sprintf( __('CSR Remaining wallet address updated with %s amount at %s.
                Address: %s
                Old Amount: %s', CIP_TXTDOMAIN), $csrAmount, date_i18n('d/m/Y H:i A'), $getRecord->wallet_address, $getRecord->amount );
                create_cip_logs_entery( $current_user->ID, 'csr_remaining_address', '','sa', $logs, true  );
            }

            file_put_contents($logFile, "Updated record ID: $getRecord->wallet_address => $csrAmount at " . date_i18n('Y-m-d H:i:s') . " \n", FILE_APPEND);
            sleep(1);
        }
    }
    echo 1;
    exit;
}
add_action( 'wp_ajax_get_csr_remaining_address_action', 'cip_get_csr_remaining_address_action_callback' );
function cip_get_csr_remaining_address_action_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportagent' ) ){
		global $wpdb;
		$tableCsrRemainingAddress = $wpdb->prefix.'csr_remaining_address';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
        $refAccount = ( isset( $_SESSION['refAccount'] ) && $_SESSION['refAccount'] != "" ) ? $_SESSION['refAccount'] : '-';
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$address_id = preg_replace(sprintf('/%s/', md5('CIP_CSRRemainingEditAddress_CIP') ), '', $decryptedId_raw);
		$tableTokenHolder = $wpdb->prefix.'token_holder';
		
		if( wp_verify_nonce( $_POST['_micro'], $address_id . md5('CIP_CSRRemainingEditAddress_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableCsrRemainingAddress WHERE 1 AND id = ".$address_id."");
			if( $getData ){
				ob_start();
				?>
                <form id="EditCsrRemainingAddressForm" class="EditCsrRemainingAddressForm">
                    <div class="modal-body">
                        <div class="form-group">
                            <label for="wallet_address">Wallet Address</label>
                            <input type="text" name="wallet_address" id="wallet_address" class="form-control" value="<?php echo $getData->wallet_address; ?>" placeholder="Enter Wallet Address">
                        </div>
                        <div class="form-group">
                            <label for="description">Description</label>
                            <input type="text" name="description" id="description" class="form-control" value="<?php echo $getData->description; ?>" placeholder="Enter description">
                        </div>
                        <div class="form-group">
                            <label for="user_ga_otp"><?php echo __('Authentication code', CIP_TXTDOMAIN); ?></label>
                            <input type="text" name="user_ga_otp" id="user_ga_otp" class="form-control mb-1" maxlength="6" pattern="{0-9}+" placeholder="Enter authentication code" />
                            <small class="form-text text-muted"><?php _e('Enter the 6-digit code generated by the Authenticator App.') ?></small>
                        </div>
                    </div>
                    <input type="hidden" name="action" value="EditNewCsrRemainingWalletAddressAct" />
                    <input type="hidden" name="wa_id" value="<?php echo $_POST['thisId']; ?>" />
					<input type="hidden" name="_micro" value="<?php echo $_POST['_micro']; ?>" />

                    <div class="modal-footer justify-content-start">
                        <button type="submit" class="btn btn-primary">Edit</button>
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                    </div>
                </form>
				<?php
				$html = ob_get_clean();
				$out = array( "error" => 0,'msg' => __('Success',CIP_TXTDOMAIN), 'html' => $html );
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_EditNewCsrRemainingWalletAddressAct', 'cip_EditNewCsrRemainingWalletAddressAct_callback' );
function cip_EditNewCsrRemainingWalletAddressAct_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportagent' ) || current_user_can( 'supportmanager' ) ){
		global $wpdb;
		$tableCsrRemainingAddress = $wpdb->prefix.'csr_remaining_address';

		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$decryptedId_raw = base64_decode( $_POST['wa_id'] );
		$address_id = preg_replace(sprintf('/%s/', md5('CIP_CSRRemainingEditAddress_CIP') ), '', $decryptedId_raw);

        $gaOTPValid = false;
        $google_auth_key = get_user_meta( $user_id, 'google_auth_key', true );
        if( !empty( $_POST['user_ga_otp'] ) ){
            $google2fa = new \PragmaRX\Google2FA\Google2FA();
            if( $google2fa->verifyKey($google_auth_key, $_POST['user_ga_otp'], 0) ){
                $gaOTPValid = true;
            }
        }
        if( $gaOTPValid === false ){
            $out = array( "error" => 1,'msg' => __('Invalid authenticator code',CIP_TXTDOMAIN) );
            echo wp_json_encode( $out );
            exit;
        }

        $getAlreadyHave = $wpdb->get_row("SELECT `wallet_address` FROM $tableCsrRemainingAddress WHERE id != ".$address_id." AND `wallet_address`='".$_POST['wallet_address']."' LIMIT 1");
        if( $getAlreadyHave ){
            $out = array( "error" => 1,'msg' => __('Wallet address already exists.',CIP_TXTDOMAIN) );
            echo wp_json_encode( $out );
            exit;
        }

		if( wp_verify_nonce( $_POST['_micro'], $address_id . md5('CIP_CSRRemainingEditAddress_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableCsrRemainingAddress WHERE 1 AND id = ".$address_id."");
			if( $getData ){
                if( !empty( $_POST['wallet_address'] ) && !empty( $_POST['description'] ) ){

                    $csrAmount = cip_get_ether_balance( $_POST['wallet_address'], 'csr' );

                    $csrAmount = floatval( bcadd($csrAmount, 0, 2) );
        
                    $updateData = ['wallet_address' => $_POST['wallet_address'], 'description' => stripslashes( $_POST['description'] ), 'amount' => round( $csrAmount ), 'last_update' => date_i18n('Y-m-d H:i:s') ];
                    $whereData = ['id' => $getData->id];
                    $update = $wpdb->update( $tableCsrRemainingAddress, $updateData, $whereData );
                    if( $update ){
                        $logs = sprintf( __('Edit CSR Remaining wallet address by %s at %s.
                        Address: from %s to %s
                        Description: from %s to %s
                        Amount: from %s to %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $getData->wallet_address, $_POST['wallet_address'], $getData->description, $_POST['description'], $getData->amount, floatval( bcadd($csrAmount, 0, 2) ) );
                        create_cip_logs_entery( $current_user->ID, 'csr_remaining_address', '','sa', $logs, true  );
                        $out = array( "error" => 0, 'msg' => __('CSR Remaining Wallet Address updated successfully', CIP_TXTDOMAIN) );
                    }else{
                        $out = array( "error" => 1,'msg' => __('Failed to update CSR Remaining Wallet Address',CIP_TXTDOMAIN) );
                    }
                }
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_action( 'wp_ajax_delete_csr_remaining_address_action', 'cip_delete_csr_remaining_address_callback' );
function cip_delete_csr_remaining_address_callback(){
	$out = array( "error" => 1,'msg' => __('Something went wrong.',CIP_TXTDOMAIN) );
	$html = "";
	if( current_user_can( 'supportagent' ) || current_user_can( 'supportmanager' ) ){
		global $wpdb;
		$tableCsrRemainingAddress = $wpdb->prefix.'csr_remaining_address';
		$current_user = wp_get_current_user();
		$user_id = $current_user->ID;
		$decryptedId_raw = base64_decode( $_POST['thisId'] );
		$id = preg_replace(sprintf('/%s/', md5('CIP_CSRRemainingEditAddress_CIP') ), '', $decryptedId_raw);
		if( wp_verify_nonce( $_POST['_micro'], $id . md5('CIP_CSRRemainingEditAddress_CIP') ) ){
			$getData = $wpdb->get_row("SELECT * FROM $tableCsrRemainingAddress WHERE 1 AND id = ".$id."");
			if( $getData ){
				$deleting = $wpdb->delete( $tableCsrRemainingAddress, ['id' => $id] );
				if( $deleting ){
					$logs = sprintf( __('CSR Remaining address deleted by %s at %s. Address: %s', CIP_TXTDOMAIN), $current_user->user_email, date_i18n('d/m/Y H:i A'), $getData->wallet_address );
					create_cip_logs_entery( $user_id, 'csr_remaining_address', '','sa', $logs, true );
					$out = array( "error" => 0,'msg' => __('CSR Remaining Address deleted',CIP_TXTDOMAIN));
				}else{
					$out = array( "error" => 1,'msg' => __('CSR Remaining Address failed to delete',CIP_TXTDOMAIN));
				}
				
			}
		}
	}
	echo wp_json_encode( $out );
	exit;
}
add_shortcode('CSRRemain', 'display_csr_remain');
function display_csr_remain(){
    global $wpdb;
    $tableCsrRemainingAddress = $wpdb->prefix.'csr_remaining_address';
    $csr_remaining_total_supply = ( !empty( get_option('csr_remaining_total_supply') ) ) ? get_option('csr_remaining_total_supply') : 0;
    $getTotalRemainingAddress = $wpdb->get_row("SELECT COALESCE(SUM(`amount`),0) as `totalAmount` FROM $tableCsrRemainingAddress WHERE 1");

    $csrRemainAmount = 0;
    try {
        $csrRemainAmount = $csr_remaining_total_supply - $getTotalRemainingAddress->totalAmount;
    } catch (\Throwable $th) {
        $csrRemainAmount = 0;
    }

    return number_format( $csrRemainAmount );
}
