@extends('layouts.app')

@section('title', '권한 분석')

@section('content')
    <!-- 페이지 헤더 -->
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800">권한 분석</h1>
        <div class="flex items-center gap-2">
            <button
                type="button"
                class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                hx-post="/api/admin/permission-analyze/recalculate"
                hx-swap="none"
                onclick="showToast('권한이 재계산되었습니다.', 'success')"
            >
                <span class="flex items-center gap-1">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
                    </svg>
                    권한 재계산
                </span>
            </button>
            <button
                type="button"
                id="exportCsvBtn"
                class="px-4 py-2 bg-green-600 text-white text-sm font-medium rounded-lg hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-green-500 disabled:bg-gray-400 disabled:cursor-not-allowed"
                onclick="exportCsv()"
                disabled
            >
                <span class="flex items-center gap-1">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                    CSV 내보내기
                </span>
            </button>
        </div>
    </div>

    <!-- 필터 영역 -->
    <div class="bg-white rounded-lg shadow-sm p-4 mb-6">
        <div class="flex items-center gap-4">
            <!-- 권한 유형 선택 -->
            <div class="flex items-center gap-2">
                <label class="text-sm font-medium text-gray-700">권한 유형:</label>
                <select
                    id="permissionType"
                    name="permission_type"
                    class="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                    onchange="onPermissionTypeChange()"
                >
                    @foreach($permissionTypes as $type)
                        <option value="{{ $type }}">{{ ucfirst($type) }}</option>
                    @endforeach
                </select>
            </div>

            <!-- 권한 규칙 표시 -->
            <div class="flex-1 text-right">
                <span class="text-xs text-gray-500 bg-gray-100 px-3 py-1 rounded-full">
                    권한 규칙: ALLOW = 부서 OR 역할 OR (개인 ALLOW) → 개인 DENY 최우선
                </span>
            </div>
        </div>
    </div>

    <!-- 2단 레이아웃 (고정 높이, 좌우 분할) -->
    <div class="flex gap-6" style="height: calc(100vh - 220px);">
        <!-- 좌측: 메뉴 트리 (50%) -->
        <div class="w-1/2">
            <div class="bg-white rounded-lg shadow-sm h-full flex flex-col">
                <div class="px-4 py-3 border-b border-gray-200">
                    <h2 class="text-lg font-semibold text-gray-800 mb-3">메뉴 트리</h2>
                    <!-- 검색 -->
                    <input
                        type="text"
                        id="menuSearch"
                        placeholder="메뉴 검색..."
                        class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
                        onkeyup="searchMenu(this.value)"
                    >
                </div>
                <div id="menu-tree" class="p-2 flex-1 overflow-y-auto">
                    @include('permission-analyze.partials.menu-tree', ['menuTree' => $menuTree])
                </div>
            </div>
        </div>

        <!-- 우측: 분석 결과 (50%) -->
        <div class="w-1/2 min-w-0">
            <div class="bg-white rounded-lg shadow-sm h-full flex flex-col w-full">
                <div class="px-4 py-3 border-b border-gray-200">
                    <h2 class="text-lg font-semibold text-gray-800" id="selectedMenuTitle">선택된 메뉴</h2>
                </div>

                <!-- 탭 메뉴 -->
                <div class="border-b border-gray-200 flex-shrink-0">
                    <nav class="flex -mb-px" id="analysisTabs">
                        <button
                            type="button"
                            class="tab-button px-4 py-3 text-sm font-medium border-b-2 border-blue-500 text-blue-600"
                            data-tab="access-allowed"
                            onclick="switchTab('access-allowed')"
                        >
                            접근 가능
                        </button>
                        <button
                            type="button"
                            class="tab-button px-4 py-3 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                            data-tab="explicit-deny"
                            onclick="switchTab('explicit-deny')"
                        >
                            명시적 DENY
                        </button>
                        <button
                            type="button"
                            class="tab-button px-4 py-3 text-sm font-medium border-b-2 border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300"
                            data-tab="trace"
                            onclick="switchTab('trace')"
                        >
                            사용자 역추적
                        </button>
                    </nav>
                </div>

                <!-- 탭 콘텐츠 -->
                <div id="analysis-content" class="p-4 flex-1 overflow-y-auto">
                    <div class="text-center py-12 text-gray-500">
                        <svg class="w-16 h-16 mx-auto mb-4 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                        </svg>
                        <p>좌측에서 분석할 메뉴를 선택해주세요.</p>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <input type="hidden" id="selectedMenuId" value="">
@endsection

@push('scripts')
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<script>
    let currentTab = 'access-allowed';

    // 메뉴 선택
    function selectMenu(menuId, menuName) {
        // 모든 메뉴 항목의 선택 상태 제거
        document.querySelectorAll('.menu-item').forEach(item => {
            item.classList.remove('bg-blue-100', 'border-blue-500');
            item.classList.add('hover:bg-gray-50');
        });

        // 선택된 메뉴 항목 활성화
        const selectedItem = document.querySelector(`[data-menu-id="${menuId}"]`);
        if (selectedItem) {
            selectedItem.classList.add('bg-blue-100', 'border-blue-500');
            selectedItem.classList.remove('hover:bg-gray-50');
        }

        // 상태 저장
        document.getElementById('selectedMenuId').value = menuId;
        document.getElementById('selectedMenuTitle').textContent = menuName;

        // CSV 버튼 활성화
        document.getElementById('exportCsvBtn').disabled = false;

        // 분석 결과 로드
        loadAnalysis();
    }

    // 분석 결과 로드
    function loadAnalysis() {
        const menuId = document.getElementById('selectedMenuId').value;
        const permissionType = document.getElementById('permissionType').value;

        if (!menuId) return;

        if (currentTab === 'trace') {
            loadTrace();
        } else {
            fetch(`/api/admin/permission-analyze/analyze?menu_id=${menuId}&permission_type=${permissionType}&tab=${currentTab}`, {
                headers: {
                    'HX-Request': 'true',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.html) {
                    document.getElementById('analysis-content').innerHTML = data.html;
                    // 탭 콘텐츠 표시/숨김 처리
                    showCurrentTabContent();
                }
            });
        }
    }

    // 현재 탭 콘텐츠 표시
    function showCurrentTabContent() {
        document.querySelectorAll('[id^="tab-"]').forEach(tab => {
            tab.classList.add('hidden');
        });
        const tabContent = document.getElementById('tab-' + currentTab);
        if (tabContent) {
            tabContent.classList.remove('hidden');
        }
    }

    // 역추적 결과 로드
    function loadTrace() {
        const menuId = document.getElementById('selectedMenuId').value;
        const permissionType = document.getElementById('permissionType').value;

        if (!menuId) return;

        fetch(`/api/admin/permission-analyze/trace?menu_id=${menuId}&permission_type=${permissionType}`, {
            headers: {
                'HX-Request': 'true',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.html) {
                document.getElementById('analysis-content').innerHTML = data.html;
            }
        });
    }

    // 탭 전환
    function switchTab(tab) {
        currentTab = tab;

        // 탭 버튼 스타일 변경
        document.querySelectorAll('.tab-button').forEach(btn => {
            btn.classList.remove('border-blue-500', 'text-blue-600');
            btn.classList.add('border-transparent', 'text-gray-500');
        });

        const activeBtn = document.querySelector(`[data-tab="${tab}"]`);
        if (activeBtn) {
            activeBtn.classList.remove('border-transparent', 'text-gray-500');
            activeBtn.classList.add('border-blue-500', 'text-blue-600');
        }

        // 분석 결과 로드
        loadAnalysis();
    }

    // 권한 유형 변경
    function onPermissionTypeChange() {
        loadAnalysis();
    }

    // 메뉴 검색
    let searchTimeout;
    function searchMenu(query) {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(() => {
            const items = document.querySelectorAll('.menu-item');
            items.forEach(item => {
                const name = item.getAttribute('data-menu-name').toLowerCase();
                if (query === '' || name.includes(query.toLowerCase())) {
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                }
            });
        }, 300);
    }

    // CSV 내보내기
    function exportCsv() {
        const menuId = document.getElementById('selectedMenuId').value;
        const permissionType = document.getElementById('permissionType').value;

        if (!menuId) {
            showToast('메뉴를 선택해주세요.', 'warning');
            return;
        }

        window.location.href = `/api/admin/permission-analyze/export-csv?menu_id=${menuId}&permission_type=${permissionType}`;
    }

    // HTMX 응답 처리
    document.body.addEventListener('htmx:afterSwap', function(event) {
        if (event.detail.target.id === 'menu-tree') {
            const response = JSON.parse(event.detail.xhr.response);
            if (response.html) {
                event.detail.target.innerHTML = response.html;
            }
        }
    });
</script>
<script src="{{ asset('js/menu-tree.js') }}"></script>
@endpush