<!-- SAM RULES: include=../inc/header.php; base=/tenant; width=1280; js=jQuery+BS5 -->
<?php
$CURRENT_SECTION = 'category';
include '../inc/header.php';

// 서버 렌더 기준 선택된 카테고리 (없으면 1)
$category_id = isset($_GET['category_id']) ? intval($_GET['category_id']) : 1;
?>
<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">
            <div class="d-flex align-items-center gap-2">
                <h4 class="mb-0">분류(서브카테고리)</h4>
                <!-- 카테고리 선택 -->
                <select id="selCategory" class="form-select form-select-sm" style="width:220px;">
                    <!-- JS에서 옵션 렌더 -->
                </select>
            </div>
            <button class="btn btn-primary" id="btnOpenAdd">+ 분류 등록</button>
        </div>

        <div class="table-responsive">
            <table class="table table-hover align-middle text-center" id="subTable">
                <thead class="table-light">
                <tr>
                    <th style="width:80px;">#</th>
                    <th>분류명</th>
                    <th>설명</th>
                    <th style="width:150px;">관리</th>
                </tr>
                </thead>
                <tbody id="subTbody"><!-- JS 렌더 --></tbody>
            </table>
        </div>
    </div>
</div>

<!-- 등록 모달 -->
<div class="modal fade" id="subAddModal" 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="subAddForm" autocomplete="off">
                <div class="modal-body">
                    <div class="mb-2">
                        <label class="form-label">상위 카테고리</label>
                        <select class="form-select" id="add_parent_cat"></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="subEditModal" 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="subEditForm" 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_cat"></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="subDeleteModal" 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>

<script>
    $(function(){
        // ===== 샘플 데이터 =====
        // 카테고리 목록 (id, name)
        const categories = [
            {id:1, name:'제품군'},
            {id:2, name:'자재군'}
        ];
        // 분류 목록 (카테고리별 배열)
        let SEQ = 300;
        const subsByCat = {
            1: [
                {id:101, name:'주자재',   desc:'본체에 사용되는 자재'},
                {id:102, name:'부자재', desc:'BOM에 사용되는 자재'},
                {id:102, name:'소모품', desc:'소모성 자재'},
            ],
            2: [
                {id:201, name:'주자재',  desc:'메인자재'},
                {id:202, name:'BOM',desc:'결합제품'},
                {id:202, name:'반자재',desc:'일부결합제품'},
                {id:202, name:'제품',desc:'판매제품'},
            ]
        };

        // 초기 선택(서버에서 전달된 category_id)
        let currentCat = <?php echo json_encode($category_id); ?>;
        if(!categories.some(c=>c.id===currentCat)) currentCat = categories[0]?.id || 1;

        // ----- 렌더러 -----
        function renderCatOptions(){
            $('#selCategory, #add_parent_cat, #edit_parent_cat').each(function(){
                const selId = this.id==='selCategory' ? currentCat : currentCat;
                const html = categories.map(c =>
                    `<option value="${c.id}" ${c.id===selId?'selected':''}>${escapeHtml(c.name)}</option>`
                ).join('');
                $(this).html(html);
            });
        }

        function renderList(){
            const list = subsByCat[currentCat] || [];
            const rows = list.map(s=>`
      <tr data-id="${s.id}">
        <td>${s.id}</td>
        <td>${escapeHtml(s.name)}</td>
        <td>${escapeHtml(s.desc||'')}</td>
        <td>
          <div class="d-flex justify-content-center gap-1">
            <button class="btn btn-sm btn-outline-secondary btn-edit" data-id="${s.id}">수정</button>
            <button class="btn btn-sm btn-outline-danger btn-del" data-id="${s.id}">삭제</button>
          </div>
        </td>
      </tr>
    `).join('');
            $('#subTbody').html(rows);
        }

        const escapeHtml = s => String(s??'').replace(/[&<>"']/g, m=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;' }[m]));

        // ----- 이벤트 -----
        // 카테고리 변경
        $(document).on('change', '#selCategory', function(){
            currentCat = +$(this).val();
            renderCatOptions(); // 상단/모달의 셀렉트 동기화
            renderList();
            // 실제: location.href = '?category_id='+currentCat;
        });

        // 등록 열기
        $('#btnOpenAdd').on('click', function(){
            $('#subAddForm')[0].reset();
            renderCatOptions();
            new bootstrap.Modal('#subAddModal').show();
        });

        // 등록 처리
        $('#subAddForm').on('submit', function(e){
            e.preventDefault();
            const pid  = +$('#add_parent_cat').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;
            subsByCat[pid] = subsByCat[pid] || [];
            subsByCat[pid].push({id, name, desc});

            currentCat = pid;
            renderCatOptions();
            renderList();
            bootstrap.Modal.getInstance(document.getElementById('subAddModal')).hide();

            // 실제: $.post('/tenant/category/subcategory_add_process.php', {category_id:pid, subcategory_name:name, subcategory_desc:desc})
        });

        // 수정 열기
        $(document).on('click', '.btn-edit', function(){
            const id = +$(this).data('id');
            const list = subsByCat[currentCat] || [];
            const item = list.find(x=>x.id===id); if(!item) return;
            $('#edit_id').val(id);
            $('#edit_name').val(item.name);
            $('#edit_desc').val(item.desc||'');
            renderCatOptions();
            new bootstrap.Modal('#subEditModal').show();
        });

        // 수정 처리
        $('#subEditForm').on('submit', function(e){
            e.preventDefault();
            const id   = +$('#edit_id').val();
            const pid  = +$('#edit_parent_cat').val();
            const name = $('#edit_name').val().trim();
            const desc = $('#edit_desc').val().trim();
            if(name.length<2){ alert('분류명을 2글자 이상 입력하세요.'); return; }

            // 기존 위치에서 제거 후 새 카테고리에 삽입(카테고리 이동 허용)
            for(const k of Object.keys(subsByCat)){
                const idx = (subsByCat[k]||[]).findIndex(x=>x.id===id);
                if(idx>-1){ subsByCat[k].splice(idx,1); break; }
            }
            subsByCat[pid] = subsByCat[pid] || [];
            subsByCat[pid].push({id, name, desc});

            currentCat = pid;
            renderCatOptions();
            renderList();
            bootstrap.Modal.getInstance(document.getElementById('subEditModal')).hide();

            // 실제: $.post('/tenant/category/subcategory_edit_process.php', {category_id:pid, subcategory_id:id, subcategory_name:name, subcategory_desc:desc})
        });

        // 삭제 열기/확정
        $(document).on('click', '.btn-del', function(){
            $('#del_id').val(+$(this).data('id'));
            new bootstrap.Modal('#subDeleteModal').show();
        });
        $('#btnConfirmDelete').on('click', function(){
            const id = +$('#del_id').val();
            const list = subsByCat[currentCat] || [];
            const idx = list.findIndex(x=>x.id===id);
            if(idx>-1) list.splice(idx,1);
            renderList();
            bootstrap.Modal.getInstance(document.getElementById('subDeleteModal')).hide();

            // 실제: location.href = '/tenant/category/subcategory_delete.php?category_id='+currentCat+'&id='+id;
        });

        // 초기 렌더
        renderCatOptions();
        renderList();
    });
</script>

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