<?php
// 섹션-서브메뉴 정의 (링크는 네가 쓰는 경로에 맞춰두었어)
$NAV = [
    'item' => [
        'title' => '품목',
        'items' => [
            ['라벨' => '품목관리', 'href' => '/tenant/material/list.php'],
            ['라벨' => 'BOM 단품(기초 바람시)', 'href' => '/tenant/product//bending.php'],
            ['라벨' => 'BOM 결합 상품', 'href' => '/tenant/product/bom_combined.php'],
            ['라벨' => '제품 단가', 'href' => '/tenant/product/product_price.php'],
            ['라벨' => '코드 및 로트 관리', 'href' => '/tenant/product/code_lot.php'],
        ],
    ],
    'order' => [
        'title' => '수주',
        'items' => [
            ['라벨' => '견적 관리', 'href' => '/tenant/order/estimate.php'],
            ['라벨' => '수주 관리', 'href' => '/tenant/order/manage.php'],
            ['라벨' => '수주 등록/수정', 'href' => '/tenant/order/edit.php'],
            ['라벨' => '상태 관리', 'href' => '/tenant/order/status.php'],
        ],
    ],
    'process' => [
        'title' => '생산',
        'items' => [
            ['라벨' => '공정관리', 'href' => '/tenant/process/processes.php'],
            ['라벨' => '작업관리', 'href' => '/tenant/process/tasks.php'],
            ['라벨' => '작업지시 설정', 'href' => '/tenant/process/process_settings.php'],
            ['라벨' => '스크린 작업', 'href' => '/tenant/production/screen_work.php'],
            ['라벨' => '슬랫 작업', 'href' => '/tenant/production/screen_work.php'],
            ['라벨' => '절곡 작업', 'href' => '/tenant/production/screen_work.php'],
        ],
    ],
    'shipment' => [
        'title' => '출고',
        'items' => [
            ['라벨' => '출고 현황 조회', 'href' => '/tenant/shipment/status.php'],
            ['라벨' => '월간 출고 일정', 'href' => '/tenant/shipment/monthly_schedule.php'],
        ],
    ],
    'quality' => [
        'title' => '품질',
        'items' => [
            ['라벨' => '제품 검사 요청', 'href' => '/tenant/quality/request.php'],
            ['라벨' => '제품 검사 일정', 'href' => '/tenant/quality/schedule.php'],
            ['라벨' => '품질 인정 실적 대장', 'href' => '/tenant/quality/record.php'],
            ['라벨' => '인정서류 자료실', 'href' => '/tenant/quality/docs.php'],
        ],
    ],
    'inventory' => [
        'title' => '재고',
        'items' => [
            ['라벨' => '재고 조회', 'href' => '/tenant/inventory/stock.php'],
            ['라벨' => '수입 검사 대장', 'href' => '/tenant/material/inspection_list.php'],
            ['라벨' => '입고 현황', 'href' => '/tenant/material/inventory_status.php'],
            ['라벨' => '부적합품 관리', 'href' => '/tenant/inventory/defective.php'],
        ],
    ],
    'subscription' => [
        'title' => '구독',
        'items' => [
            ['라벨' => '구독 하기', 'href' => '/tenant/tenant/subscribe.php'],
            ['라벨' => '구독 관리', 'href' => '/tenant/subscription/list.php'],
            ['라벨' => '회사 조회', 'href' => '/tenant/subscription/tenant_list.php'],
            ['라벨' => '상품별 회사 리스트', 'href' => '/tenant/subscription/tenant_product_list.php'],
        ],
    ],
    'member' => [
        'title' => '회원',
        'items' => [
            ['라벨' => '가입', 'href' => '/tenant/member/register.php'],
            ['라벨' => '회사 선택', 'href' => '/tenant/member/tenant_select.php'],
            ['라벨' => '내정보 수정', 'href' => '/tenant/member/profile_edit.php'],
            ['라벨' => '탈퇴', 'href' => '/tenant/member/withdraw.php'],
            ['라벨' => '회원가입 컬럼설정', 'href' => '/tenant/settings/member_fields.php'],
        ],
    ],
    'permission' => [
        'title' => '메뉴/권한',
        'items' => [
            ['라벨' => '메뉴 관리', 'href' => '/tenant/permission/tenant_menu.php'],
            ['라벨' => '부서 권한 설정', 'href' => '/tenant/permission/department.php'],
            ['라벨' => '역할 권한 설정', 'href' => '/tenant/permission/role.php'],
            ['라벨' => '유저 권한 설정', 'href' => '/tenant/permission/user.php'],
            ['라벨' => '권한 분석', 'href' => '/tenant/permission/analyze.php'],
        ],
    ],
    'approval' => [
        'title' => '결재(승인)',
        'items' => [
            ['라벨' => '결재 대상 관리', 'href' => '/tenant/approval/objects.php'],
            ['라벨' => '결재 규칙/결재선 관리', 'href' => '/tenant/approval/rules.php'],
            ['라벨' => '결재권자 관리', 'href' => '/tenant/approval/pool.php'],
            ['라벨' => '결재 현황 조회', 'href' => '/tenant/approval/instances.php'],
        ],
    ],
    'tenant' => [
        'title' => '회사',
        'items' => [
            ['라벨' => '회사 가입', 'href' => '/tenant/tenant/join.php'],
            ['라벨' => '수정', 'href' => '/tenant/tenant/edit.php'],
            ['라벨' => '탈퇴', 'href' => '/tenant/tenant/withdraw.php'],
            ['라벨' => '카테고리 관리', 'href' => '/tenant/category/category_list.php'],
            ['라벨' => '분류 관리', 'href' => '/tenant/category/subcategory_list.php'],
            ['라벨' => '부서 관리', 'href' => '/tenant/tenant/department_list.php'],
            ['라벨' => '역할 관리', 'href' => '/tenant/tenant/role_list.php'],
            ['라벨' => '유저 관리', 'href' => '/tenant/tenant/user_list.php'],
            ['라벨' => '옵션 관리', 'href' => '/tenant/tenant/option.php'],
        ],
    ],
];

// ② 1뎁스가 없는 화면에서 노출할 "기본 2뎁스"
$NAV_ROOT = [
    'title' => '기본',
    'items' => [
        ['라벨' => '인트로', 'href' => '/tenant/member/intro.php'],
        ['라벨' => '대시보드', 'href' => '/tenant/member/dashboard.php'],
    ],
];

// ③ 현재 경로/섹션 파악
$currentPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$hasSection = isset($CURRENT_SECTION, $NAV[$CURRENT_SECTION]);

// ④ JS/초기 렌더에 사용할 "초기 섹션" (없으면 root 사용)
$INITIAL_SECTION = $hasSection ? $CURRENT_SECTION : 'root';

// ⑤ JS로 넘길 NAV(+root)
$NAV_JS = $NAV;
$NAV_JS['root'] = $NAV_ROOT;
?>


<div id="navArea"><!-- 마우스가 이 영역(1뎁스+2뎁스)을 떠나면 복귀 -->

    <!-- 1뎁스 -->
    <nav class="navbar navbar-expand-lg navbar-dark" style="background-color:#2c4a85;">
        <div class="container" style="max-width:1280px;">
            <a class="navbar-brand" href="/tenant/">(주)경동기업</a>
            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#mainNav">
                <span class="navbar-toggler-icon"></span>
            </button>

            <div class="collapse navbar-collapse" id="mainNav">
                <ul class="navbar-nav me-auto mb-2 mb-lg-0">
                    <?php foreach ($NAV as $key => $conf) { // root는 1뎁스에 출력하지 않음?>
                        <li class="nav-item">
                            <a href="#"
                               class="nav-link top-link <?= ($hasSection && $CURRENT_SECTION === $key) ? 'active' : '' ?>"
                               data-section="<?= $key ?>">
                                <?= htmlspecialchars($conf['title']) ?>
                            </a>
                        </li>
                    <?php } ?>
                </ul>
                <!-- 우측 로그인/로그아웃 영역은 그대로 -->
            </div>
        </div>
    </nav>

    <!-- 2뎁스 -->
    <div class="subnav-wrapper" style="background:#e9f0fb;border-bottom:1px solid #d5deef;">
        <div class="container" style="max-width:1280px;">
            <ul id="subnav" class="subnav list-unstyled d-flex flex-wrap gap-3 m-0 py-2">
                <?php
                $INIT_ITEMS = ($INITIAL_SECTION === 'root') ? $NAV_ROOT['items'] : $NAV[$INITIAL_SECTION]['items'];
foreach ($INIT_ITEMS as $item) {
    $activeClass = ($currentPath === $item['href']) ? 'active' : '';
    ?>
                    <li><a class="subnav-link <?= $activeClass ?>" href="<?= $item['href'] ?>"><?= htmlspecialchars($item['라벨']) ?></a></li>
                <?php } ?>
            </ul>
        </div>
    </div>

</div><!-- /#navArea -->

<style>
    .navbar .nav-link.active{background:rgba(255,255,255,.15);border-radius:.375rem}
    .navbar .top-link{cursor:default}
    .navbar .top-link:hover{background:rgba(255,255,255,.10);border-radius:.375rem}
    .subnav-link{display:inline-block;padding:.35rem .6rem;border-radius:.35rem;color:#2c3e67;text-decoration:none}
    .subnav-link:hover{background:#dbe7ff;text-decoration:none}
    .subnav-link.active{font-weight:700;text-decoration:underline}
</style>

<script>
    $(function(){
        const NAV = <?= json_encode($NAV_JS, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
        const INITIAL_SECTION = '<?= $INITIAL_SECTION ?>'; // 'root' 또는 실제 섹션 키
        const $subnav = $('#subnav');

        const esc = s => String(s)
            .replace(/&/g,'&amp;').replace(/</g,'&lt;')
            .replace(/>/g,'&gt;').replace(/"/g,'&quot;').replace(/'/g,'&#39;');

        // 현재 섹션 렌더
        function renderSection(sectionKey){
            if (!NAV[sectionKey]) return;
            // 1뎁스 active 표시 (root일 땐 모두 해제)
            $('.top-link').removeClass('active');
            if (sectionKey !== 'root') {
                $(`.top-link[data-section="${sectionKey}"]`).addClass('active');
            }
            // 2뎁스 갱신
            const path = location.pathname.replace(/\/+$/,'');
            const items = NAV[sectionKey].items || [];
            const html = items.map(it=>{
                const href = String(it.href||'');
                const isActive = (href.replace(/\/+$/,'') === path);
                return `<li><a class="subnav-link ${isActive?'active':''}" href="${esc(href)}">${esc(it['라벨'])}</a></li>`;
            }).join('');
            $subnav.html(html);
        }

        // 1뎁스: 마우스오버/포커스 → 2뎁스만 교체 (이동 없음)
        $(document).on('mouseenter', '.top-link', function(){
            renderSection($(this).data('section'));
        });
        $(document).on('focusin', '.top-link', function(){
            renderSection($(this).data('section'));
        });

        // 네비 영역(1뎁스+2뎁스)을 벗어나면 원래 섹션으로 복귀
        $('#navArea').on('mouseleave', function(){
            renderSection(INITIAL_SECTION);
        });

        // 필요 시 최초 렌더 보정 (서버에서 이미 렌더했지만 JS도 상태 기억)
        renderSection(INITIAL_SECTION);
    });
</script>
