<!-- 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:24px;">
    <div class="card">
        <div class="sam-toolbar">
            <div class="sam-title">공통코드 / 옵션 관리</div>
            <div class="sam-actions">
                <input type="text" class="form-control form-control-sm" id="kwGroup" placeholder="그룹 검색(키/이름)">
                <button class="btn btn-sm btn-outline-secondary" id="btnFindGroup">검색</button>
                <button class="btn btn-sm btn-primary" id="btnOpenAddGroup">+ 그룹 생성</button>
            </div>
        </div>

        <div class="row g-0">
            <!-- 좌측: 그룹 리스트 -->
            <div class="col-12 col-md-4 border-end">
                <div class="p-3">
                    <div class="d-flex justify-content-between align-items-center mb-2">
                        <strong>그룹 목록</strong>
                        <div class="text-muted small" id="groupCount"></div>
                    </div>
                    <div class="table-responsive" style="max-height:520px; overflow:auto;">
                        <table class="table table-sam" id="tblGroups">
                            <thead><tr><th style="width:80px;">ID</th><th>그룹키</th><th>이름</th><th style="width:90px;">관리</th></tr></thead>
                            <tbody><!-- JS render --></tbody>
                        </table>
                    </div>
                </div>
            </div>

            <!-- 우측: 항목(값) 리스트 -->
            <div class="col-12 col-md-8">
                <div class="p-3">
                    <div class="d-flex align-items-center justify-content-between mb-2">
                        <div>
                            <strong>항목 목록</strong>
                            <span class="text-muted ms-2" id="currentGroupLabel">선택된 그룹이 없습니다</span>
                        </div>
                        <div class="d-flex align-items-center gap-2">
                            <input type="text" class="form-control form-control-sm" id="kwValue" placeholder="항목 검색(코드/라벨)">
                            <button class="btn btn-sm btn-outline-secondary" id="btnFindValue">검색</button>
                            <button class="btn btn-sm btn-primary" id="btnOpenAddValue" disabled>+ 항목 추가</button>
                        </div>
                    </div>

                    <div class="table-responsive" style="max-height:520px; overflow:auto;">
                        <table class="table table-sam" id="tblValues">
                            <thead>
                            <tr>
                                <th style="width:80px;">ID</th>
                                <th>코드(value_key)</th>
                                <th>라벨(value_label)</th>
                                <th style="width:90px;">정렬</th>
                                <th style="width:90px;">사용</th>
                                <th style="width:120px;">관리</th>
                            </tr>
                            </thead>
                            <tbody><!-- JS render --></tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 그룹 추가/수정 모달 -->
<div class="modal fade" id="groupModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-md modal-dialog-centered">
        <form class="modal-content" id="groupForm" autocomplete="off">
            <div class="modal-header">
                <h5 class="modal-title" id="groupModalTitle">그룹 생성</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="닫기"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="id" id="group_id">
                <div class="mb-2">
                    <label class="form-label">그룹키 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="group_key" id="group_key" placeholder="예: position, job_title" required>
                    <div class="form-text">영문/코드 권장. 테넌트 내 유일해야 합니다.</div>
                </div>
                <div class="mb-2">
                    <label class="form-label">이름 <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="name" id="group_name" required>
                </div>
                <div class="mb-2">
                    <label class="form-label">설명</label>
                    <input type="text" class="form-control" name="description" id="group_desc" maxlength="255">
                </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" id="btnSaveGroup">저장</button>
            </div>
        </form>
    </div>
</div>

<!-- 항목 추가/수정 모달 -->
<div class="modal fade" id="valueModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-md modal-dialog-centered">
        <form class="modal-content" id="valueForm" autocomplete="off">
            <div class="modal-header">
                <h5 class="modal-title" id="valueModalTitle">항목 추가</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="닫기"></button>
            </div>
            <div class="modal-body">
                <input type="hidden" name="id" id="value_id">
                <input type="hidden" name="group_id" id="value_group_id">
                <div class="mb-2">
                    <label class="form-label">코드(value_key) <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="value_key" id="value_key" required>
                    <div class="form-text">그룹 내 유일해야 합니다.</div>
                </div>
                <div class="mb-2">
                    <label class="form-label">라벨(value_label) <span class="text-danger">*</span></label>
                    <input type="text" class="form-control" name="value_label" id="value_label" required>
                </div>
                <div class="mb-2">
                    <label class="form-label">정렬(sort_order)</label>
                    <input type="number" class="form-control" name="sort_order" id="sort_order" value="0">
                </div>
                <div class="form-check">
                    <input class="form-check-input" type="checkbox" id="is_active" checked>
                    <label class="form-check-label" for="is_active">사용함</label>
                </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" id="btnSaveValue">저장</button>
            </div>
        </form>
    </div>
</div>

<!-- 삭제 확인 모달 (그룹/항목 공용) -->
<div class="modal fade" id="confirmModal" 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="confirm_target" value="">
                <input type="hidden" id="confirm_type" value=""> <!-- group | value -->
            </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>
    /* 좌측 리스트 선택 표시 */
    #tblGroups tbody tr.active { background:#eef4ff; }
    /* 작은 토글 느낌 */
    .toggle-yes { color:#2c4a85; font-weight:600; }
    .toggle-no  { color:#888; }
</style>

<script>
    // ====== 프로토타입 데이터 ======
    // 실제에선 tenant_id=세션테넌트 기준으로 API 연동
    let GROUPS = [
        {id: 101, group_key:'position',      name:'직급',     description:'회사 직급'},
        {id: 102, group_key:'job_title',     name:'직책',     description:'직책/보임직'},
        {id: 103, group_key:'employment_type', name:'고용형태', description:'정규/계약/인턴'},
        {id: 104, group_key:'work_location', name:'근무지',   description:'본사/공장/현장'},
        {id: 105, group_key:'work_type',     name:'근무형태', description:'주간/야간/교대'},
        {id: 106, group_key:'gender',        name:'성별',     description:''},
        {id: 107, group_key:'bank_name',     name:'은행',     description:'급여계좌 은행'}
    ];
    // group_id별 값
    let VALUES = {
        101:[{id:1, group_id:101, value_key:'staff', value_label:'사원', sort_order:10, is_active:1},
            {id:2, group_id:101, value_key:'assistant', value_label:'대리', sort_order:20, is_active:1}],
        102:[{id:3, group_id:102, value_key:'team_lead', value_label:'팀장', sort_order:10, is_active:1}],
        103:[{id:4, group_id:103, value_key:'regular', value_label:'정규직', sort_order:10, is_active:1},
            {id:5, group_id:103, value_key:'contract', value_label:'계약직', sort_order:20, is_active:1}],
        104:[{id:6, group_id:104, value_key:'hq', value_label:'본사', sort_order:10, is_active:1}],
        105:[{id:7, group_id:105, value_key:'day', value_label:'주간', sort_order:10, is_active:1}],
        106:[{id:8, group_id:106, value_key:'male', value_label:'남', sort_order:10, is_active:1},
            {id:9, group_id:106, value_key:'female', value_label:'여', sort_order:20, is_active:1}],
        107:[{id:10, group_id:107, value_key:'kb', value_label:'국민은행', sort_order:10, is_active:1},
            {id:11, group_id:107, value_key:'shinhan', value_label:'신한은행', sort_order:20, is_active:1}]
    };
    let seqValue = 1000; // 데모용 id 증가

    let currentGroupId = null;
    let filterGroupKW = '';
    let filterValueKW = '';

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

    // ====== 렌더링 ======
    function renderGroups(){
        const list = GROUPS.filter(g => {
            if(!filterGroupKW) return true;
            const s = filterGroupKW.toLowerCase();
            return [g.group_key, g.name].some(v => String(v).toLowerCase().includes(s));
        }).sort((a,b)=> a.name.localeCompare(b.name,'ko'));
        $('#groupCount').text(`${list.length}개`);
        const html = list.map(g=>`
      <tr data-id="${g.id}" class="${g.id===currentGroupId?'active':''}">
        <td>${g.id}</td>
        <td class="text-start">${esc(g.group_key)}</td>
        <td class="text-start">${esc(g.name)}</td>
        <td>
          <div class="d-flex justify-content-center gap-1">
            <button class="btn btn-sm btn-outline-secondary btn-edit-group" data-id="${g.id}">수정</button>
            <button class="btn btn-sm btn-outline-danger btn-del-group" data-id="${g.id}">삭제</button>
          </div>
        </td>
      </tr>
    `).join('');
        $('#tblGroups tbody').html(html);
    }

    function renderValues(){
        const labelSpan = currentGroupId
            ? (()=>{ const g = GROUPS.find(x=>x.id===currentGroupId); return g ? `(${esc(g.group_key)} / ${esc(g.name)})` : '' })()
            : '선택된 그룹이 없습니다';
        $('#currentGroupLabel').text(labelSpan);
        $('#btnOpenAddValue').prop('disabled', !currentGroupId);

        const rows = VALUES[currentGroupId] || [];
        const list = rows
            .filter(v=>{
                if(!filterValueKW) return true;
                const s = filterValueKW.toLowerCase();
                return [v.value_key, v.value_label].some(x => String(x).toLowerCase().includes(s));
            })
            .sort((a,b)=> a.sort_order-b.sort_order || a.value_label.localeCompare(b.value_label,'ko'));
        const html = list.map(v=>`
      <tr data-id="${v.id}">
        <td>${v.id}</td>
        <td class="text-start">${esc(v.value_key)}</td>
        <td class="text-start">${esc(v.value_label)}</td>
        <td>${v.sort_order}</td>
        <td>${v.is_active?'<span class="toggle-yes">Y</span>':'<span class="toggle-no">N</span>'}</td>
        <td>
          <div class="d-flex justify-content-center gap-1">
            <button class="btn btn-sm btn-outline-secondary btn-edit-value" data-id="${v.id}">수정</button>
            <button class="btn btn-sm btn-outline-danger btn-del-value" data-id="${v.id}">삭제</button>
          </div>
        </td>
      </tr>
    `).join('');
        $('#tblValues tbody').html(html);
    }

    // ====== 그룹 이벤트 ======
    $(document).on('click', '#tblGroups tbody tr', function(e){
        // 행 클릭 시 선택(버튼 클릭은 제외)
        if($(e.target).closest('button').length) return;
        const id = +$(this).data('id');
        currentGroupId = id;
        renderGroups();
        renderValues();
    });

    $('#btnFindGroup').on('click', function(){
        filterGroupKW = $('#kwGroup').val().trim();
        renderGroups();
    });

    $('#btnOpenAddGroup').on('click', function(){
        $('#groupModalTitle').text('그룹 생성');
        $('#groupForm')[0].reset();
        $('#group_id').val('');
        new bootstrap.Modal('#groupModal').show();
    });

    $(document).on('click', '.btn-edit-group', function(){
        const id = +$(this).data('id');
        const g = GROUPS.find(x=>x.id===id);
        if(!g) return;
        $('#groupModalTitle').text('그룹 수정');
        $('#group_id').val(g.id);
        $('#group_key').val(g.group_key);
        $('#group_name').val(g.name);
        $('#group_desc').val(g.description||'');
        new bootstrap.Modal('#groupModal').show();
    });

    $(document).on('click', '.btn-del-group', function(){
        const id = +$(this).data('id');
        $('#confirm_type').val('group');
        $('#confirm_target').val(id);
        new bootstrap.Modal('#confirmModal').show();
    });

    $('#groupForm').on('submit', function(e){
        e.preventDefault();
        const id = $('#group_id').val();
        const payload = {
            group_key: $('#group_key').val().trim(),
            name: $('#group_name').val().trim(),
            description: $('#group_desc').val().trim()
        };
        if(!payload.group_key || !payload.name){
            alert('그룹키와 이름은 필수입니다.'); return;
        }

        if(id){ // 수정
            const g = GROUPS.find(x=>x.id==id);
            if(!g) return;
            g.group_key = payload.group_key;
            g.name      = payload.name;
            g.description = payload.description;
            // 실제: POST /tenant/api/options/group_update.php
        }else{ // 생성
            const newId = Math.max(0, ...GROUPS.map(x=>x.id)) + 1;
            GROUPS.push({id:newId, ...payload});
            VALUES[newId] = [];
            currentGroupId = newId;
            // 실제: POST /tenant/api/options/group_create.php
        }
        bootstrap.Modal.getInstance(document.getElementById('groupModal')).hide();
        renderGroups(); renderValues();
    });

    // ====== 항목 이벤트 ======
    $('#btnFindValue').on('click', function(){
        filterValueKW = $('#kwValue').val().trim();
        renderValues();
    });

    $('#btnOpenAddValue').on('click', function(){
        if(!currentGroupId){ alert('그룹을 먼저 선택하세요.'); return; }
        $('#valueModalTitle').text('항목 추가');
        $('#valueForm')[0].reset();
        $('#value_id').val('');
        $('#value_group_id').val(currentGroupId);
        $('#is_active').prop('checked', true);
        new bootstrap.Modal('#valueModal').show();
    });

    $(document).on('click', '.btn-edit-value', function(){
        const id = +$(this).data('id');
        const list = VALUES[currentGroupId] || [];
        const v = list.find(x=>x.id===id);
        if(!v) return;
        $('#valueModalTitle').text('항목 수정');
        $('#value_id').val(v.id);
        $('#value_group_id').val(v.group_id);
        $('#value_key').val(v.value_key);
        $('#value_label').val(v.value_label);
        $('#sort_order').val(v.sort_order);
        $('#is_active').prop('checked', !!v.is_active);
        new bootstrap.Modal('#valueModal').show();
    });

    $(document).on('click', '.btn-del-value', function(){
        const id = +$(this).data('id');
        $('#confirm_type').val('value');
        $('#confirm_target').val(id);
        new bootstrap.Modal('#confirmModal').show();
    });

    $('#valueForm').on('submit', function(e){
        e.preventDefault();
        const id = $('#value_id').val();
        const gid = +$('#value_group_id').val();
        const payload = {
            group_id: gid,
            value_key: $('#value_key').val().trim(),
            value_label: $('#value_label').val().trim(),
            sort_order: parseInt($('#sort_order').val(),10) || 0,
            is_active: $('#is_active').is(':checked') ? 1 : 0
        };
        if(!payload.value_key || !payload.value_label){
            alert('코드와 라벨은 필수입니다.'); return;
        }
        const list = VALUES[gid] || (VALUES[gid]=[]);
        if(id){ // 수정
            const v = list.find(x=>x.id==id);
            if(!v) return;
            Object.assign(v, payload);
            // 실제: POST /tenant/api/options/value_update.php
        }else{ // 추가
            const newId = ++seqValue;
            list.push({id:newId, ...payload});
            // 실제: POST /tenant/api/options/value_create.php
        }
        bootstrap.Modal.getInstance(document.getElementById('valueModal')).hide();
        renderValues();
    });

    // ====== 공용 삭제 확정 ======
    $('#btnConfirmDelete').on('click', function(){
        const type = $('#confirm_type').val();
        const targetId = +$('#confirm_target').val();
        if(type==='group'){
            // 그룹 삭제: 값도 함께 제거(외래키 ON DELETE CASCADE 성격)
            GROUPS = GROUPS.filter(g=>g.id!==targetId);
            delete VALUES[targetId];
            if(currentGroupId===targetId) currentGroupId = null;
            // 실제: GET /tenant/api/options/group_delete.php?id=...
            renderGroups(); renderValues();
        }else if(type==='value'){
            if(!currentGroupId){ return; }
            const list = VALUES[currentGroupId] || [];
            const idx = list.findIndex(v=>v.id===targetId);
            if(idx>-1) list.splice(idx,1);
            // 실제: GET /tenant/api/options/value_delete.php?id=...
            renderValues();
        }
        bootstrap.Modal.getInstance(document.getElementById('confirmModal')).hide();
    });

    // ====== 초기 렌더 ======
    $(function(){
        renderGroups();
        // 기본 선택: 첫 그룹
        if(GROUPS.length){
            currentGroupId = GROUPS[0].id;
            renderGroups(); renderValues();
        }
    });
</script>

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