@extends('layouts.app')

@section('title', '참조함')

@section('content')
    <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-6">
        <h1 class="text-2xl font-bold text-gray-800">참조함</h1>
    </div>

    {{-- 미열람/열람 필터 탭 --}}
    <div class="flex gap-1 mb-4">
        <button onclick="setReadFilter('')" id="tab-all"
                class="px-4 py-2 rounded-lg text-sm font-medium transition bg-blue-600 text-white">
            전체
        </button>
        <button onclick="setReadFilter('false')" id="tab-unread"
                class="px-4 py-2 rounded-lg text-sm font-medium transition bg-gray-100 text-gray-700 hover:bg-gray-200">
            미열람
            <span id="unread-badge" class="ml-1 inline-flex items-center justify-center px-1.5 py-0.5 rounded-full text-xs bg-red-500 text-white" style="display:none;"></span>
        </button>
        <button onclick="setReadFilter('true')" id="tab-read"
                class="px-4 py-2 rounded-lg text-sm font-medium transition bg-gray-100 text-gray-700 hover:bg-gray-200">
            열람완료
        </button>
    </div>

    <x-filter-collapsible id="filterForm">
        <form id="filterForm" class="flex flex-wrap gap-2 sm:gap-4">
            <input type="hidden" name="is_read" id="is_read_filter" value="">
            <div class="flex-1 min-w-0 w-full sm:w-auto">
                <input type="text" name="search" placeholder="제목, 문서번호 검색..."
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
            <button type="submit" class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-2 rounded-lg transition w-full sm:w-auto">
                검색
            </button>
        </form>
    </x-filter-collapsible>

    <!-- 테이블 상단 (선택삭제 + 페이지 사이즈) -->
    <div class="flex items-center justify-between mb-2">
        <div>
            <button id="bulkDeleteBtn" onclick="bulkDelete()" class="hidden bg-red-500 hover:bg-red-600 text-white px-4 py-1.5 rounded-lg text-sm font-medium transition">
                선택삭제 (<span id="selectedCount">0</span>건)
            </button>
        </div>
        <div class="flex items-center gap-2 text-sm text-gray-600">
            <span>페이지당</span>
            <select id="perPageSelect" onchange="loadReferences(1)" class="px-2 py-1 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
                <option value="15" selected>15</option>
                <option value="50">50</option>
                <option value="100">100</option>
                <option value="200">200</option>
                <option value="500">500</option>
            </select>
            <span>건</span>
        </div>
    </div>

    <div id="approval-table" class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div class="flex justify-center items-center p-12">
            <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        </div>
    </div>

    <div id="pagination-area" class="mt-4"></div>
@endsection

@push('scripts')
<script>
const isSuperAdmin = @json(auth()->user()->isSuperAdmin());
const userId = {{ auth()->id() }};
let currentReadFilter = '';
let selectedIds = new Set();

document.addEventListener('DOMContentLoaded', function() {
    loadReferences();
    loadUnreadCount();
    document.getElementById('filterForm').addEventListener('submit', function(e) {
        e.preventDefault();
        loadReferences();
    });
});

function setReadFilter(value) {
    currentReadFilter = value;
    document.getElementById('is_read_filter').value = value;

    ['tab-all', 'tab-unread', 'tab-read'].forEach(id => {
        const el = document.getElementById(id);
        el.className = 'px-4 py-2 rounded-lg text-sm font-medium transition bg-gray-100 text-gray-700 hover:bg-gray-200';
    });
    const activeTab = value === '' ? 'tab-all' : (value === 'false' ? 'tab-unread' : 'tab-read');
    document.getElementById(activeTab).className = 'px-4 py-2 rounded-lg text-sm font-medium transition bg-blue-600 text-white';

    loadReferences();
}

function loadUnreadCount() {
    fetch('/api/admin/approvals/badge-counts', {
        headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' }
    })
    .then(r => r.json())
    .then(data => {
        const count = data.data?.reference_unread || 0;
        const badge = document.getElementById('unread-badge');
        if (count > 0) { badge.textContent = count; badge.style.display = 'inline-flex'; }
    })
    .catch(() => {});
}

function loadReferences(page = 1) {
    selectedIds.clear();
    updateBulkDeleteBtn();

    const form = document.getElementById('filterForm');
    const params = new URLSearchParams(new FormData(form));
    params.set('page', page);
    params.set('per_page', document.getElementById('perPageSelect').value);

    fetch(`/api/admin/approvals/references?${params}`, {
        headers: { 'Accept': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' }
    })
    .then(r => r.json())
    .then(data => renderTable(data.data || [], data))
    .catch(() => {
        document.getElementById('approval-table').innerHTML = '<div class="p-8 text-center text-gray-500">데이터를 불러올 수 없습니다.</div>';
    });
}

function toggleSelectAll(checkbox) {
    const checkboxes = document.querySelectorAll('.row-checkbox');
    checkboxes.forEach(cb => {
        cb.checked = checkbox.checked;
        const id = parseInt(cb.value);
        if (checkbox.checked) selectedIds.add(id); else selectedIds.delete(id);
    });
    updateBulkDeleteBtn();
}

function toggleRowCheckbox(checkbox) {
    const id = parseInt(checkbox.value);
    if (checkbox.checked) selectedIds.add(id); else selectedIds.delete(id);
    const allCb = document.getElementById('selectAllCheckbox');
    const rowCbs = document.querySelectorAll('.row-checkbox');
    if (allCb) allCb.checked = rowCbs.length > 0 && [...rowCbs].every(cb => cb.checked);
    updateBulkDeleteBtn();
}

function updateBulkDeleteBtn() {
    const btn = document.getElementById('bulkDeleteBtn');
    const count = document.getElementById('selectedCount');
    if (selectedIds.size > 0) { btn.classList.remove('hidden'); count.textContent = selectedIds.size; }
    else { btn.classList.add('hidden'); }
}

function bulkDelete() {
    if (selectedIds.size === 0) return;
    if (!confirm(`선택한 ${selectedIds.size}건의 문서를 삭제하시겠습니까?`)) return;

    fetch('/api/admin/approvals/bulk-delete', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', 'X-CSRF-TOKEN': '{{ csrf_token() }}' },
        body: JSON.stringify({ ids: [...selectedIds] }),
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) { if (typeof showToast === 'function') showToast(data.message, 'success'); loadReferences(); }
        else { if (typeof showToast === 'function') showToast(data.message || '삭제 실패', 'error'); }
    })
    .catch(() => { if (typeof showToast === 'function') showToast('삭제 중 오류가 발생했습니다.', 'error'); });
}

function escapeHtml(str) {
    if (!str) return '';
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
}

function renderTable(items, pagination) {
    const container = document.getElementById('approval-table');

    if (!items.length) {
        container.innerHTML = '<div class="p-8 text-center text-gray-500">참조된 결재 문서가 없습니다.</div>';
        document.getElementById('pagination-area').innerHTML = '';
        return;
    }

    const statusBadge = (status) => {
        const map = {
            draft: '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-700">임시저장</span>',
            pending: '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-700">진행</span>',
            approved: '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-700">완료</span>',
            rejected: '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-700">반려</span>',
            cancelled: '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-700">회수</span>',
            on_hold: '<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-amber-100 text-amber-700">보류</span>',
        };
        return map[status] || status;
    };

    let html = `<div class="overflow-x-auto">
        <table class="min-w-full divide-y divide-gray-200">
            <thead class="bg-gray-50">
                <tr>
                    <th class="px-2 py-3 text-center" style="width: 40px;">
                        <input type="checkbox" id="selectAllCheckbox" onchange="toggleSelectAll(this)" class="w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500">
                    </th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">문서번호</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">제목</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">기안자</th>
                    <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">상태</th>
                    <th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">열람</th>
                    <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">기안일</th>
                    ${isSuperAdmin ? '<th class="px-4 py-3 text-center text-xs font-medium text-gray-500 uppercase">관리</th>' : ''}
                </tr>
            </thead>
            <tbody class="bg-white divide-y divide-gray-200">`;

    items.forEach(item => {
        const draftedAt = item.drafted_at ? new Date(item.drafted_at).toLocaleDateString('ko-KR') : (item.created_at ? new Date(item.created_at).toLocaleDateString('ko-KR') : '-');

        const refStep = (item.steps || []).find(s => s.step_type === 'reference' && s.approver_id === userId);
        const isRead = refStep?.is_read;
        const readBadge = isRead
            ? '<span class="text-xs text-green-600">열람</span>'
            : '<span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-600">미열람</span>';
        const rowBold = isRead ? '' : 'font-bold';

        html += `<tr class="hover:bg-gray-50 cursor-pointer ${rowBold}" onclick="goToApproval(${item.id})">
            <td class="px-2 py-3 text-center" onclick="event.stopPropagation();">
                <input type="checkbox" class="row-checkbox w-4 h-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500" value="${item.id}" onchange="toggleRowCheckbox(this)">
            </td>
            <td class="px-4 py-3 text-sm text-gray-600 whitespace-nowrap">${item.document_number || '-'}</td>
            <td class="px-4 py-3 text-sm text-gray-800">${item.title || '-'}</td>
            <td class="px-4 py-3 text-sm text-gray-600">${item.drafter?.name || '-'}</td>
            <td class="px-4 py-3 text-center">${statusBadge(item.status)}</td>
            <td class="px-4 py-3 text-center">${readBadge}</td>
            <td class="px-4 py-3 text-sm text-gray-500 whitespace-nowrap">${draftedAt}</td>
            ${isSuperAdmin ? `<td class="px-4 py-3 text-center"><button onclick="event.stopPropagation(); confirmForceDelete(${item.id}, '${escapeHtml(item.title)}')" class="text-xs text-red-500 hover:text-red-700 font-medium whitespace-nowrap">영구삭제</button></td>` : ''}
        </tr>`;
    });

    html += '</tbody></table></div>';
    container.innerHTML = html;

    const area = document.getElementById('pagination-area');
    if (!pagination.last_page || pagination.last_page <= 1) { area.innerHTML = ''; return; }
    let pHtml = '<div class="flex justify-center gap-1">';
    for (let i = 1; i <= pagination.last_page; i++) {
        const active = i === pagination.current_page ? 'bg-blue-600 text-white' : 'bg-white text-gray-700 hover:bg-gray-100';
        pHtml += `<button onclick="loadReferences(${i})" class="px-3 py-1 rounded border text-sm ${active}">${i}</button>`;
    }
    pHtml += '</div>';
    area.innerHTML = pHtml;
}

async function goToApproval(id) {
    try {
        await fetch(`/api/admin/approvals/${id}/mark-read`, {
            method: 'POST',
            headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' },
        });
    } catch (e) {}
    location.href = '/approval-mgmt/' + id;
}

function confirmForceDelete(id, title) {
    if (!confirm(`"${title}" 문서를 영구삭제하시겠습니까?\n\n이 작업은 되돌릴 수 없습니다.`)) return;

    fetch(`/api/admin/approvals/${id}/force`, {
        method: 'DELETE',
        headers: { 'X-CSRF-TOKEN': '{{ csrf_token() }}', 'Accept': 'application/json' }
    })
    .then(r => r.json())
    .then(data => {
        if (data.success) { showToast(data.message, 'success'); loadReferences(); }
        else { showToast(data.message, 'error'); }
    });
}
</script>
@endpush
