$(function(){
	if ($('.custom-access-block .user-product-block').length) {
		let productInfo = {
			'4175364': ['Сладкий бабулех', '/fileservice/file/download/a/790870/sc/140/h/2ac0f983b2d4a8c02e4fa5536c943912.jpg', 'block', ''],
			'639665': ['Дуй Амстериксм', '/fileservice/file/download/a/790870/sc/341/h/c0ac8922cac3fcc77726c1ece66f7d17.jfif', 'none', '']
		}
        //'айди_продукта_по_которому_отслеживать' : ['Заголовок_блока', 'Ссылка_из_файлового_хранилища_на_изображение', 'видимость_кнопки', 'кастомная_ссылка_на_кнопку']
		
	    const months = {
	    	'Янв':'01 января',
	    	'Фев':'02 февраля',
	    	'Мар':'03 марта',
	    	'Апр':'04 апреля',
	    	'Май':'05 мая',
	    	'Июн':'06 июня',
	    	'Июл':'07 июля',
	    	'Авг':'08 августа',
	    	'Сен':'09 сентября',
	    	'Окт':'10 октября',
	    	'Ноя':'11 ноября',
	    	'Дек':'12 декабря'
	    };
		
		let productIdArr = [];
		
		
		
		$('.custom-access-block .xdget-productTiming').each(function(){
			if ($(this).find('.user-product-block').length) {
				productIdArr.push($(this).find('.user-product-block').attr('id').replace(/\D+/g,""))
                $('.custom-access-block').show()
			}
		})
		console.log(productIdArr)
    	let productId = $('.custom-access-block .user-product-block').attr('id').replace(/\D+/g,"");
	    $.get("/sales/control/userProduct/my", function(data) {
	    	$('.table-notitle tbody tr', data).each(function(q,r){
	    		let salesProductId = $(this).find('a').attr('href').replace(/\D+/g,"");
	    		productIdArr.forEach(function(e){
		    		if (e == salesProductId) {
		    			let startDay = $(r).find('td:nth-child(2)').text().split(' ')[1];
		    			let startMonth = $(r).find('td:nth-child(2)').text().split(' ')[2];
		    			let startYear = $(r).find('td:nth-child(2)').text().split(' ')[3];
		    			let endDay = $(r).find('td:nth-child(2)').text().split(' ')[5];
		    			let endMonth = $(r).find('td:nth-child(2)').text().split(' ')[6];
		    			let endYear = $(r).find('td:nth-child(2)').text().split(' ')[7];
		    			let startDate = new Date(months[startMonth].replace(/[^0-9]/g, '') + '/' + startDay + '/' + startYear);
		    			console.log(startDate)
		    			let endDate = new Date(months[endMonth].replace(/[^0-9]/g, '') + '/' + endDay + '/' + endYear);
		    			let totalDays = Math.ceil((endDate.getTime() - startDate.getTime()) / (1000 * 3600 *24));
		    			let currentDate = new Date();
		    			let restDays = Math.ceil((endDate.getTime() - currentDate.getTime()) / (1000 * 3600 *24));
		    			console.log(restDays)
		                if (restDays > 0) {
		                	Object.keys(productInfo).forEach(function(t,u){
								if ($(`.custom-access-block .user-product-block[id*="${e}"]`).parent().hasClass(t)) {
									if (productIdArr.length > 1) {
										let wrapperStyle = restDays <= 5 ? 'red-style' : '';
										//let renewalLink = Object.values(productInfo)[u][3].length > 1 ? '' : 'hide';
				    					$('.custom-access-block').append(`
						               		<div class="custom-access-wrapper ${wrapperStyle}">
						               			<img src="${Object.values(productInfo)[u][1]}">
						               			<div>
						               				<h3>${Object.values(productInfo)[u][0]}</h3>
						               				<span>Заканчивается через ${restDays} ${declOfNum(restDays, ['день', 'дня', 'дней'])}</span>
						               				<button class="custom-access-btn" style="display:${Object.values(productInfo)[u][2]}" onclick="window.open('${Object.values(productInfo)[u][3]}', '_blank')">Продлить доступ</button>
						               			</div>
						               		</div>
						               	`)
									} else {
										let fewDays = restDays <= 5 ? `<span>Доступ закончится через ${restDays} ${declOfNum(restDays, ['день', 'дня', 'дней'])},<br> не забудьте оплатить продление</span>` : '';
										let wrapperStyle = restDays <= 5 ? 'red-style' : '';
										let renewalLink = Object.values(productInfo)[u][3].length > 1 ? '' : 'hide';
										$('.custom-access-block').append(`
					                		<div class="custom-access-wrapper single-block ${wrapperStyle}">
					                			<img src="${Object.values(productInfo)[u][1]}">
					                			<div>
					                				<h3>${Object.values(productInfo)[u][0]}</h3>
					                				<span>До ${endDay} ${months[endMonth].replace(/[0-9]/g, '')} ${endYear}</span>
					                				<span>Заканчивается через ${restDays} ${declOfNum(restDays, ['день', 'дня', 'дней'])}</span>
					                			</div>
					                		</div>
											<button class="custom-access-btn" style="display:${Object.values(productInfo)[u][2]}" onclick="window.open('${Object.values(productInfo)[u][3]}', '_blank')">Продлить доступ</button>
					                		${fewDays}
					                	`)
									}
								}
							})
		                } else {
		                	Object.keys(productInfo).forEach(function(t,u){
								if ($(`.custom-access-block .user-product-block[id*="${e}"]`).parent().hasClass(t)) {
									if (productIdArr.length > 1) {
				    					$('.custom-access-block').append(`
						               		<div class="custom-access-wrapper access-expired">
						               			<img src="${Object.values(productInfo)[u][1]}">
						               			<div>
						               				<h3>${Object.values(productInfo)[u][0]}</h3>
						               				<span>Доступ закончился</span>
						               				<button class="custom-access-btn" style="display:${Object.values(productInfo)[u][2]}" onclick="window.open('${Object.values(productInfo)[u][3]}', '_blank')">Продлить доступ</button>
						               			</div>
						               		</div>
						               	`)
									} else {
										$('.custom-access-block').append(`
					                		<div class="custom-access-wrapper single-block access-expired">
					                			<img src="${Object.values(productInfo)[u][1]}">
					                			<div>
					                				<h3>${Object.values(productInfo)[u][0]}</h3>
					                				<span>Доступ закончился</span>
					                			</div>
					                		</div>
					                		<button class="custom-access-btn" style="display:${Object.values(productInfo)[u][2]}" onclick="window.open('${Object.values(productInfo)[u][3]}', '_blank')">Продлить доступ</button>
					                	`)
									}
								}
							})
		                }
		    		};
	    		})
	    	});
		});
        $('.custom-access-block .user-product-block').each(function(i,e){
        	if ($(e).find('.prolong-offers').length) {
        		let prolongInter = setInterval(function(){
        			if ($('.custom-access-wrapper').eq(i).length) {
        				if ($('.custom-access-wrapper').eq(i).hasClass('single-block')) {
        					$('.custom-access-wrapper').eq(i).siblings('button').click(function(q){
								q.preventDefault()
				    			$(e).find('.prolong-offers button').removeAttr('onclick').click()
        					})
        				} else {
                        console.log('qq')
	        				$('.custom-access-wrapper').eq(i).find('button').removeAttr('onclick').click(function(q){
                        console.log('qqq')
								q.preventDefault()
				    			$(e).find('.prolong-offers button').click()
	        				})
        				}
        				clearInterval(prolongInter)
        			}
				},100)
			} 
        })
	}
});

function declOfNum(n, text_forms) {
	n = Math.abs(n) % 100; 
	var n1 = n % 10;
	if (n > 10 && n < 20) { return text_forms[2]; }
	if (n1 > 1 && n1 < 5) { return text_forms[1]; }
	if (n1 == 1) { return text_forms[0]; }
	return text_forms[2];
};