@page
@model Admin.Pages.Forum.Board.GroupModel
@{
    ViewData["Title"] = "게시판 분류";
}

<div class="container-fluid">
    <h3>@ViewData["Title"]</h3>
    <hr />

    <partial name="_StatusMessage" />

    <div class="row g-2 align-items-end">
        <div class="col">
            Total : @Model.Total
        </div>
        <div class="col text-end">
            <button type="button" id="btnAdd" class="btn btn-primary" form="fAdminWrite">추가</button>
            <button type="submit" id="btnSave" class="btn btn-success" form="fAdminWrite">저장</button>
        </div>
    </div>

    <div class="table-responsive">
        <form id="fAdminWrite" method="post" accept-charset="utf-8" autocomplete="off"></form>

        <table class="table table-striped table-bordered table-hover mt-3">
            <caption>
                게시판 분류에 등록된 게시판이 있다면 삭제가 불가합니다.<br/>
                게시판 분류를 삭제하려면 등록된 게시판을 먼저 삭제해주세요.
            </caption>
            <colgroup>
                <col style="width: 5%;" />
                <col />
                <col style="width: 20%;" />
                <col />
                <col />
                <col />
                <col />
                <col />
                <col />
                <col />
            </colgroup>
            <thead>
                <tr>
                    <th>ID</th>
                    <th>Code</th>
                    <th>분류 명</th>
                    <th>순서</th>
                    <th>게시판 수</th>
                    <th>게시글 수</th>
                    <th>댓글 수</th>
                    <th>등록일시</th>
                    <th>수정일시</th>
                    <th>비고</th>
                </tr>
            </thead>
            <tbody id="boardGroupList">
                @if (Model.List == null || Model.List.Count <= 0)
                {
                    <tr>
                        <td colspan="10">No Data.</td>
                    </tr>
                }
                else
                {
                    @foreach (var row in Model.List)
                    {
                        var index = row.Index;

                        <tr>
                            <td>
                                <input type="text" readonly class="form-control-plaintext text-center @(row.Boards > 0 ? "text-white bg-danger" : "")" value="@row.Num" />
                                <input type="hidden" name="request[@index].ID" readonly class="form-control-plaintext text-center" required form="fAdminWrite" value="@row.ID" />
                            </td>
                            <td>
                                <input type="text" name="request[@index].Code" class="form-control" maxlength="30" required form="fAdminWrite" value="@row.Code" />
                            </td>
                            <td>
                                <input type="text" name="request[@index].Name" class="form-control" maxlength="255" required form="fAdminWrite" value="@row.Name" />
                            </td>
                            <td>
                                <input type="number" name="request[@index].Order" class="form-control" min="-9999" max="9999" required form="fAdminWrite" value="@row.Order" />
                            </td>
                            <td>@row.Boards.ToString("N0")</td>
                            <td>@row.Posts.ToString("N0")</td>
                            <td>@row.Comments.ToString("N0")</td>
                            <td>@row.CreatedAt</td>
                            <td>@row.UpdatedAt</td>
                            <td>
                                <button type="button" class="btn btn-sm btn-danger btn-delete">삭제</button>
                            </td>
                        </tr>
                    }
                }
            </tbody>
        </table>
    </div>
</div>

@section Scripts {
<script>
    $(function() {
        let $boardGroupList = $("#boardGroupList");
        let total = Number(@Model.Total);

        // 추가
        $(document).on("click", "#btnAdd", function() {
            if (total <= 0) {
                $boardGroupList.empty();
            }

            let now = new Date().toLocaleString();
            let tableRow = `
                <tr>
                    <td>-</td>
                    <td>
                        <input type="text" name="request[${total}].Code" class="form-control" maxlength="30" required form="fAdminWrite" />
                    </td>
                    <td>
                        <input type="text" name="request[${total}].Name" class="form-control" maxlength="255" required form="fAdminWrite" />
                    </td>
                    <td>
                        <input type="number" name="request[${total}].Order" class="form-control" min="-999" max="999" required form="fAdminWrite" />
                    </td>
                    <td>-</td>
                    <td>-</td>
                    <td>-</td>
                    <td>${now}</td>
                    <td>-</td>
                    <td>
                        <button type="button" class="btn btn-danger btn-delete">삭제</button>
                    </td>
                </tr>
            `;

            $boardGroupList.append(tableRow);
            total++;
            recalculateIndices();
        });

        // 삭제
        $(document).on("click", "button.btn-delete", function(e) {
            e.target.closest("tr").remove();
            total--;

            if (total <= 0) {
                $boardGroupList.append(
                    `<tr><td colspan="10">No Data.</td></tr>`
                );
                total = 0;
            } else {
                recalculateIndices();
            }
        });

        // 저장
        $(document).on("click", "#btnSave", function() {
            if (confirm("저장 하시겠습니까?")) {
                let form = document.getElementById("fAdminWrite");
                if (form.checkValidity()) {
                    form.submit();
                } else {
                    form.reportValidity();
                }
            }
            return false;
        });

        // 인덱스 재계산 함수
        function recalculateIndices() {
            $boardGroupList.find("tr").each(function(index, tr) {
                $(tr)
                    .find("input, label")
                    .each(function() {
                        let name = $(this).attr("name");
                        let id = $(this).attr("id");

                        if (name) {
                            $(this).attr("name", name.replace(/\[\d+\]/, `[${index}]`));
                        }

                        if (id) {
                            $(this).attr("id", id.replace(/_\d+_/, `_${index}_`));
                        }
                    });

                $(tr)
                    .find("label")
                    .each(function() {
                        let labelFor = $(this).attr("for");
                        if (labelFor) {
                            $(this).attr("for", labelFor.replace(/_\d+_/, `_${index}_`));
                        }
                    });
            });
        }
    });
</script>
}