function populateTable() {
	let date  		= new Date($('#dateNow').val());
    let startDay 	= new Date(date.getFullYear(), date.getMonth(), 1);
    let lastDay 	= new Date(date.getFullYear(), date.getMonth()+ 1, 0);
   	let days 		= lastDay.getDate();

    $('#days').html('')
    $('.data-grid').html('')

    let thurs   = [];
    let frid    = [];

    for(let i = 1; i <= days  ; i++) {
        let elClass = '';
        let newDate = new Date(date.getFullYear(), date.getMonth(), i)
        if(newDate.getDay() == 4) thurs.push(i)
        if(newDate.getDay() == 5) frid.push(i)

        if(thurs.includes(i)) elClass += ' weekend';
        if(frid.includes(i)) elClass += ' weekend';

        let daysNumbers = `<div class="col center ${elClass} bl">${i}</div>`;
        let dataCols = `<div class="col col-${i} bb center ${elClass} bl"><span></span></div>`;

        $('.data-grid').append(dataCols)


        $('#days').append(daysNumbers)

        // This only works the first time

        // window.addEventListener('load', () => {
        // 	$('.data-grid').append(dataCols)
        // })
    }
}
function scheduler() {
    let date    = new Date();
    let year    = date.getFullYear();
    let month   = date.getMonth() + 1;
    let day     = date.getDay();

    let startDay = new Date(date.getFullYear(), date.getMonth(), 1);
    let lastDay = new Date(date.getFullYear(), date.getMonth()+ 1, 0);

    let monthName = date.toLocaleString('default', {month: 'long'});
    let monthNameShort = date.toLocaleString('default', {month: 'short'});

    let currentMonthTop = `${startDay.getDate()} ${monthNameShort} - ${lastDay.getDate()} ${monthNameShort}`;
    let currentMonth = `${monthName} ${year}`;

    $('.currentMonthTop').html(currentMonthTop)
    $('.currentMonth').html(currentMonth)

    // Populate inner table with number of days head and table cols
    // dataTable(lastDay.getDate(), date)

    $('#dateNow').val(date)
}
function nextMonth() {
    let date  = new Date($('#dateNow').val());
    let newDate = new Date(date.getFullYear(), date.getMonth() +1, 1)
    let year    = newDate.getFullYear();

    let startDay 	= new Date(newDate.getFullYear(), newDate.getMonth(), 1);
    let lastDay 	= new Date(newDate.getFullYear(), newDate.getMonth()+ 1, 0);

    let monthName 	= newDate.toLocaleString('default', {month: 'long'});
    let monthNameShort = newDate.toLocaleString('default', {month: 'short'});

    let currentMonthTop = `${startDay.getDate()} ${monthNameShort} - ${lastDay.getDate()} ${monthNameShort}`;
    let currentMonth 	= `${monthName} ${year}`;

    $('.currentMonthTop').html(currentMonthTop)
    $('.currentMonth').html(currentMonth)

    $('#dateNow').val(newDate)
    getData4Scheduler()
}
function prevMonth() {
    let date  = new Date($('#dateNow').val());
    date = new Date(date.getFullYear(), date.getMonth())
    let newDate = new Date(date.getFullYear(), date.getMonth() -1, 1)

    let year    = newDate.getFullYear();

    let startDay = new Date(newDate.getFullYear(), newDate.getMonth(), 1);
    let lastDay = new Date(newDate.getFullYear(), newDate.getMonth()+ 1, 0);

    let monthName = newDate.toLocaleString('default', {month: 'long'});
    let monthNameShort = newDate.toLocaleString('default', {month: 'short'});

    let currentMonthTop = `${startDay.getDate()} ${monthNameShort} - ${lastDay.getDate()} ${monthNameShort}`;
    let currentMonth = `${monthName} ${year}`;

    $('.currentMonthTop').html(currentMonthTop)
    $('.currentMonth').html(currentMonth)

    $('#dateNow').val(newDate)
    getData4Scheduler()
}
function getData4Scheduler() {
	let date  = new Date($('#dateNow').val());
    let newDate = new Date(date.getFullYear(), date.getMonth() +1, 1)
	let monthDate = `${newDate.getFullYear()}-${newDate.getMonth()}`
	let room_filter  = $('#room_filter').val();
	let data =  {date:monthDate, room_filter:room_filter}
	$.ajax({
		type: "POST",
		url: "./includes/reception.php?action=get_recInfo&dest=getData4Scheduler",
		data: data,
		cache: false,
		success: function(result) {
			// console.log(result)
			let res = JSON.parse(result);
			// console.log(res.records)
			records = res.records
			$('.records.data-grid-records').html(res.rows)

			populateTable()
			setRecordsStatus(records)
		},
	});
}
function setRecordsStatus(records) {
	console.log(records)
	records.map((record) => {
		let recRow = record.row;
		let href = `./reservation-workplace.php?role=${myRole}&task=reservation&subtask=showInfo&recID=${record.checkInID}`
		let recordHTML = `<a target="_blank" href="${href}" style="display:block" data-startday="${record.startDay}" data-endday="${record.endDay}" data-lastdayofmonth="${record.lastDayOfMonth}" data-pricetype="${record.priceType}" data-starthpoint="${record.startHPoint}" data-diff="${record.diff}" class="${record.status}  record  status">
			<div class="room-info">
				<p>${record.clientName}</p>
				<p>${record.dates}</p>
				<p class="status">${record.status}</p>
			</div>
		</a>`;
		$(`.data-row.${recRow} .data-grid`).addClass('hasRecords')
		$(`.data-row.${recRow} .data-grid`).append(recordHTML)
	})

	recordsSet()
}
function recordsSet() {
	let width = 0;
    let rows = 0;
    $('.data-grid.hasRecords').each((i, el) => {
        $(el).find('.col').each((ind, col) => {
            width += $(col).width()
        })
        rows ++;
        let rowWidth = width/rows
        let records = $(el).find('.record.status')
        let x = 0;
        $(records).each((i, record) => {
        	if($(record) instanceof jQuery) {
        		let {startday, endday, lastdayofmonth, pricetype, diff, starthpoint} = $(record).data()
        		if(endday < startday) endday = lastdayofmonth;
        		// console.log(pricetype)
        		let startCol = $(el).find('.col-'+startday)
        		let endCol = $(el).find('.col-'+endday)
        		if($(startCol)[0] != undefined) {
        			let startColWidth 	= $(startCol)[0].getBoundingClientRect()['width']
        			let endColWidth 	= $(endCol)[0].getBoundingClientRect()['width']
        			let recordWith 		= endColWidth * (1+ endday-startday) ;
        			let left 			= $(startCol)[0].offsetLeft + 0;

                    if(pricetype == 'hour') {
                        recordWith = (recordWith/24)*diff;
                        left = left + starthpoint;
                    }

                    $(record).css('left', left)
        			$(record).css('width', recordWith)
        		}
        	}
        })
    })
}
