// Custom Table Logic
let treatmentList = [];

function renderTreatmentTable() {
    let tbody = document.getElementById("treatmentListBody");
    if (!tbody) {
        // If the tbody doesn't exist (e.g., on a page without the table), do nothing.
        // This can happen if this JS is included on multiple pages.
        return;
    }
    tbody.innerHTML = "";

    treatmentList.forEach((item, index) => {
        let row = document.createElement("tr");
        row.innerHTML = `
            <td><input type="checkbox" name="treatmentCheck" value="${index}"></td>
            <td style="text-align:left; padding-left:10px;">${item.treatmentProcedureName}</td>
            <td style="text-align:right;">${num2won(item.price)}</td>
            <td style="text-align:right;">${num2won(item.discountPrice)}</td>
        `;
        tbody.appendChild(row);
    });
}

function fn_checkAll(source) {
    let checkboxes = document.getElementsByName('treatmentCheck');
    for (var i = 0, n = checkboxes.length; i < n; i++) {
        checkboxes[i].checked = source.checked;
    }
}

function num2won(x) {
    if (typeof x === 'undefined' || x === null) return '';
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}

/****************************************************************************
 * 이벤트 등록
 ****************************************************************************/
function fn_insertWebEvent() {
    if ("Y" != insertUseYn) {
        modalEvent.warning("", "등록 권한이 없습니다.");
        return false;
    }

    let title = $("#title").val();
    let content = $("#content").val();
    let hashtag = $("#hashtag").val();
    let thumbnail_bottom_txt = $("#thumbnailBottomTxt").val();
    let categoryNo = $("select[name=category]").val();

    var treatmentIdList = []; // muTreatmentId
    var treatmentProcedureIdList = []; // muTreatmentProcedureId

    treatmentList.forEach(item => {
        treatmentIdList.push(item.muTreatmentId);
        treatmentProcedureIdList.push(item.muTreatmentProcedureId);
    });

    let eventStartDt = $("#eventStartDt").val();
    let eventEndDt = $("#eventEndDt").val();
    let file = $("#file")[0].files[0];
    let content_file = $("#content_file")[0].files[0];

    if (true != fn_emptyCheck(categoryNo)) {
        modalEvent.warning("등록", "카테고리를 입력하세요.");
        return;
    }
    if (true != fn_emptyCheck(title)) {
        modalEvent.warning("등록", "제목을 입력하세요.");
        return;
    }
    /** 20251024 이상우팀장 요청으로 인해 필수입력 validation 삭제
    if(true != fn_emptyCheck(content)) {
        modalEvent.warning("등록", "내용을 입력하세요.");
        return;
    }
    if(true != fn_emptyCheck(hashtag)) {
        modalEvent.warning("등록", "해시태그를 입력하세요.");
        return;
    }
    if(true != fn_emptyCheck(thumbnail_bottom_txt)) {
        modalEvent.warning("등록", "썸네일 하단 내용을 입력하세요.");
        return;
    }

    if(true != fn_emptyCheck(file)) {
        modalEvent.warning("등록", "썸네일 이미지가 첨부되지 않았습니다.");
        return;
    }else{
        for(let i=0; i<file.length; i++){
            let fileSize = file[i].size;
            if(fileSize > fn_maxFileSize()){
                modalEvent.warning("", "파일정보 용량이 50MB를 넘습니다. 업로드가 불가능합니다.");
                
                return;
            }
        }
    }
    if(true != fn_emptyCheck(content_file)) {
            modalEvent.warning("등록", "컨텐츠 이미지가 첨부되지 않았습니다.");
            return;
        }else{
            for(let i=0; i<content_file.length; i++){
                let fileSize = content_file[i].size;
                if(fileSize > fn_maxFileSize()){
                    modalEvent.warning("", "파일정보 용량이 50MB를 넘습니다. 업로드가 불가능합니다.");
                    
                    return;
                }
            }
        }
    */
    modalEvent.info("등록", categorytitle + " 정보를 등록하시겠습니까?", function () {
        let formData = new FormData();
        formData.append("menuClass", menuClass);
        formData.append("categoryDivCd", categoryDivCd);
        formData.append("categoryNo", categoryNo);
        formData.append("title", title);
        formData.append("content", content);
        formData.append("hashtag", hashtag);
        formData.append("thumbnail_bottom_txt", thumbnail_bottom_txt);
        formData.append("file", file);
        formData.append("content_file", content_file);
        formData.append("treatmentlist", treatmentIdList);
        formData.append("treatmentprocedurelist", treatmentProcedureIdList);
        formData.append("oldCrmItemId", $("#oldCrmItemId").val());
        formData.append("ordNo", $("#ordNo").val());
        formData.append("eventStartDt", eventStartDt);
        formData.append("eventEndDt", eventEndDt);

        $.ajax({
            url: encodeURI('/contentsBbs/putContentsBbs.do'),
            data: formData,
            dataType: "json",
            processData: false,
            contentType: false,
            type: 'POST',
            async: true,
            success: function (data) {
                if ('0' == data.msgCode) {
                    modalEvent.success("등록 성공", data.msgDesc, function () {
                        fn_selectListWebTreatmentPetitIntro();
                    });
                }
                else {
                    modalEvent.danger("등록 오류", data.msgDesc);
                }
            },
            error: function (xhr, status, error) {
                modalEvent.danger("등록 오류", "등록 중 오류가 발생하였습니다. 잠시후 다시시도하십시오.");
            },
            beforeSend: function () {

            },
            complete: function () {

            }
        });
    });
}



/****************************************************************************
 * 배너 이미지 미리보기
 ****************************************************************************/
function fn_filePreview(width, height, obj) {
    let file = "";
    if (obj == '.img_box') {
        file = $("#file")[0].files[0];
    } else {
        file = $("#content_file")[0].files[0];
    }

    if (file) {
        // 기존 이미지 제거 대신 src 교체를 위해 구조 변경됨
        // 하지만 ContentsBbsUpd와 구조를 맞췄으므로 img 태그 id를 이용하는 것이 좋음
        const reader = new FileReader();
        reader.onload = function (e) {
            if (obj == '.img_box') {
                $("#thumbnailImg").attr("src", e.target.result).show();
            } else {
                $("#contentsImg").attr("src", e.target.result).show();
            }
        };
        reader.readAsDataURL(file);
    }
}
/****************************************************************************
 * 배너 이미지 삭제
 ****************************************************************************/
function fn_removePreview() {
    $("#file").val('');
    $("#thumbnailImg").attr("src", "").hide();
}


/****************************************************************************
 * 배너 이미지 미리보기 (컨텐츠) - Unified in fn_filePreview logic mostly but kept callback
 ****************************************************************************/
// fn_filePreview handles logic based on obj param

/****************************************************************************
 * 배너 이미지 삭제 (컨텐츠)
 ****************************************************************************/
function fn_removeContentPreview() {
    $("#content_file").val('');
    $("#contentsImg").attr("src", "").hide();
}

/****************************************************************************
 * 리스트 화면으로 이동.
 ****************************************************************************/
function fn_selectListWebTreatmentPetitIntro() {
    if ("Y" == selectUseYn) {
        let pagingParam = "?menuClass=" + menuClass;
        pagingParam += "&categoryDivCd=" + categoryDivCd;
        fn_leftFormAction("/contentsBbs/moveContentsBbsList.do" + pagingParam);
    } else {
        modalEvent.warning("", "조회 권한이 없습니다.");
        return false;
    }
}

/****************************************************************************
 * 페이지 init
 ****************************************************************************/
function fn_pageInit() {
    // 날짜 datepicker (jQuery UI)
    $("#eventStartDt, #eventEndDt").datepicker({
        dateFormat: 'yy-mm-dd',
        prevText: '이전 달',
        nextText: '다음 달',
        monthNames: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
        monthNamesShort: ['1월', '2월', '3월', '4월', '5월', '6월', '7월', '8월', '9월', '10월', '11월', '12월'],
        dayNames: ['일', '월', '화', '수', '목', '금', '토'],
        dayNamesShort: ['일', '월', '화', '수', '목', '금', '토'],
        dayNamesMin: ['일', '월', '화', '수', '목', '금', '토'],
        showMonthAfterYear: true,
        yearSuffix: '년',
        changeMonth: true,
        changeYear: true
    });

    // 시작일 오늘 날짜 세팅
    $("#eventStartDt").datepicker("setDate", new Date());

    if (categoryDivCd === '02' || categoryDivCd === '04') {
        $("#dateSelectionRow").show();
    }
}

/****************************************************************************
 * 페이지 event
 ****************************************************************************/
function fn_pageEvent() {
    // 검색 input
    $('.btnCancle').on("click", function () {
        fn_selectListWebTreatmentPetitIntro();
    });

    $('.btnSave').on("click", function () {
        fn_insertWebEvent();
    });
    $('#delete_btn').on("click", function () {
        fn_removePreview();
    });
    $('#file').on('change', function (e) {
        // Updated selector logic for new structure
        fn_filePreview('800px', '450px', '.img_box');
    })
    $('#content_delete_btn').on("click", function () {
        fn_removeContentPreview();
    });
    $('#content_file').on('change', function (e) {
        fn_filePreview('100%', '100%', '.file_box');
    })
}

/****************************************************************************
 * 시술 목록 팝업
 ****************************************************************************/
function listOpen() {
    let reqParam = {};
    treatmentSelectModal.popup(function (obj, reqParam) {

        let isDuplicate = false;
        treatmentList.forEach((item) => {
            if (item.muTreatmentProcedureId == obj.treatmentProcedureId) {
                isDuplicate = true;
            }
        });

        if (isDuplicate) {
            modalEvent.warning("", "이미 시술정보가 있습니다.");
            return;
        }

        let newItem = {
            treatmentProcedureName: obj.treatmentNm,
            price: obj.price,
            discountPrice: obj.discountPrice,
            muTreatmentId: obj.treatmentId,
            muTreatmentProcedureId: obj.treatmentProcedureId
        };
        treatmentList.push(newItem);
        renderTreatmentTable();

    }, reqParam);
}

function fn_removeRow() {
    let checkboxes = document.getElementsByName('treatmentCheck');
    let indicesToRemove = [];

    // Collect indices checking from end to start to maintain index validity
    for (let i = checkboxes.length - 1; i >= 0; i--) {
        if (checkboxes[i].checked) {
            indicesToRemove.push(parseInt(checkboxes[i].value));
        }
    }

    if (indicesToRemove.length === 0) {
        modalEvent.warning("", "삭제할 항목을 선택해주세요.");
        return;
    }

    // Remove items
    indicesToRemove.forEach(index => {
        treatmentList.splice(index, 1);
    });

    // Uncheck "all" checkbox if checked
    let checkAllCheckbox = document.getElementById("checkAll");
    if (checkAllCheckbox) {
        checkAllCheckbox.checked = false;
    }

    renderTreatmentTable();
}


$(function () {
    // 페이지 init
    fn_pageInit();

    // 페이지 event
    fn_pageEvent();

    // Initial render for empty table
    renderTreatmentTable();
});

/* =========================================
   PREVIEW LOGIC
   ========================================= */
function fn_openPreview() {
    let url = "/contentsBbs/contentsBbsPreview.do";
    window.open(url, "preview", "width=1280,height=900,scrollbars=yes");
}

function getTreatmentListForPreview() {
    return treatmentList;
}