const dateFromInput = document.getElementById("date-from-input");
const dateToInput = document.getElementById("date-to-input");
const generateButton = document.getElementById("generate-button");
const sendByMailButton = document.getElementById("send-by-mail-button");
const dateToSpan = document.getElementById("date-to-span");
const dateFromSpan = document.getElementById("date-from-span");
const tbody = document.getElementById("tbody");

generateButton.addEventListener("click", () => {
    const dateFrom = new Date(dateFromInput.value);
    const dateTo = new Date(dateToInput.value);
    const reportModel = {
        "DateFrom": dateFrom,
        "DateTo": dateTo
    };
    $.ajax({
        url: "/home/getreport",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(reportModel)
    }).done((data) => {
        dateFromSpan.innerHTML = reportModel["DateFrom"].toLocaleDateString();
        dateToSpan.innerHTML = reportModel["DateTo"].toLocaleDateString();
        renderTable(data);               
    });
});

const formatDate = (dateString) => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = ('0' + (date.getMonth() + 1)).slice(-2);
    const day = ('0' + date.getDate()).slice(-2);
    return `${year}-${month}-${day}`;
};

sendByMailButton.addEventListener("click", () => {
    const dateFrom = new Date(dateFromInput.value);
    const dateTo = new Date(dateToInput.value);
    const reportModel = {
        "DateFrom": dateFrom,
        "DateTo": dateTo
    };
    $.ajax({
        url: "/home/sendbymailstatusreport",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(reportModel)
    }).done(() => {
        alert("Отчет успешно отправлен на вашу почту!")
    });
});



const renderTable = (data) => {
    tbody.innerHTML = "";
    
    for (var i = 0; i < data.length; i++) {
        var hearingData = data[i];
        var hearingName = hearingData.hearing;
        
        for (var j = 0; j < hearingData.caseLawyers.length; j++) {
            var info = hearingData.caseLawyers[j];

            if (j === 0) {
                var row = tbody.insertRow();
                var hearingNameCell = row.insertCell()
                hearingNameCell.textContent = hearingName;
                var caseNameCell = row.insertCell();
                var dateCell = row.insertCell();
                var lawyerCell = row.insertCell();
                tbody.appendChild(row)
            }

            var row = tbody.insertRow();
            var hearingNameCell = row.insertCell()
            var caseNameCell = row.insertCell();
            caseNameCell.textContent = info.case;
            var dateCell = row.insertCell();
            dateCell.textContent = formatDate(info.date);
            var lawyerCell = row.insertCell();
            lawyerCell.textContent = info.lawyer;

            tbody.appendChild(row);
        }
    }
}
