var _calendar = document.querySelector(".s-calendar");
var _title = document.querySelector(".s-title");
var _daysContainer = document.querySelector(".s-days");
var _prev = document.querySelector(".s-prev");
var _next = document.querySelector(".s-next");
var _todayBtn = document.querySelector(".s-today-btn");
var _gotoLastEventBtn = document.querySelector(".s-goto-last-event");
var _gotoBtn = document.querySelector(".s-goto-btn");
var _dateInput = document.querySelector(".s-date-input");
var _eventDay = document.querySelector(".s-event-day");
var _eventDate = document.querySelector(".s-event-date");
var _eventsContainer = document.querySelector(".s-events");
var _totalEventThisMonth = document.querySelector(".s-event-this-month");
var _totalEventThisDay = document.querySelector(".s-event-this-day");
var _weekDays = document.querySelector(".s-weekdays");

var _today = new Date();
var _activeDay;
var _date = _today.getDate();
var _month = _today.getMonth();
var _year = _today.getFullYear();
var _lastEventDate = null;

var _monthsNameFull = [
    "January",
    "February",
    "March",
    "April",
    "May",
    "June",
    "July",
    "August",
    "September",
    "October",
    "November",
    "December"
];

var _monthsNameShort = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
];

var _daysNameFull = [
    "Sunday",
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday"
]

var _daysNameShort = [
    "Sun",
    "Mon",
    "Tue",
    "Wed",
    "Thu",
    "Fri",
    "Sat"
]

var _eventsArr = [];

$.ajax({
    type: "post",
    url: "calendar/calDb.php",
    data: {},
    success: function (sData) {
        var data = JSON.parse(sData);

        data.forEach(item => {
            // var eventDateParts = item['Event_Date'].split('-');
            var eventDateParts = new Date(item['event_date_time']);
            //var eventDateParts = new Date('2025-01-07 14:23:45');
            // var day = parseInt(eventDateParts[0]);
            // var month = monthsNameShort.indexOf(eventDateParts[1]) + 1;
            // var year = parseInt(eventDateParts[2]);
            var day = eventDateParts.getDate();
            var month = eventDateParts.getMonth() + 1;
            var year = eventDateParts.getFullYear();

            _eventsArr.push({
                day: day,
                month: month,
                year: year,
                events: [
                    {
                        id: item['id'],
                        groom: item['groom'],
                        bride: item['bride'],
                        phone: item['phone'],
                        eventType: item['event_type'],
                        packageTypd: item['package_type'].substring(0, item['package_type'].length - 2),
                        packageAmt: item['package_amount'],
                        location: item['location'],
                        eventTime: sTime(item['event_date_time'])
                    }
                ]
            });

            // Short by id (asc = a-b, desc = b-a)
            _eventsArr.sort((a, b) => a.events[0].id - b.events[0].id);

            // last event date
            // 
            // event date
            var eventDate = new Date(year, month - 1, day); // Month is 0-based in JavaScript

            // Compare eventDate with the current lastEventDate
            if (_lastEventDate == null || eventDate > _lastEventDate) {
                _lastEventDate = eventDate;
            }
        });

        sCalendar();

    },
    error: function (xhr, textStatus, errorThrown) {
        console.error('Error fetching data:', errorThrown);
    }
});

function sCalendar() {
    var firstDay = new Date(_year, _month, 1); // current month first date
    var lastDay = new Date(_year, _month + 1, 0); // current month last date
    var lastDate = lastDay.getDate(); // current month last day
    var prevLastDay = new Date(_year, _month, 0); // previous month last date
    var prevDays = prevLastDay.getDate(); // previous month last day
    var day = firstDay.getDay(); // previous month total days in current month
    var nextDays = 42 - (day + lastDate); // next month total days in current month
    // var nextDays = 7 - lastDay.getDay() - 1; // next month total days in current month

    var totalEventMonth = 0;

    _title.innerHTML = _monthsNameFull[_month] + " " + _year;

    // Week Days
    var daysName = "";
    for (var d = 0; d < 7; d++) {
        daysName += `<div>` + _daysNameShort[d] + `</div>`;
    }
    _weekDays.innerHTML = daysName;

    var days = "";

    // previous month days
    for (var s = day; s > 0; s--) {
        days += `<div class="s-day s-prev-date">${prevDays - s + 1}</div>`;
    }

    //current month days
    for (var s = 1; s <= lastDate; s++) {

        // check if event present on current day
        var event = false;
        _eventsArr.forEach((eventObj) => {
            if (eventObj.day == s && eventObj.month == _month + 1 && eventObj.year == _year) {
                event = true;
                totalEventMonth += 1;
            }
        });

        // if day is today
        if (s === new Date().getDate() && _year === new Date().getFullYear() && _month === new Date().getMonth()) {

            _activeDay = s;
            getActiveDay(s);
            eventListOnDate(s);

            if (event) {
                days += `<div class="s-day s-today s-active s-event">${s}</div>`;
            }
            else {
                days += `<div class="s-day s-today s-active">${s}</div>`;
            }
        }
        else {
            if (event) {
                if (s === _date) {
                    days += `<div class="s-day s-active s-event">${s}</div>`;
                } else {
                    days += `<div class="s-day s-event">${s}</div>`;
                }
            }
            else {
                if (s === _date) {
                    days += `<div class="s-day s-active">${s}</div>`;
                } else {
                    days += `<div class="s-day">${s}</div>`;
                }
            }

            getActiveDay(_date);
            eventListOnDate(_date);
        }
    }

    for (var s = 1; s <= nextDays; s++) {
        days += `<div class="s-day s-next-date">${s}</div>`;
    }

    _daysContainer.innerHTML = days;
    _totalEventThisMonth.innerHTML = "This month: " + totalEventMonth + " events";
    addListenre();
}

// previous month
_prev.addEventListener("click", () => {
    _date = 1;
    _month--;
    if (_month < 0) {
        _month = 11;
        _year--;
    }
    sCalendar();
});

// next month
_next.addEventListener("click", () => {
    _date = 1;
    _month++;
    if (_month > 11) {
        _month = 0;
        _year++;
    }
    sCalendar();
});

// Today
_todayBtn.addEventListener("click", () => {
    _date = _today.getDate();
    _month = _today.getMonth();
    _year = _today.getFullYear();
    sCalendar();
});

// goto last event date
_gotoLastEventBtn.addEventListener("click", () => {
    _date = _lastEventDate.getDate();
    _month = _lastEventDate.getMonth();
    _year = _lastEventDate.getFullYear();
    sCalendar();
});

_dateInput.addEventListener("input", function (e) {
    // input only number
    _dateInput.value = _dateInput.value.replace(/[^0-9]/g, "");
    if (_dateInput.value.length > 6) {
        _dateInput.value = _dateInput.value.slice(0, 6);
    }
});

_gotoBtn.addEventListener("click", () => {
    gotoDate();
});

_dateInput.addEventListener("keydown", function (event) {
    if (event.key === "Enter") {
        gotoDate();
    }
});

function gotoDate() {
    var inputDate = _dateInput.value;
    var baseYear = 2000;
    var searchDay = 1;
    var searchMonth = 1;
    var searchYear = baseYear;
    const daysInMonth = {
        1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30,
        7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31
    };

    if (inputDate.length === 6) {
        // ddmmyy format
        searchDay = inputDate.slice(0, 2); // First 2 characters for day
        searchMonth = inputDate.slice(2, 4); // Next 2 characters for month
        searchYear = inputDate.slice(4, 6); // Last 2 characters for year
    } else if (inputDate.length === 4) {
        // mmyy format
        searchMonth = inputDate.slice(0, 2); // First 2 characters for month
        searchYear = inputDate.slice(2, 4); // Last 2 characters for year
    } else {
        alert("Invalid date format. Please use ddmmyy or mmyy.");
    }

    if (searchDay >= 1 && searchDay <= 31 && searchMonth >= 1 && searchMonth <= 12 && searchYear.length === 2) {
        if (Number(searchMonth) === 2 && ((Number(baseYear) + Number(searchYear)) % 4 === 0)) {
            daysInMonth[2] = 29;  // February in a leap year has 29 days
        }
    } else {
        alert("Invalid date. Please check the format and values.");
    }
    
    if (searchDay < 1 || searchDay > daysInMonth[Number(searchMonth)]) {
        alert("Invalid day for the given month");
    } else {
        _date = Number(searchDay);
        _month = Number(searchMonth) - 1; // Adjust month to 0-based index
        _year = baseYear + Number(searchYear);
        sCalendar();
    }
}

// create function to add listener on days after rendered
function addListenre() {
    var days = document.querySelectorAll(".s-day");
    days.forEach((day) => {
        day.addEventListener("click", (e) => {

            if (!e.target.classList.contains("s-prev-date") && !e.target.classList.contains("s-next-date")) {

                _activeDay = Number(e.target.innerHTML);

                days.forEach((day) => {
                    day.classList.remove("s-active");
                });

                e.target.classList.add("s-active");
                getActiveDay(e.target.innerHTML);
                eventListOnDate(Number(e.target.innerHTML));
            }

        });
    });
}

// active day event
function getActiveDay(_date) {
    var day = new Date(_year, _month, _date);
    var dayName = day.toString().split(" ")[0];
    var fullName = _daysNameFull[_daysNameShort.indexOf(dayName)];
    _eventDay.innerHTML = fullName;
    _eventDate.innerHTML = _date + " " + _monthsNameFull[_month] + " " + _year;
}

// show event to the day
function eventListOnDate(_date) {

    var eventEx = false;
    var totalEventDay = 0;
    var events = `<div class="table-responsive">
    <table class="table table_sm table-bordered table-dark">
    <thead style="color:var(--s-text-color)">
        <th style="width: 5px;">ID</th>
        <th style="width: 150px;">Groom & Bride</th>
        <th style="width: 50px;">Contact</th>
        <th style="width: 50px;">Event Type</th>
        <th style="width: 150px;">Package</th>
        <th style="width: 50px;">Amount</th>
        <th>Location</th>
        <th style="width: 90px;">Event Time</th>
        <th style="width: 5px;">ASN</th>
    </thead>
    <tbody style="color: #e5e5e5;">`;
    var eventTable2 = `</tbody></table></div>`;

    _eventsArr.forEach((event) => {

        if (_date == event.day && _month + 1 == event.month && _year == event.year) {
            event.events.forEach((event) => {
                eventEx = true;
                var phone = (event.phone.length == 14) ? event.phone.substring(3) : event.phone;
                var updateBtn = Permission() ? '<button type="button" class="btn btn-sm action-btn" onclick="UpdateModal(' + event.id + ')"><i class="bi bi-pencil-fill"></i></button>' : '';
                var eventTable1 = `<tr>
                <td>${event.id}</td>
                <td>${event.groom} & ${event.bride}</td>
                <td>${phone}</td>
                <td>${event.eventType}</td>
                <td>${event.packageTypd}</td>
                <td>${event.packageAmt}</td>
                <td>${event.location}</td>
                <td>${event.eventTime}</td>
                <td>
                    <div class="btn-group">
                        <button type="button" class="btn btn-sm action-btn" onclick="AssignModal(${event.id})"><i class="bi bi-pin-angle-fill"></i></button>
                        ${updateBtn}
                    </div>
                </td>
                </tr>`;
                events += eventTable1;
                totalEventDay += 1;
            });
        }
    });

    events += eventTable2;
    if (eventEx === false) {
        events = `<div class="s-no-event">
                <h3>No Events</h3>
            </div>`;
    }

    if (_eventsContainer) {
        _eventsContainer.innerHTML = events;
    }

    _totalEventThisDay.innerHTML = "This day: " + totalEventDay + " events";
}

sCalendar();