$(function(){
	if ($('.custom-access-block .user-product-block').length) {
		let productInfo = {
			'3844032': ['Курс "Дизайн с нуля"', '/fileservice/file/download/a/531225/sc/15/h/7e4c771362c8810a5a9f551b493963f3.png', 'block', 'https://talentsy.getcourse.ru/teach/control/stream/index'],
            '3847088': ['Курс "Дизайн с нуля 2.0"', '/fileservice/file/download/a/531225/sc/15/h/7e4c771362c8810a5a9f551b493963f3.png', 'none', 'https://talentsy.getcourse.ru/teach/control/stream/index'],
		}
		
	    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,""))
			}
		})
		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' : '';
				    					$('.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' : '';
										$('.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').click()
        					})
        				} else {
	        				$('.custom-access-wrapper').eq(i).find('button').click(function(q){
								q.preventDefault()
				    			$(e).find('.prolong-link button').click()
	        				})
        				}
        				clearInterval(prolongInter)
        			}
				},100)
			} 
        })
    } else {
    	$('.custom-access-block').hide()
    }
});

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];
};