<!DOCTYPE html>
<html lang="en">
<head>
	<!-- Main navbar -->
		<?php $this->load->view('admin/common_header'); ?>
	<!-- /main navbar -->

	<!-- select box theme JS files -->
	<script type="text/javascript" src="<?php echo base_url();?>assets/js/plugins/forms/selects/bootstrap_select.min.js"></script>

	<!-- Theme JS files -->
	<script type="text/javascript" src="<?php echo base_url();?>assets/js/plugins/tables/datatables/datatables.min.js"></script>
	<script type="text/javascript" src="<?php echo base_url();?>assets/js/plugins/tables/datatables/extensions/responsive.min.js"></script>
	<script type="text/javascript" src="<?php echo base_url();?>assets/js/plugins/forms/selects/select2.min.js"></script>

	<script type="text/javascript" src="<?php echo base_url();?>assets/js/core/app.js"></script>
	<script type="text/javascript" src="<?php echo base_url();?>assets/js/pages/datatables_responsive.js"></script>
	<!-- /theme JS files -->

	<!-- notify JS files -->
    <script type="text/javascript" src="<?php echo base_url();?>assets/js/plugins/notifications/jgrowl.min.js"></script>

    <!-- Theme JS files -->
	<script type="text/javascript" src="<?php echo base_url();?>assets/js/plugins/notifications/bootbox.min.js"></script>
	<script type="text/javascript" src="<?php echo base_url();?>assets/js/plugins/notifications/sweet_alert.min.js"></script>

	<script type="text/javascript" src="<?php echo base_url();?>styles/web3/bignumber.min.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>styles/web3/dist/web3-light.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>styles/web3/dist/web3.js"></script>
<script type="text/javascript" src="<?php echo base_url();?>styles/web3/buffer.js"></script>
<script src="https://cdn.rawgit.com/ethereumjs/browser-builds/2fb69a714afe092b06645286f14b94f41e5c062c/dist/ethereumjs-tx.js"></script>
    
    <style type="text/css">
	    .icons-list a[data-action="reload1"]:after {
		  content: '\e9fb';
		}
		.btns {
			padding: 5px;
		}
	</style>
</head>

<body class="navbar-top-md-md pace-done">

	<!-- Fixed navbars wrapper -->
	<div class="navbar-fixed-top">

		<!-- Main navbar -->
		<?php $this->load->view('admin/mainnav'); ?>
		<!-- /main navbar -->


		<!-- Second navbar -->
		<?php $this->load->view('admin/secondnav'); ?>
		<!-- /second navbar -->

	</div>
	<!-- /fixed navbars wrapper -->


	<!-- Page header -->
	<?php $this->load->view('admin/'.$module_name.'_header'); ?>
	<!-- /page header -->


	<!-- Page container -->
	<div class="page-container">

		<!-- Page content -->
		<div class="page-content">

			<!-- Main content -->
			<div class="content-wrapper">
				
				<form method="post" id="pending_withdraw" action="<?php echo $action;?>">
					<!-- Basic responsive configuration -->
					<div class="panel panel-flat">
					
						<div class="panel-heading">
							<div class="col-md-11">
								<h5 class=""><?php echo $page_title; ?></h5>
							</div>
							<div style="clear:both;"><Br></div>


							<div id="data_load" style="color:red;" align="center"></div>

							<div class="log"></div>

							<!-- <div class="col-md-2">
								<div class="heading-elements">
									<ul class="icons-list">
										
				                		<li><a data-action="collapse"></a></li>
				                		<li><a data-action="reload"></a></li>
				                		<li><a data-action="close"></a></li>
				                	</ul>
			                	</div>
			                </div> -->

						</div>
						<?php $currency_info = defaultcurrency();?>
						
						
						<table class="table datatable-responsive-withdraw table-hover">
							<col width="1%">
							<col width="10%">
							<col width="1%">
	  						<col width="20%">
	  						<col width="15%" style="display:none;">
	  						<col width="15%" style="display:none;">
	  						<col width="15%" style="display:none;">
	  						<col width="1%">
	  						<col width="25%">

	  						<col width="15%" style="display:none;">
	  						<col width="10%">
							<thead>
								<tr>
									<th></th>
									<th class=""><?php echo $this->lang->line('label_payaddress');?></th>
									<th></th>
									<th class=""><?php echo $this->lang->line('label_payaddr_name');?></th>
									<th class=""><?php echo $this->lang->line('lbl_user_name');?></th>
									<th class="" style="display:none;"><?php echo $this->lang->line('menu_bank_name');?></th>
									<th class="" style="display:none;"><?php echo $this->lang->line('menu_bank_account');?></th>
									<th class="" style="display:none;"><?php echo $this->lang->line('menu_bank_swift');?></th>
									<th></th>
									<th class=""><?php echo $this->lang->line('lbl_amount');?></th>
									<th class="" style="display:none;"><?php echo $this->lang->line('lbl_payment_gateway');?></th>
									<th class=""><?php echo $this->lang->line('lbl_options');?></th>
								</tr>
							</thead>
							<tbody>
							<?php 
								if($history) {
									
									$row_count = count($history);
									$this->load->library('MyEncrypt');
									$myencrypt = new MyEncrypt;
									foreach ($history as $row) {

										$coinid=$row->coin_id;
										
										$userid=$row->uuserid;
										$condition = "coid ='".$coinid."'";
										$cointable = $this->common_model->GetRow('coin_info',$condition);
										$pay_mode=$cointable->pay_mode;

										$condition1 = "uusersid ='".$userid."'";
										$usertable = $this->common_model->GetRow('uusers',$condition1);
										$username=$usertable->username;
										if($username=='')
												$username='--';

										
										

										if($pay_mode=='1')
										{
											$symbol=strtolower($cointable->coin_symbol);
											$data="https://live.blockcypher.com/".$symbol."/address/".$row->btc_address;
										}	
										else
										{
											$data="https://etherscan.io/address/".$row->btc_address;
										}

										$pay_status=$cointable->pay_status;
										
										$condition = "payment_id ='".$payment_id."'";
										$payments = $this->common_model->GetResults("payment_controls",$condition);
										foreach ($payments as $payments)
										{
											$form_data[$payments->payment_key] = $payments->payment_value;
										}
										$private=$row->private_key;

										$public=$row->public_key;
										$to=$row->btc_address;
										
										$from=$row->payment_value;
										
										$condition = "payment_key in('status') AND payment_id = '".$payment_id."'";
										$payment = $this->finance_model->PaymentName($condition);
										$payment_name=$payment->payment_name;
										
										

										$currency=$row->currency;

										$find_name=$this->db->query("select * from coin_info where coid='$currency'");
										$det=$find_name->result();

										if($row->bank_name=='')
											$bank_name='---';
										else
											$bank_name=$row->bank_name;

										if($row->account_number=='')
											$account_number='---';
										else
											$account_number=$row->account_number;

										if($row->swift_code=='')
											$swift_code='---';
										else
											$swift_code=$row->swift_code;

										$amount1=$row->amount*100000000;

								?>
								<tr>
									<td></td>
								    <td class=""><a href="<?php echo $data;?>"><?php echo $row->btc_address;?></a></td>
								    <td></td>
									<td class=""><?php echo strtoupper($cointable->coin_symbol);?></td>
									<td class=""><?php echo ucfirst($username);?></td>
									<td class="" style="display:none;"><?php echo ucfirst($bank_name);?></td>
									<td class="" style="display:none;"><?php echo ucfirst($account_number);?></td>
									<td class="" style="display:none;"><?php echo ucfirst($swift_code);?></td>
									<td></td>
									<td class=""><?php echo number_format($row->amount, $det[0]->coin_decimal, '.', '').' '.strtoupper($det[0]->coin_symbol);?></td>
									<td class="" style="display:none;"><?php echo ucfirst($payment_name);?></td>
									<td class="text-center">

										<?php
	                                	if($row->balance > 0)
	                                	{

	                                			if($pay_status=='1')
	                                			{
	                                		?>
	                                			<a class="btns" data-popup="tooltip" title="<?php echo $this->lang->line('lbl_approve_withdraw');?>"  href="javascript:void(0)" onClick="payouts1('<?php echo $myencrypt->encode($row->id);?>','<?php echo $private;?>','<?php echo $public?>','<?php echo $from?>','<?php echo $to;?>','<?php echo $amount;?>','<?php echo $payment_id?>')" ><i class="fa fa-thumbs-up"></i></a>

	                                		<?php
	                                			}
	                                			else
	                                			{
	                                			?>
	                                				<a class="btns" data-popup="tooltip" title="<?php echo $this->lang->line('lbl_approve_withdraw');?>"  href="javascript:void(0)" onClick="payouts2('<?php echo $myencrypt->encode($row->id);?>','<?php echo trim($private);?>','<?php echo trim($from);?>','<?php echo trim($to);?>','<?php echo trim($cointable->contract);?>','<?php echo $row->amount;?>')" ><i class="fa fa-thumbs-up"></i></a>

	                                			<?php
	                                			}

	                                		}

	                                	?>
	                                	
	                                </td>
								</tr>
							<?php 

									}
								}  else { 

							?>
								<?php } ?>
							</tbody>
						</table>
					
					</div>
				</form>
				

			</div>
			<!-- /main content -->

		</div>
		<!-- /page content -->


		<!-- Footer -->
		<div class="footer text-muted">
			<?php echo site_footer();?>
		</div>
		<!-- /footer -->

	</div>
	<!-- /page container -->

	<script type="text/javascript">
		
	(function($) {

	    $(document).ready(function() {

	    	$('.datatable-responsive-withdraw').DataTable({
		        responsive: {
		            details: {
		                type: 'column',
		                target: 'tr'
		            }
		        },
		        columnDefs: [
		            {
		                className: 'control',
		                orderable: false,
		                targets:   0
		            },
		            { 
		                width: "100px",
		                targets: [8]
		            },
		            { 
		                orderable: false,
		                targets: [8]
		            },
		            { 
		                orderable: false,
		                targets: [1]
		            }
		        ],
		        order: [2, 'asc']

		    });

	    	$.jGrowl.defaults.closer = false;


	    	<?php if($this->session->flashdata('error_message')) { ?>
				$.jGrowl("<?php echo $this->session->flashdata('error_message');?>", {
		            header: '<?php echo $this->lang->line("error");?>',
		            theme: 'bg-danger'
		        });
            <?php } ?>
                    
            <?php if($this->session->flashdata('success_message')) { ?>
                $.jGrowl("<?php echo $this->session->flashdata('success_message');?>", {
		            header: '<?php echo $this->lang->line("success");?>',
		            theme: 'bg-success'
		        });
            <?php } ?>

				

	            $('#icon-bck').on('click',function() {
					window.history.back();
				});

				$('#checkall').on('click', function() {
					if($('#checkall').prop('checked'))
						$(':checkbox').prop('checked', true);
					else
						$(':checkbox').prop('checked', false);
				})

				$('.panel [data-action=reload1]').click(function (e) {
			        e.preventDefault();
			        var block = $(this).parent().parent().parent().parent().parent();
			        jQuery.ajax({
			            url:'<?php echo base_url();?>admin/finance/pendingwithdraw',
			            beforeSend: function() {
				            $(block).block({ 
					            message: '<i class="icon-spinner2 spinner"></i>',
					            overlayCSS: {
					                backgroundColor: '#fff',
					                opacity: 0.8,
					                cursor: 'wait',
					                'box-shadow': '0 0 0 1px #ddd'
					            },
					            css: {
					                border: 0,
					                padding: 0,
					                backgroundColor: 'none'
					            }
					        });
					        $('.panel .panel-heading').find('.dataTables_wrapper').remove();
					        
					        $('#DataTables_Table_0_wrapper').remove();
				        },
				        complete: function() {
				            $(block).unblock();
				        },
			            success : function(resp)
			            {
			            	$('.panel .panel-heading').after(resp);
			            	location.reload();
			            }
			        });
			        
			    });
			    
		});

	})(jQuery);

	function PaySelected() {

	    if(jQuery('.case:checked').length) {
	    	jQuery.ajax({
	            type: 'post',
	            url : '<?php echo base_url();?>admin/masspayout/pendingwithdraw',
	            // data : jQuery('#pending_withdraw').serialize(),
	            data : jQuery('input[type=\'checkbox\']'),

	            beforeSend: function(){

	            	jQuery('.panel').block({ 
			            message: '<i class="icon-spinner2 spinner"></i>',
			            overlayCSS: {
			                backgroundColor: '#fff',
			                opacity: 0.8,
			                cursor: 'wait',
			                'box-shadow': '0 0 0 1px #ddd'
			            },
			            css: {
			                border: 0,
			                padding: 0,
			                backgroundColor: 'none'
			            }
			        });
				    
			   	},
	            success : function(resp)
	            {
	                if(resp) {

	                	console.log(resp);
	                	console.log({elapsed_time});
	                }
	            },
	            complete: function(){
			    	jQuery('.panel').unblock();
			   	}
	        }); 
	    } else {
	    	console.log('no box checked');
	    }
	}

	function payouts(id) {

		
				jQuery.ajax({
		            type: 'post',
		            url : '<?php echo base_url();?>admin/masspayout/singleuserpay',
		            data : {'id':id},

		            beforeSend: function(){

		            	jQuery('.panel').block({ 
				            message: '<i class="icon-spinner2 spinner"></i>',
				            overlayCSS: {
				                backgroundColor: '#fff',
				                opacity: 0.8,
				                cursor: 'wait',
				                'box-shadow': '0 0 0 1px #ddd'
				            },
				            css: {
				                border: 0,
				                padding: 0,
				                backgroundColor: 'none'
				            }
				        });
					    
				   	},
		            success : function(resp)
		            {

		               if(resp) {

		                	console.log(resp);
		                	console.log({elapsed_time});
		                	location.reload();
		                }
		            },
		            complete: function(){
				    	jQuery('.panel').unblock();
				   	}
		        });
		    // }
      //   });
	}

	function payouts1(id,private1,public1,from,to,amount,payment) 
	{
		$("#data_load").html("Please Wait Payment Processing.......");
		var hash="";
		var bitcoin = require("bitcoinjs-lib");
		var bigi    = require("bigi");
		var buffer    = require("buffer");
		var payment=payment;

		if(payment=='1')
			var rootUrl = "https://api.blockcypher.com/v1/btc/main";
		else if(payment=='2')
			var rootUrl = "https://api.blockcypher.com/v1/eth/main";
		else if(payment=='3')
			var rootUrl = "https://api.blockcypher.com/v1/ltc/main";
		else if(payment=='4')
			var rootUrl = "https://api.blockcypher.com/v1/dash/main";
		else if(payment=='5')
			var rootUrl = "https://api.blockcypher.com/v1/dash/main";
		else
			var rootUrl = "https://api.blockcypher.com/v1/btc/test3";	

		var source = {
		  private : private1,
		  public  : public1,
		  address : from
		}
		var key   = new bitcoin.ECKey(bigi.fromHex(source.private), true);
		var dest  = null;
		var dest = {
		 
		  address : to
		}

		/*var source = {
  private : "1af97b1f428ac89b7d35323ea7a68aba8cad178a04eddbbf591f65671bae48a2",
  public  : "03bb318b00de944086fad67ab78a832eb1bf26916053ecd3b14a3f48f9fbe0821f",
  address : "mtWg6ccLiZWw2Et7E5UqmHsYgrAi5wqiov"
}
var key   = new bitcoin.ECKey(bigi.fromHex(source.private), true);
var dest  = null;

var dest = {
 
  address : "miw3uWxNS7AsxbzXV2R68EvUwTWqzieqnM"
}*/

		var newtx = {
    		"inputs": [{"addresses": [source.address]}],
    		"outputs": [{"addresses": [dest.address], "value": 25000}]
  		};
		
		function newTransaction() {
		  var newtx = {
		    "inputs": [{"addresses": [source.address]}],
		    "outputs": [{"addresses": [dest.address], "value": 25000}]
		  }
  		return $.post(rootUrl+"/txs/new", JSON.stringify(newtx));
		}

		function signAndSend(newtx) 
		{
  			if (checkError(newtx)) return;
			newtx.pubkeys     = [];
		  	newtx.signatures  = newtx.tosign.map(function(tosign) {
		  	

		    newtx.pubkeys.push(source.public);
		    return key.sign(new buffer.Buffer(tosign, "hex")).toDER().toString("hex");
  		});
  		return $.post(rootUrl+"/txs/send", JSON.stringify(newtx)).then(function(d) {

  			 hash=d.tx.hash;
			
  	$.ajax({
        url: "<?php echo base_url();?>admin/finance/deppayment",
        type: "post",
        data: {'id':id,'hash':hash} ,
        success: function (response) {
           // you will get response from your php page (what you echo or print)                 
          
    	console.log({elapsed_time});
    	location.reload();

        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        },
        complete: function(){
				    	jQuery('.panel').unblock();
				   	}


    });

  			
  			//console.log(d)
  		});
		}

		function checkError(msg) {
  if (msg.errors && msg.errors.length) {
    log("Errors occured!!/n" + msg.errors.join("/n"));

    return true;
  }
}

		// Chaining
		$.post(rootUrl+"/txs/new", JSON.stringify(newtx))
  		//.then(logAddr)
  		//.then(newTransaction)
  		.then(signAndSend)

  		//.done(function(data){alert('Done!'+data.tx.hash);})
   		.fail(function(errMsg) {
   				//alert('Failure!'+errMsg.responseText); console.log(errMsg);

   			document.getElementById('data_load').innerHTML=errMsg.responseText;

   	} );


  		
  		//.then(waitForConfirmation);
	}


	var isAddress = function (address) {
    // function isAddress(address) {
        if (!/^(0x)?[0-9a-f]{40}$/i.test(address)) {
        // check if it has the basic requirements of an address
        return false;
    } else if (/^(0x)?[0-9a-f]{40}$/.test(address) || /^(0x)?[0-9A-F]{40}$/.test(address)) {
        // If it's all small caps or all all caps, return "true
        return true;
    } else {
        // Otherwise check each case
        return isChecksumAddress(address);
    }
}


var isChecksumAddress = function (address) {
    // Check each case
    address = address.replace('0x','');
    var addressHash = web3.sha3(address.toLowerCase());
    for (var i = 0; i < 40; i++ ) {
        // the nth letter should be uppercase if the nth digit of casemap is 1
        if ((parseInt(addressHash[i], 16) > 7 && address[i].toUpperCase() !== address[i]) || (parseInt(addressHash[i], 16) <= 7 && address[i].toLowerCase() !== address[i])) {
            return false;
        }
    }
    return true;

}
	function payouts2(id,private_add,from_add,to_add,contract,amount) 
	{
		var web3 = new Web3();
    	web3.setProvider(new web3.providers.HttpProvider('https://api.myetherapi.com/eth'));
  		var abiArray=[{"constant":true,"inputs":[],"name":"name","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"}],"name":"approve","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"totalSupply","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transferFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"decimals","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_value","type":"uint256"}],"name":"burn","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"}],"name":"balanceOf","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_from","type":"address"},{"name":"_value","type":"uint256"}],"name":"burnFrom","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[],"name":"symbol","outputs":[{"name":"","type":"string"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"_to","type":"address"},{"name":"_value","type":"uint256"}],"name":"transfer","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":false,"inputs":[{"name":"_spender","type":"address"},{"name":"_value","type":"uint256"},{"name":"_extraData","type":"bytes"}],"name":"approveAndCall","outputs":[{"name":"success","type":"bool"}],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"address"},{"name":"","type":"address"}],"name":"allowance","outputs":[{"name":"","type":"uint256"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[],"payable":false,"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":true,"name":"to","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Transfer","type":"event"},{"anonymous":false,"inputs":[{"indexed":true,"name":"from","type":"address"},{"indexed":false,"name":"value","type":"uint256"}],"name":"Burn","type":"event"}];
		
		contractAddress = contract;
		var flag=0;

		if(isAddress(contractAddress))
		{
			flag=1;	
		}
		else{
		    document.getElementById('data_load').innerHTML="contract Address Invaild for this transaction...";
		}

		if(flag=='1')
		{
			contract = web3.eth.contract(abiArray).at(contractAddress);
			var count = web3.eth.getTransactionCount(from_add);
			if(count < 10)
	       	 count="0x0"+''+count;
		
			var amount=parseFloat(5*100);
	    	var limit='0x9493';
	     	var price='0x098bca5a00';
			var count=web3.toHex(count);
			
			rawTransaction = {
		    "from": from_add,
		    "nonce": count,
		    "gasPrice":price,
		    "gasLimit": limit,
		    "to": contractAddress,
		    "value": "0x0",
		    "data": contract.transfer.getData(to_add, amount, {from: from_add}),
		    "chainId": 0x03
			};
	    	let privateKey = new EthJS.Buffer.Buffer(private_add, 'hex')
			
			let tx = new EthJS.Tx(rawTransaction);
		    tx.sign(privateKey);
		    let serializedTx = tx.serialize().toString('hex')
		    web3.eth.sendRawTransaction('0x' + serializedTx.toString('hex'), function(err, hash) {
		    if (!err)
		    {
		        //document.getElementById('data_load').innerHTML=hash;

		        $.ajax({
			        url: "<?php echo base_url();?>admin/finance/deppayment",
			        type: "post",
			        data: {'id':id,'hash':hash} ,
			        success: function (response) {
			           // you will get response from your php page (what you echo or print)                 
			          
			    	console.log({elapsed_time});
			    	location.reload();

			        },
			        error: function(jqXHR, textStatus, errorThrown) {
			           console.log(textStatus, errorThrown);
			        },
			        complete: function(){
						jQuery('.panel').unblock();
					  }
				});
		    }
		    else
		    {
		    	console.log(err);
		    	document.getElementById('data_load').innerHTML=err;
		    }

			});
			document.getElementById('data_load').innerHTML="Pls Check Your console log..";
		}


		
	}


	function cancelpayouts(id) {

		swal({
            title: "<?php echo $this->lang->line('confirm_cancel_request_text');?>",
            showCancelButton: true,
            closeOnConfirm: false,
            confirmButtonColor: "#2196F3",
            cancelButtonColor: true,
            showLoaderOnConfirm: true
        },
        function(inputValue){
            if (inputValue === false) {
            	return false;
            } else {
            	window.location.href = "<?php echo base_url();?>admin/masspayout/Deleterequest/"+id;
            }
        });

	}
	
    
	
	</script>
<script src="https://cdn.rawgit.com/blockcypher/docs/master/bitcoinjs-min.js"></script>
</body>
</html>
