<!-- 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="deptTable">
                <thead class="table-light">
                <tr>
                    <th style="width:80px;">#</th>
                    <th class="text-start">조직(부서/팀/파트)</th>
                    <th>설명</th>
                    <th style="width:200px;">관리</th>
                </tr>
                </thead>
                <tbody id="deptTbody"><!-- JS 렌더 --></tbody>
            </table>
        </div>
    </div>
</div>

<!-- 등록 모달 -->
<div class="modal fade" id="deptAddModal" 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="deptAddForm" autocomplete="off">
                <div class="modal-body">
                    <input type="hidden" name="parent_id" id="add_parent_id" value="">
                    <div class="mb-2">
                        <label class="form-label">상위 조직</label>
                        <select class="form-select" id="add_parent_select">
                            <!-- JS로 계층 옵션 렌더 -->
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">부서명 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="dept_name" maxlength="50" required>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">설명</label>
                        <input type="text" class="form-control" name="dept_desc" maxlength="100">
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline-secondary" data-bs-dismiss="modal" type="button">취소</button>
                    <button class="btn btn-primary" type="submit">등록</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 수정 모달 -->
<div class="modal fade" id="deptEditModal" 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="deptEditForm" autocomplete="off">
                <div class="modal-body">
                    <input type="hidden" name="dept_id" id="edit_dept_id">
                    <div class="mb-2">
                        <label class="form-label">상위 조직</label>
                        <select class="form-select" id="edit_parent_select">
                            <!-- JS로 계층 옵션 렌더 -->
                        </select>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">부서명 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="dept_name" id="edit_dept_name" maxlength="50" required>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">설명</label>
                        <input type="text" class="form-control" name="dept_desc" id="edit_dept_desc" maxlength="100">
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline-secondary" data-bs-dismiss="modal" type="button">취소</button>
                    <button class="btn btn-primary" type="submit">저장</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- 삭제 확인 모달 -->
<div class="modal fade" id="deptDeleteModal" 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_dept_id">
            </div>
            <div class="modal-footer">
                <button class="btn btn-outline-secondary" data-bs-dismiss="modal" type="button">취소</button>
                <button class="btn btn-danger" id="btnConfirmDelete" type="button">삭제</button>
            </div>
        </div>
    </div>
</div>

<style>
    /* 트리 인덴트 표현 */
    #deptTbody 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 = 7;
        const nodes = [
            {id:1, parent_id:0, name:'경영지원본부', desc:'인사/총무/회계'},
            {id:2, parent_id:1, name:'인사팀', desc:'인사 기획/운영'},
            {id:3, parent_id:1, name:'총무팀', desc:'총무/자산/구매'},
            {id:4, parent_id:0, name:'영업본부', desc:'고객/채널'},
            {id:5, parent_id:4, name:'영업1팀', desc:'대기업 영업'},
            {id:6, parent_id:0, name:'생산본부', desc:'제조/품질'},
            {id:7, parent_id:6, name:'생산팀', desc:'현장 생산 관리'},
        ];

        // 확장 상태 기억
        const expanded = new Set(); // 펼친 id

        function childrenOf(pid){
            return nodes.filter(n => n.parent_id === pid);
        }
        function hasChildren(id){
            return nodes.some(n => n.parent_id === id);
        }

        // 계층 순회(전개)하여 플랫 렌더 데이터 구성
        function flatten(rootPid=0, level=0){
            const out = [];
            const ch = childrenOf(rootPid).sort((a,b)=>a.name.localeCompare(b.name,'ko'));
            for(const n of ch){
                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);
            const html = rows.map(r=>{
                const hasKid = hasChildren(r.id);
                const caret = hasKid
                    ? `<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>${escapeHtml(r.name)}</strong>
          </td>
          <td>${escapeHtml(r.desc||'')}</td>
          <td>
            <div class="d-flex justify-content-center gap-1">
              <button class="btn btn-sm btn-outline-primary btn-add-child" 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('');
            $('#deptTbody').html(html);
        }

        // 옵션용 계층 라벨 만들기
        function buildOptions(selectedParentId=null, excludeId=null){
            function walk(pid=0, level=0){
                const list = childrenOf(pid).sort((a,b)=>a.name.localeCompare(b.name,'ko'));
                let out = [];
                for(const n of list){
                    if(excludeId && n.id===excludeId) continue; // 자기 자신은 상위로 못 올림
                    const label = `${'— '.repeat(level)}${n.name}`;
                    out.push(`<option value="${n.id}" ${selectedParentId==n.id?'selected':''}>${escapeHtml(label)}</option>`);
                    out.push(...walk(n.id, level+1));
                }
                return out;
            }
            // 최상위(루트) 선택
            return [`<option value="0" ${selectedParentId==0?'selected':''}>(최상위)</option>`, ...walk()].join('');
        }

        // 유틸
        function escapeHtml(s){ return String(s??'').replace(/[&<>"']/g, m=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[m])); }
        function findNode(id){ return nodes.find(n=>n.id==id); }
        function removeBranch(id){
            // 해당 노드와 모든 하위 재귀 삭제
            const kids = childrenOf(id);
            for(const k of kids) 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 allExpanded = allIds.every(id => expanded.has(id) || !hasChildren(id));
            if(allExpanded){
                expanded.clear();
                $(this).text('전체 펼치기');
            }else{
                expanded.clear();
                allIds.forEach(id => { if(hasChildren(id)) expanded.add(id); });
                $(this).text('전체 접기');
            }
            render();
        });

        // 루트 추가 버튼
        $('#btnOpenAddRoot').on('click', function(){
            $('#add_parent_id').val(0);
            $('#add_parent_select').html(buildOptions(0));
            $('#deptAddForm')[0].reset();
            new bootstrap.Modal('#deptAddModal').show();
        });

        // 행: 하위등록
        $(document).on('click', '.btn-add-child', function(){
            const id = +$(this).data('id');
            $('#add_parent_id').val(id);
            $('#add_parent_select').html(buildOptions(id));
            $('#deptAddForm')[0].reset();
            // 부모 펼쳐 둠
            expanded.add(id);
            new bootstrap.Modal('#deptAddModal').show();
        });

        // 등록 처리(프로토타입: 클라이언트만)
        $('#deptAddForm').on('submit', function(e){
            e.preventDefault();
            const pid = +$('#add_parent_select').val();
            const name = $(this).find('[name="dept_name"]').val().trim();
            const desc = $(this).find('[name="dept_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('deptAddModal')).hide();

            // 실제 서버 전송 예:
            // $.post('/tenant/tenant/department_add_process.php', {parent_id:pid, dept_name:name, dept_desc:desc})
        });

        // 행: 수정 열기
        $(document).on('click', '.btn-edit', function(){
            const id = +$(this).data('id');
            const n = findNode(id);
            if(!n) return;
            $('#edit_dept_id').val(n.id);
            $('#edit_dept_name').val(n.name);
            $('#edit_dept_desc').val(n.desc||'');
            $('#edit_parent_select').html(buildOptions(n.parent_id, n.id)); // 자신 제외
            new bootstrap.Modal('#deptEditModal').show();
        });

        // 수정 처리(프로토타입)
        $('#deptEditForm').on('submit', function(e){
            e.preventDefault();
            const id = +$('#edit_dept_id').val();
            const pid = +$('#edit_parent_select').val();
            const name = $('#edit_dept_name').val().trim();
            const desc = $('#edit_dept_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('deptEditModal')).hide();

            // 실제 서버 전송 예:
            // $.post('/tenant/tenant/department_edit_process.php', {dept_id:id, parent_id:pid, dept_name:name, dept_desc:desc})
        });

        // 행: 삭제 열기
        $(document).on('click', '.btn-del', function(){
            const id = +$(this).data('id');
            $('#del_dept_id').val(id);
            new bootstrap.Modal('#deptDeleteModal').show();
        });

        // 삭제 처리(프로토타입)
        $('#btnConfirmDelete').on('click', function(){
            const id = +$('#del_dept_id').val();
            removeBranch(id);
            render();
            bootstrap.Modal.getInstance(document.getElementById('deptDeleteModal')).hide();

            // 실제 서버 전송 예:
            // location.href = '/tenant/tenant/department_delete.php?id='+id;
        });

        // 초기: 1~2단계만 펼치기
        expanded.add(1); expanded.add(4); expanded.add(6);
        render();
    });
</script>

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