const updateBtn = document.getElementById("update-button");
const subjectInput = document.getElementById("subject-input");
const responsibilitiesInput = document.getElementById("responsibilities-input");
const dateInput = document.getElementById("date-input");
const dealId = document.getElementById("vb-id").dataset.id;
const errorP = document.getElementById("error-p");
const errorDivShell = document.getElementById("error-div-shell");

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}`;
};

window.addEventListener("load", async () => {
    try {
        await $.ajax({
            url: `/deal/get?id=${dealId}`,
            type: "GET",
            contentType: "json"
        }).done((result) => {
            subjectInput.value = result.subject;
            responsibilitiesInput.value = result.responsibilities;
            dateInput.value = formatDate(result.date);
        });
    } catch (error) {
        console.error(error);
    }
});

const correctData = function () {

    return true;
};

const validate = function () {

    if (subjectInput.value === "") {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Заполните поле 'Предмет договора'";
        return false;
    }
    if (responsibilitiesInput.value === "") {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Заполните поле 'Обязаности'";
        return false;
    }
    if (dataArray.length === 0) {
        errorDivShell.style.gridTemplateRows = "1fr";
        errorP.innerHTML = "Заполните список 'Дел'";
        return false;
    }
    return true;
};

updateBtn.addEventListener("click", () => {
    if (!correctData()) {
        return;
    }
    if (!validate()) {
        return;
    }
    
    let dealModel = {
        "Id": parseInt(dealId),
        "Subject": subjectInput.value,
        "Responsibilities": responsibilitiesInput.value,
        "Date": dateInput.value
    };
    console.log(dealModel)
    $.ajax({
        url: "/deal/update",
        type: "POST",
        contentType: "application/json",
        data: JSON.stringify(dealModel)
    }).done(() => {
        window.location.href = "/Home/Deals";
    });
});