/* ===== tkuser 업체(공급업체) CRUD ===== */
let vendorsLoaded = false;
let vendorsList = [];
let selectedVendorIdTkuser = null;

async function loadVendorsTab() {
    if (vendorsLoaded) return;
    vendorsLoaded = true;
    if (currentUser && ['admin', 'system'].includes(currentUser.role)) {
        document.getElementById('btnAddVendorTkuser')?.classList.remove('hidden');
    }
    await loadVendorsList();
}

async function loadVendorsList() {
    try {
        const isActive = document.getElementById('vendorFilterActiveTkuser')?.value;
        const search = document.getElementById('vendorSearchTkuser')?.value?.trim() || '';
        const params = new URLSearchParams();
        if (isActive !== '' && isActive !== undefined) params.set('is_active', isActive);
        if (search) params.set('search', search);
        const r = await api('/vendors?' + params.toString());
        vendorsList = r.data || [];
        renderVendorsListTkuser();
    } catch (e) {
        document.getElementById('vendorsListTkuser').innerHTML = `<div class="text-red-500 text-center py-6"><i class="fas fa-exclamation-triangle text-xl"></i><p class="text-sm mt-2">${e.message}</p></div>`;
    }
}

function renderVendorsListTkuser() {
    const c = document.getElementById('vendorsListTkuser');
    if (!vendorsList.length) {
        c.innerHTML = '<p class="text-gray-400 text-center py-4 text-sm">등록된 업체가 없습니다.</p>';
        return;
    }
    const isAdmin = currentUser && ['admin', 'system'].includes(currentUser.role);
    c.innerHTML = vendorsList.map(v => {
        return `<div class="flex items-center justify-between p-2.5 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer ${selectedVendorIdTkuser === v.vendor_id ? 'ring-2 ring-indigo-400' : ''}" onclick="selectVendorTkuser(${v.vendor_id})">
            <div class="flex-1 min-w-0">
                <div class="text-sm font-medium text-gray-800 truncate">
                    <i class="fas fa-store mr-1.5 text-gray-400 text-xs"></i>${escHtml(v.vendor_name)}
                    ${!v.is_active ? '<span class="px-1.5 py-0.5 rounded text-xs bg-gray-100 text-gray-400 ml-1">비활성</span>' : ''}
                </div>
                <div class="text-xs text-gray-500 flex items-center gap-1.5 mt-0.5">
                    ${v.business_number ? `<span>${escHtml(v.business_number)}</span>` : ''}
                    ${v.contact_name ? `<span>${escHtml(v.contact_name)}</span>` : ''}
                </div>
            </div>
            ${isAdmin ? `<div class="flex gap-1 ml-2 flex-shrink-0">
                <button onclick="event.stopPropagation(); openEditVendorTkuser(${v.vendor_id})" class="p-1.5 text-slate-500 hover:text-slate-700 hover:bg-slate-200 rounded" title="수정"><i class="fas fa-pen text-xs"></i></button>
                ${v.is_active ? `<button onclick="event.stopPropagation(); deactivateVendorTkuser(${v.vendor_id}, '${escHtml(v.vendor_name).replace(/'/g, "\\'")}')" class="p-1.5 text-red-400 hover:text-red-600 hover:bg-red-100 rounded" title="비활성화"><i class="fas fa-ban text-xs"></i></button>` : ''}
            </div>` : ''}
        </div>`;
    }).join('');
}

async function selectVendorTkuser(id) {
    selectedVendorIdTkuser = id;
    renderVendorsListTkuser();
    try {
        const r = await api(`/vendors/${id}`);
        const v = r.data;
        renderVendorDetailTkuser(v);
        document.getElementById('vendorDetailTkuser').classList.remove('hidden');
        document.getElementById('vendorEmptyTkuser').classList.add('hidden');
    } catch (e) {
        showToast('상세 조회 실패: ' + e.message, 'error');
    }
}

function renderVendorDetailTkuser(v) {
    document.getElementById('vendorDetailTkuser').innerHTML = `
        <div class="bg-white rounded-xl shadow-sm p-5">
            <h3 class="text-lg font-semibold text-gray-800 mb-3">${escHtml(v.vendor_name)}</h3>
            <div class="grid grid-cols-2 gap-3 text-sm">
                <div><span class="text-gray-500">사업자번호:</span> <span class="font-medium">${escHtml(v.business_number) || '-'}</span></div>
                <div><span class="text-gray-500">대표자:</span> <span class="font-medium">${escHtml(v.representative) || '-'}</span></div>
                <div><span class="text-gray-500">담당자:</span> <span class="font-medium">${escHtml(v.contact_name) || '-'}</span></div>
                <div><span class="text-gray-500">연락처:</span> <span class="font-medium">${escHtml(v.contact_phone) || '-'}</span></div>
                <div class="col-span-2"><span class="text-gray-500">주소:</span> <span class="font-medium">${escHtml(v.address) || '-'}</span></div>
                <div><span class="text-gray-500">은행:</span> <span class="font-medium">${escHtml(v.bank_name) || '-'}</span></div>
                <div><span class="text-gray-500">계좌번호:</span> <span class="font-medium">${escHtml(v.bank_account) || '-'}</span></div>
                ${v.notes ? `<div class="col-span-2"><span class="text-gray-500">비고:</span> ${escHtml(v.notes)}</div>` : ''}
            </div>
        </div>`;
}

/* ===== 업체 등록 ===== */
function openAddVendorTkuser() { document.getElementById('addVendorModalTkuser').classList.remove('hidden'); }
function closeAddVendorTkuser() { document.getElementById('addVendorModalTkuser').classList.add('hidden'); document.getElementById('addVendorFormTkuser').reset(); }

async function submitAddVendorTkuser(e) {
    e.preventDefault();
    const data = {
        vendor_name: document.getElementById('newVendorNameTkuser').value.trim(),
        business_number: document.getElementById('newVendorBizNumTkuser').value.trim() || null,
        representative: document.getElementById('newVendorRepTkuser').value.trim() || null,
        contact_name: document.getElementById('newVendorContactNameTkuser').value.trim() || null,
        contact_phone: document.getElementById('newVendorContactPhoneTkuser').value.trim() || null,
        address: document.getElementById('newVendorAddressTkuser').value.trim() || null,
        bank_name: document.getElementById('newVendorBankNameTkuser').value.trim() || null,
        bank_account: document.getElementById('newVendorBankAccountTkuser').value.trim() || null,
        notes: document.getElementById('newVendorNotesTkuser').value.trim() || null,
    };
    if (!data.vendor_name) { showToast('업체명은 필수입니다', 'error'); return; }
    try {
        await api('/vendors', { method: 'POST', body: JSON.stringify(data) });
        showToast('업체가 등록되었습니다');
        closeAddVendorTkuser();
        await loadVendorsList();
    } catch (e) { showToast(e.message, 'error'); }
}

/* ===== 업체 수정 ===== */
function openEditVendorTkuser(id) {
    const v = vendorsList.find(x => x.vendor_id === id);
    if (!v) return;
    document.getElementById('editVendorIdTkuser').value = v.vendor_id;
    document.getElementById('editVendorNameTkuser').value = v.vendor_name;
    document.getElementById('editVendorBizNumTkuser').value = v.business_number || '';
    document.getElementById('editVendorRepTkuser').value = v.representative || '';
    document.getElementById('editVendorContactNameTkuser').value = v.contact_name || '';
    document.getElementById('editVendorContactPhoneTkuser').value = v.contact_phone || '';
    document.getElementById('editVendorAddressTkuser').value = v.address || '';
    document.getElementById('editVendorBankNameTkuser').value = v.bank_name || '';
    document.getElementById('editVendorBankAccountTkuser').value = v.bank_account || '';
    document.getElementById('editVendorNotesTkuser').value = v.notes || '';
    document.getElementById('editVendorModalTkuser').classList.remove('hidden');
}
function closeEditVendorTkuser() { document.getElementById('editVendorModalTkuser').classList.add('hidden'); }

async function submitEditVendorTkuser(e) {
    e.preventDefault();
    const id = document.getElementById('editVendorIdTkuser').value;
    const data = {
        vendor_name: document.getElementById('editVendorNameTkuser').value.trim(),
        business_number: document.getElementById('editVendorBizNumTkuser').value.trim() || null,
        representative: document.getElementById('editVendorRepTkuser').value.trim() || null,
        contact_name: document.getElementById('editVendorContactNameTkuser').value.trim() || null,
        contact_phone: document.getElementById('editVendorContactPhoneTkuser').value.trim() || null,
        address: document.getElementById('editVendorAddressTkuser').value.trim() || null,
        bank_name: document.getElementById('editVendorBankNameTkuser').value.trim() || null,
        bank_account: document.getElementById('editVendorBankAccountTkuser').value.trim() || null,
        notes: document.getElementById('editVendorNotesTkuser').value.trim() || null,
    };
    try {
        await api(`/vendors/${id}`, { method: 'PUT', body: JSON.stringify(data) });
        showToast('수정되었습니다');
        closeEditVendorTkuser();
        await loadVendorsList();
        if (selectedVendorIdTkuser == id) selectVendorTkuser(id);
    } catch (e) { showToast(e.message, 'error'); }
}

/* ===== 업체 비활성화 ===== */
async function deactivateVendorTkuser(id, name) {
    if (!confirm(`"${name}" 업체를 비활성화하시겠습니까?`)) return;
    try {
        await api(`/vendors/${id}`, { method: 'DELETE' });
        showToast('비활성화 완료');
        await loadVendorsList();
        if (selectedVendorIdTkuser === id) {
            document.getElementById('vendorDetailTkuser').classList.add('hidden');
            document.getElementById('vendorEmptyTkuser').classList.remove('hidden');
            selectedVendorIdTkuser = null;
        }
    } catch (e) { showToast(e.message, 'error'); }
}

// 검색/필터 이벤트 + 모달 폼 이벤트
document.addEventListener('DOMContentLoaded', () => {
    let searchTimeout;
    const searchEl = document.getElementById('vendorSearchTkuser');
    if (searchEl) searchEl.addEventListener('input', () => {
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(loadVendorsList, 300);
    });
    const filterEl = document.getElementById('vendorFilterActiveTkuser');
    if (filterEl) filterEl.addEventListener('change', loadVendorsList);

    document.getElementById('addVendorFormTkuser')?.addEventListener('submit', submitAddVendorTkuser);
    document.getElementById('editVendorFormTkuser')?.addEventListener('submit', submitEditVendorTkuser);
});
