<!-- SAM RULES: include=../inc/header.php; base=/tenant; width=1280; js=jQuery+BS5 -->
<?php
$CURRENT_SECTION = 'tenant';
include '../inc/header.php';
?>
<div class="container" style="max-width:1280px; margin-top:40px;">
    <div class="card shadow p-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h4 class="mb-0">카테고리 트리</h4>
            <div class="d-flex gap-2">
                <button class="btn btn-outline-secondary" id="btnToggleAll">전체 접기</button>
                <button class="btn btn-primary" id="btnOpenAddRoot">+ 카테고리 등록</button>
            </div>
        </div>

        <div class="table-responsive">
            <table class="table table-hover align-middle text-center" id="catTable">
                <thead class="table-light">
                <tr>
                    <th style="width:80px;">#</th>
                    <th class="text-start">카테고리명</th>
                    <th>설명</th>
                    <th style="width:220px;">관리</th>
                </tr>
                </thead>
                <tbody id="catTbody"><!-- JS 렌더 --></tbody>
            </table>
        </div>
    </div>
</div>

<!-- 등록 모달 -->
<div class="modal fade" id="catAddModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-md modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">카테고리 등록</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="닫기"></button>
            </div>
            <form id="catAddForm" autocomplete="off">
                <div class="modal-body">
                    <div class="mb-2">
                        <label class="form-label">상위 카테고리</label>
                        <select class="form-select" id="add_parent_select"><!-- 옵션 렌더 --></select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">카테고리명 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="name" maxlength="50" required>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">설명</label>
                        <input type="text" class="form-control" name="desc" maxlength="100">
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline-secondary" type="button" data-bs-dismiss="modal">취소</button>
                    <button class="btn btn-primary" type="submit">등록</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 수정 모달 -->
<div class="modal fade" id="catEditModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-md modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">카테고리 수정</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="닫기"></button>
            </div>
            <form id="catEditForm" autocomplete="off">
                <div class="modal-body">
                    <input type="hidden" id="edit_id">
                    <div class="mb-2">
                        <label class="form-label">상위 카테고리</label>
                        <select class="form-select" id="edit_parent_select"><!-- 옵션 렌더 --></select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">카테고리명 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" id="edit_name" maxlength="50" required>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">설명</label>
                        <input type="text" class="form-control" id="edit_desc" maxlength="100">
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline-secondary" type="button" data-bs-dismiss="modal">취소</button>
                    <button class="btn btn-primary" type="submit">저장</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 삭제 모달 -->
<div class="modal fade" id="catDeleteModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-sm modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">삭제 확인</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="닫기"></button>
            </div>
            <div class="modal-body">
                <div class="small">하위 항목이 모두 함께 삭제됩니다. 진행할까요?</div>
                <input type="hidden" id="del_id">
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline-secondary" type="button" data-bs-dismiss="modal">취소</button>
                <button class="btn btn-danger" type="button" id="btnConfirmDelete">삭제</button>
            </div>
        </div>
    </div>
</div>

<style>
    /* 부서 트리와 동일 톤 */
    #catTbody tr[data-level] td.name-cell{
        --indent: calc(var(--level,0)*18px);
        padding-left: calc(var(--indent) + .25rem) !important;
    }
    .caret{
        display:inline-flex; align-items:center; justify-content:center;
        width:1.15rem; height:1.15rem; border-radius:4px; border:1px solid #cbd3e1;
        background:#f6f8fc; cursor:pointer; margin-right:.35rem; font-size:.8rem; user-select:none;
    }
    .caret[aria-expanded="false"]::after{ content:"+"; }
    .caret[aria-expanded="true"]::after{ content:"–"; }
    .badge-node{ background:#e9f0fb; color:#2c4a85; }
</style>

<script>
    $(function(){
        // ===== 샘플 데이터 (id, parent_id, name, desc) =====
        let SEQ = 6;
        const nodes = [
            {id:1, parent_id:0, name:'제품군', desc:'회사 제품 카테고리'},
            {id:2, parent_id:1, name:'방화제품', desc:'방화/내화'},
            {id:3, parent_id:2, name:'방화셔터', desc:'셔터 라인'},
            {id:4, parent_id:1, name:'일반제품', desc:'상용 제품'},
            {id:5, parent_id:0, name:'서비스', desc:'서비스 카테고리'},
            {id:6, parent_id:5, name:'유지보수', desc:'유지보수/점검'},
        ];
        const expanded = new Set([1,5]); // 기본 펼침

        const childrenOf = pid => nodes.filter(n=>n.parent_id===pid);
        const hasChildren = id => nodes.some(n=>n.parent_id===id);
        const findNode = id => nodes.find(n=>n.id==id);
        const esc = s => String(s??'').replace(/[&<>"']/g, m=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[m]));

        function flatten(pid=0, level=0){
            const list = childrenOf(pid).sort((a,b)=>a.name.localeCompare(b.name,'ko'));
            let out=[]; for(const n of list){
                out.push({...n, level});
                if(expanded.has(n.id)) out.push(...flatten(n.id, level+1));
            } return out;
        }

        function render(){
            const rows = flatten(0,0).map(r=>{
                const caret = hasChildren(r.id)
                    ? `<span class="caret" data-id="${r.id}" aria-expanded="${expanded.has(r.id)}"></span>`
                    : `<span style="display:inline-block;width:1.15rem;margin-right:.35rem;"></span>`;
                return `
        <tr data-id="${r.id}" data-level="${r.level}" style="--level:${r.level}">
          <td>${r.id}</td>
          <td class="text-start name-cell">
            ${caret}
            <span class="badge badge-node me-2">Lv.${r.level}</span>
            <strong>${esc(r.name)}</strong>
          </td>
          <td>${esc(r.desc||'')}</td>
          <td>
            <div class="d-flex justify-content-center gap-1">
              <button class="btn btn-sm btn-outline-primary btn-add" data-id="${r.id}">하위등록</button>
              <button class="btn btn-sm btn-outline-secondary btn-edit" data-id="${r.id}">수정</button>
              <button class="btn btn-sm btn-outline-danger btn-del" data-id="${r.id}">삭제</button>
            </div>
          </td>
        </tr>`;
            }).join('');
            $('#catTbody').html(rows);
        }

        function buildOptions(selected=0, excludeId=null){
            function walk(pid=0, level=0){
                return childrenOf(pid).sort((a,b)=>a.name.localeCompare(b.name,'ko'))
                    .flatMap(n=>{
                        if(excludeId && n.id===excludeId) return [];
                        return [
                            `<option value="${n.id}" ${selected==n.id?'selected':''}>${esc('— '.repeat(level)+n.name)}</option>`,
                            ...walk(n.id, level+1)
                        ];
                    });
            }
            return [`<option value="0" ${selected==0?'selected':''}>(최상위)</option>`, ...walk()].join('');
        }

        function removeBranch(id){
            for(const k of childrenOf(id)) removeBranch(k.id);
            const i = nodes.findIndex(n=>n.id==id);
            if(i>-1) nodes.splice(i,1);
            expanded.delete(id);
        }

        // 펼침/접기
        $(document).on('click', '.caret', function(){
            const id = +$(this).data('id');
            if(expanded.has(id)) expanded.delete(id); else expanded.add(id);
            render();
        });

        // 전체 접기/펼치기
        $('#btnToggleAll').on('click', function(){
            const allIds = nodes.map(n=>n.id);
            const allOpen = allIds.every(id => expanded.has(id) || !hasChildren(id));
            if(allOpen){ expanded.clear(); $(this).text('전체 펼치기'); }
            else{ expanded.clear(); allIds.forEach(id=>{ if(hasChildren(id)) expanded.add(id); }); $(this).text('전체 접기'); }
            render();
        });

        // 루트 등록
        $('#btnOpenAddRoot').on('click', function(){
            $('#catAddForm')[0].reset();
            $('#add_parent_select').html(buildOptions(0));
            new bootstrap.Modal('#catAddModal').show();
        });

        // 하위등록
        $(document).on('click', '.btn-add', function(){
            const pid = +$(this).data('id');
            $('#catAddForm')[0].reset();
            $('#add_parent_select').html(buildOptions(pid));
            expanded.add(pid);
            new bootstrap.Modal('#catAddModal').show();
        });

        // 등록 처리(프로토타입)
        $('#catAddForm').on('submit', function(e){
            e.preventDefault();
            const pid = +$('#add_parent_select').val();
            const name = $(this).find('[name="name"]').val().trim();
            const desc = $(this).find('[name="desc"]').val().trim();
            if(name.length<2){ alert('카테고리명을 2글자 이상 입력하세요.'); return; }
            const id = ++SEQ;
            nodes.push({id, parent_id:pid, name, desc});
            expanded.add(pid);
            render();
            bootstrap.Modal.getInstance(document.getElementById('catAddModal')).hide();
            // 실제: $.post('/tenant/category/category_add_process.php', {parent_id:pid,name,desc})
        });

        // 수정 열기
        $(document).on('click', '.btn-edit', function(){
            const id = +$(this).data('id');
            const n = findNode(id); if(!n) return;
            $('#edit_id').val(n.id);
            $('#edit_name').val(n.name);
            $('#edit_desc').val(n.desc||'');
            $('#edit_parent_select').html(buildOptions(n.parent_id, n.id));
            new bootstrap.Modal('#catEditModal').show();
        });

        // 수정 처리
        $('#catEditForm').on('submit', function(e){
            e.preventDefault();
            const id = +$('#edit_id').val();
            const pid = +$('#edit_parent_select').val();
            const name = $('#edit_name').val().trim();
            const desc = $('#edit_desc').val().trim();
            if(name.length<2){ alert('카테고리명을 2글자 이상 입력하세요.'); return; }
            const n = findNode(id); if(!n) return;
            n.name = name; n.desc = desc; n.parent_id = pid;
            expanded.add(pid);
            render();
            bootstrap.Modal.getInstance(document.getElementById('catEditModal')).hide();
            // 실제: $.post('/tenant/category/category_edit_process.php', {id, parent_id:pid, name, desc})
        });

        // 삭제
        $(document).on('click', '.btn-del', function(){
            $('#del_id').val(+$(this).data('id'));
            new bootstrap.Modal('#catDeleteModal').show();
        });
        $('#btnConfirmDelete').on('click', function(){
            const id = +$('#del_id').val();
            removeBranch(id);
            render();
            bootstrap.Modal.getInstance(document.getElementById('catDeleteModal')).hide();
            // 실제: location.href='/tenant/category/category_delete.php?id='+id;
        });

        render();
    });
</script>

<?php include '../inc/footer.php'; ?>
