<!-- 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>
            <button class="btn btn-primary" id="btnOpenAdd">+ 역할 등록</button>
        </div>

        <div class="table-responsive">
            <table class="table table-hover align-middle text-center" id="roleTable">
                <thead class="table-light">
                <tr>
                    <th style="width:80px;">#</th>
                    <th>역할명</th>
                    <th>설명</th>
                    <th style="width:180px;">관리</th>
                </tr>
                </thead>
                <tbody id="roleTbody"><!-- JS 렌더 --></tbody>
            </table>
        </div>
    </div>
</div>

<!-- 등록 모달 -->
<div class="modal fade" id="roleAddModal" 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="roleAddForm" autocomplete="off">
                <div class="modal-body">
                    <div class="mb-3">
                        <label class="form-label">역할명 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="role_name" maxlength="30" required>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">설명</label>
                        <input type="text" class="form-control" name="role_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="roleEditModal" 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="roleEditForm" autocomplete="off">
                <div class="modal-body">
                    <input type="hidden" name="role_id" id="edit_role_id">
                    <div class="mb-3">
                        <label class="form-label">역할명 <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="role_name" id="edit_role_name" maxlength="30" required>
                    </div>
                    <div class="mb-2">
                        <label class="form-label">설명</label>
                        <input type="text" class="form-control" name="role_desc" id="edit_role_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="roleDeleteModal" 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_role_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(){
        // ------- 샘플 데이터 -------
        let SEQ = 3;
        const roles = [
            {id:1, name:'최고관리자', desc:'회사 전체 관리권한'},
            {id:2, name:'일반관리자', desc:'부서/사용자/업무 관리'},
            {id:3, name:'일반직원',   desc:'일반 사용 권한'}
        ];

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

        function render(){
            const html = roles.map(r=>`
      <tr data-id="${r.id}">
        <td>${r.id}</td>
        <td>${escapeHtml(r.name)}</td>
        <td>${escapeHtml(r.desc||'')}</td>
        <td>
          <div class="d-flex justify-content-center gap-1">
            <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('');
            $('#roleTbody').html(html);
        }

        // 등록
        $('#btnOpenAdd').on('click', function(){
            $('#roleAddForm')[0].reset();
            new bootstrap.Modal('#roleAddModal').show();
        });
        $('#roleAddForm').on('submit', function(e){
            e.preventDefault();
            const name = $(this).find('[name="role_name"]').val().trim();
            const desc = $(this).find('[name="role_desc"]').val().trim();
            if(name.length<2){ alert('역할명을 2글자 이상 입력하세요.'); return; }
            const id = ++SEQ;
            roles.push({id, name, desc});
            render();
            bootstrap.Modal.getInstance(document.getElementById('roleAddModal')).hide();

            // 실제:
            // $.post('/tenant/tenant/role_add_process.php', {role_name:name, role_desc:desc}).done(()=>location.reload());
        });

        // 수정
        $(document).on('click', '.btn-edit', function(){
            const id = +$(this).data('id');
            const r = roles.find(x=>x.id===id);
            if(!r) return;
            $('#edit_role_id').val(r.id);
            $('#edit_role_name').val(r.name);
            $('#edit_role_desc').val(r.desc||'');
            new bootstrap.Modal('#roleEditModal').show();
        });
        $('#roleEditForm').on('submit', function(e){
            e.preventDefault();
            const id = +$('#edit_role_id').val();
            const name = $('#edit_role_name').val().trim();
            const desc = $('#edit_role_desc').val().trim();
            if(name.length<2){ alert('역할명을 2글자 이상 입력하세요.'); return; }
            const r = roles.find(x=>x.id===id);
            if(!r) return;
            r.name = name; r.desc = desc;
            render();
            bootstrap.Modal.getInstance(document.getElementById('roleEditModal')).hide();

            // 실제:
            // $.post('/tenant/tenant/role_edit_process.php', {role_id:id, role_name:name, role_desc:desc}).done(()=>location.reload());
        });

        // 삭제
        $(document).on('click', '.btn-del', function(){
            const id = +$(this).data('id');
            $('#del_role_id').val(id);
            new bootstrap.Modal('#roleDeleteModal').show();
        });
        $('#btnConfirmDelete').on('click', function(){
            const id = +$('#del_role_id').val();
            const idx = roles.findIndex(x=>x.id===id);
            if(idx>-1) roles.splice(idx,1);
            render();
            bootstrap.Modal.getInstance(document.getElementById('roleDeleteModal')).hide();

            // 실제:
            // location.href = '/tenant/tenant/role_delete.php?id='+id;
        });

        render();
    });
</script>

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