<?php if ($music->config->stripe_payment == 'on') { ?>
<script src="https://checkout.stripe.com/checkout.js"></script>
<?php } ?>
<div class="ma_page_content" id="container_blog">

	<div class="ma_pc_inner">
		<div class="page_padding">
			<?php $loadPage = loadPage('thirdparty/paypal-demo'); echo (!empty($loadPage)) ? $loadPage : '';?>
			<div class="ma_tabs">
				<ul class="list-unstyled mb-0">
					<li class="active">
						<a href="{{LINK ads}}" data-load="ads">{{LANG Advertising}}</a>
					</li>
					<li>
						<a href="javascript:void(0);" onclick="ReplenishWallet();">{{LANG Wallet}} ({{CURRENCY}}{{ME wallet}})</a>
					</li>
					<li>
						<a href="{{LINK create-ads}}" data-load="create-ads">{{LANG Create ad}}</a>
					</li>
				</ul>
			</div>
			<div class="content">
				<table class="table" id="music-user-ads-table">
					<thead>
						<th>{{LANG Status}}</th>
						<th>{{LANG Name}}</th>
						<th>{{LANG Results}}</th>
						<th>{{LANG Spent}}</th>
						<th>{{LANG Action}}</th>
					</thead>
					<tbody>{{ADS_LIST}}</tbody>
				</table>
			</div>
		</div>
	</div>
</div>
<div class="payment_method"></div>

<script>
	function purchaseWalletStripe(element,price) {
		var title = '{{LANG Replenish My Balance}}';

		getText = element.text();
		element.attr('disabled', 'true');
		element.text("{{LANG Please wait..}}");

		var fd = new FormData();
		fd.append('description', title);
		fd.append('price', price);
		fd.append('payType', 'wallet');
		fd.append('trackID', '');
		fd.append('hash_id', $('.main_session').val() );

		fetch('{{CONFIG ajax_url}}/new-stripe-wallet', {
			method: 'POST',
			body : fd
		}).then(function(response) {
			return response.json();
		}).then(function(session) {
			var stripe = Stripe('{{CONFIG stripe_id}}');
			return stripe.redirectToCheckout({ sessionId: session.id });
		}).then(function(result) {
			// If redirectToCheckout fails due to a browser or network
			// error, you should display the localized error message to your
			// customer using error.message.
			if (result.error) {
				alert(result.error.message);
			}
		})
		.catch(function(error) {
			console.error('Error:', error);
		});
	}
    var Delay = (function(){
        var timer = 0;
        return function(callback, ms){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
        };
    })();
	$(document).ready( function () {
	    $('#music-user-ads-table').DataTable();
		$('#music-user-ads-table').on( 'page.dt', function () {
		    Delay(function(){
		    	$('#music-user-ads-table').find('[type="checkbox"]').each(function(index, el) {
			    	$(el).bootstrapToggle();
			    });
		    },50)
		});
	});

	var amount;

    function ShowMethods(type,price = 0,user_id = 0) {
        $.post('{{CONFIG ajax_url}}/wallet/get_modal',{type:type,price:price,user_id:user_id}, function(data, textStatus, xhr) {
            if (data.status == 200) {
                $('.payment_method').html(data.html);
                $('#wallet_payment_modal').modal({
                    show: true
                });
            }
        });
    }

	function ReplenishWallet() {
		swal({
		  html:$('.replenish-wallet-form').clone().addClass('clone').removeClass('hidden'),
		  showCloseButton: true,
		  showCancelButton: false,
		  focusConfirm: false,
		  confirmButtonText:"{{LANG replenish}}",
		  cancelButtonText:"{{LANG cancel}}",
		  buttonsStyling:false,
		  confirmButtonClass:'btn btn-primary btn-mat',
		  cancelButtonClass:"btn btn-default pull-left",
		  allowOutsideClick:false,
		  showLoaderOnConfirm: true,
		  preConfirm: function () {
		    return new Promise(function (resolve, reject) {
		    	amount = $(".replenish-wallet-form.clone").find('input').val();
		    	if (!amount || amount < 1){
		    		reject("{{LANG Please check the details}}!");
		    	}
		    	else{
		    		$('#wallet_amount').val(amount);
		    		swal.close();
		    		ShowMethods('wallet',amount);
		    	}
		    })
		  }
		}).then(function(){/*pass*/},function(){/*pass*/});
	}

	function DeleteAd(id){
		if (!id) {
			return false;
		}
		swal({
		  title: '{{LANG Confirmation}}',
		  text: "{{LANG Are you sure you want to delete this ad?}}",
		  type: 'warning',
		  showCloseButton: true,
		  showCancelButton: false,
		  focusConfirm: false,
		  confirmButtonText:"{{LANG Delete}}!",
		  cancelButtonText:"{{LANG Cancel}}",
		  buttonsStyling:false,
		  confirmButtonClass:'btn btn-primary btn-mat',
		  cancelButtonClass:"btn btn-default",
		  allowOutsideClick:false,
		}).then(function (){
			$.post('{{CONFIG ajax_url}}/ads/delete', {id:id}, function(data, textStatus, xhr) {/* pass */});
			$("tr[data-ads-list='"+id+"']").slideUp(function(){
				$(this).remove();
				swal({
					title:'{{LANG campaign_deleted_succ}}',
				    type:'success',
				    buttonsStyling:false,
				    confirmButtonClass:'btn btn-success',
				});
                setTimeout(function () {
                    goToAjaxLink('ads');
                }, 1000);
			});
		});
	}

	function ToggleAdsStatus(id){
		if (!id) {
			return false;
		}
		$.post('{{CONFIG ajax_url}}/ads/toggle-stat', {id:id}, function(data, textStatus, xhr) {/* pass */});
	}

	function OpenStripe(pkg,self,video_id = 0,price = 0){
	    if (!pkg || !self) {
	      return false;
	    }
	    $(self).text("{{LANG please_wait}}").attr('disabled', 'true');
	    amount = $("#wallet_amount").val()+'00';
	    var handler = StripeCheckout.configure({
	        key: "<?php echo $music->config->stripe_secret;?>",
	        locale: 'english',
	        token: function(token) {
	          $('.modal-body').html('<i class="fa fa-spin fa-spinner"></i> {{LANG Confirming your payment, please wait..}}');
	          $.post('{{CONFIG ajax_url}}/wallet/stripe_replenish', {stripeToken:token.id, amount:amount}, function (data) {
	          	 if (data.status == 200) {
	          	 	window.location.href = data.url;
	          	 } else {
	          	 	$('.modal-body').html('<i class="fa fa-spin fa-spinner"></i> {{LANG Payment declined, please try again later.}}');
	          	 }
	          });
	        }
	    });

	    handler.open({
           name: "<?php echo $music->config->name?>",
           amount: amount,
           currency: '<?php echo $music->config->stripe_currency?>',
           opened: function () {
           	  $('#pay-go-pro').modal('hide');
           	  $('.btn-cart').attr('disabled', false).html("<i class='fa fa-credit-card'></i> {{LANG Credit Card}}");
           }
        });
	 }

	  $(document).on('click', '#select-img', function(event) {
		$("#thumbnail").click()
	});
	$(document).on('change', '#thumbnail', function(event) {
		let imgPath = $(this)[0].files[0].name;
	    if (typeof(FileReader) != "undefined") {
	        let reader = new FileReader();
	        reader.onload = function(e) {
				$('#receipt_img_preview').attr('src', e.target.result);
	        }
	        reader.readAsDataURL(this.files[0]);
	    }
		$('#bank_transfer_modal').addClass('up_rec_img_ready');
	});

	jQuery(document).ready(function($) {
		$('#bank_transfer_form').ajaxForm({
		  url: '{{CONFIG ajax_url}}/wallet/bank_replenish',
		  beforeSend: function() {
		    $('#bank_transfer_form').find('.ball-pulse').fadeIn(100);
		  },
		  success: function(data) {
		    if (data['status'] == 200) {
		    	$("#blog-alert").html('<div class="alert alert-success">'+ data['message'] +'</div>');
		    	setTimeout(function () {
		    		window.location = "<?php echo $music->config->site_url;?>";
		    		$(".prv-img").html('<div class="thumbnail-rendderer"><div><div class="error-text-renderer"></div><div><p>{{LINK Browse To Upload}}</p></div></div> </div>');
		    		$("#blog-alert").html('');
		    		$('#configreset').click();

		    	},3000)
		    } else if (data['message']) {
		      $("#blog-alert").html('<div class="alert alert-danger">' + data['message'] + '</div>');
		    } 
		    $('#bank_transfer_form').find('.ball-pulse').fadeOut(100);
		}});
	});

	 function OpenBank(pkg,self,video_id = 0,price = 0){
	    if (!pkg || !self) {
	      return false;
	    }
	    amount = $("#wallet_amount").val()+'00';
	    $('#bank_transfer_amount').val(amount)
	    $(self).text("{{LANG please_wait}}").attr('disabled', 'true');
	    $('#pay-go-pro').modal('hide');
	    $('#configreset').click();
		$("#blog-alert").html('');
    	$('#pay-go-pro').modal('hide');
    	$('#bank_transfer_modal').modal({
             show: true
		});
	}

</script>
<form class="replenish-wallet-form hidden">
	<div class="modal-title">
		<h5>{{LANG MY BALANCE}} {{CURRENCY}}{{ME wallet}}</h5>
	</div>
	<div class="form-group mat_input">
		<label>{{LANG Replenish My Balance}}</label>
		<input type="number" class="form-control" placeholder="{{LANG Amount}}">
	</div>
</form>