/* ===== tkuser 협력업체 CRUD ===== */
function hasPartnerPermission() {
    if (!currentUser) return false;
    if (['admin', 'system'].includes(currentUser.role)) return true;
    return typeof currentUserAllowedTabs !== 'undefined' && currentUserAllowedTabs.has('partners');
}
function isAdminOnly() {
    return currentUser && ['admin', 'system'].includes(currentUser.role);
}

let partnersLoaded = false;
let partnersList = [];
let partnerWorkersList = [];
let selectedPartnerIdTkuser = null;
let editingWorkerIdTkuser = null;

async function loadPartnersTab() {
    if (partnersLoaded) return;
    partnersLoaded = true;
    if (hasPartnerPermission()) {
        document.getElementById('btnAddPartnerTkuser')?.classList.remove('hidden');
    }
    await loadPartnersList();
}

async function loadPartnersList() {
    try {
        const isActive = document.getElementById('partnerFilterActiveTkuser')?.value;
        const search = document.getElementById('partnerSearchTkuser')?.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('/partners?' + params.toString());
        partnersList = r.data || [];
        renderPartnersListTkuser();
    } catch (e) {
        document.getElementById('partnersListTkuser').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 renderPartnersListTkuser() {
    const c = document.getElementById('partnersListTkuser');
    if (!partnersList.length) {
        c.innerHTML = '<p class="text-gray-400 text-center py-4 text-sm">등록된 협력업체가 없습니다.</p>';
        return;
    }
    const canManage = hasPartnerPermission();
    const isAdmin = isAdminOnly();
    c.innerHTML = partnersList.map(p => {
        const types = tryParseJsonTkuser(p.business_type) || [];
        const typeStr = types.map(t => `<span class="px-1.5 py-0.5 rounded text-xs bg-blue-50 text-blue-600">${escHtml(t)}</span>`).join(' ');
        const insuranceWarn = isInsuranceExpiringSoonTkuser(p.insurance_expiry);
        return `<div class="flex items-center justify-between p-2.5 bg-gray-50 rounded-lg hover:bg-gray-100 transition-colors cursor-pointer ${selectedPartnerIdTkuser === p.id ? 'ring-2 ring-emerald-400' : ''}" onclick="selectPartnerTkuser(${p.id})">
            <div class="flex-1 min-w-0">
                <div class="text-sm font-medium text-gray-800 truncate">
                    <i class="fas fa-building mr-1.5 text-gray-400 text-xs"></i>${escHtml(p.company_name)}
                    ${!p.is_active ? '<span class="px-1.5 py-0.5 rounded text-xs bg-gray-100 text-gray-400 ml-1">비활성</span>' : ''}
                    ${insuranceWarn ? '<span class="px-1.5 py-0.5 rounded text-xs bg-red-50 text-red-600 ml-1"><i class="fas fa-exclamation-triangle mr-0.5"></i>보험만료</span>' : ''}
                </div>
                <div class="text-xs text-gray-500 flex items-center gap-1.5 mt-0.5 flex-wrap">
                    ${p.business_number ? `<span>${p.business_number}</span>` : ''}
                    ${p.representative ? `<span>${escHtml(p.representative)}</span>` : ''}
                    ${typeStr}
                </div>
            </div>
            ${canManage ? `<div class="flex gap-1 ml-2 flex-shrink-0">
                <button onclick="event.stopPropagation(); openEditPartnerTkuser(${p.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>
                ${p.is_active ? `<button onclick="event.stopPropagation(); deactivatePartnerTkuser(${p.id}, '${escHtml(p.company_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>` : ''}
                ${isAdmin ? `<button onclick="event.stopPropagation(); hardDeletePartnerTkuser(${p.id})" class="p-1.5 text-red-300 hover:text-red-600 hover:bg-red-100 rounded" title="완전삭제"><i class="fas fa-trash text-xs"></i></button>` : ''}
            </div>` : ''}
        </div>`;
    }).join('');
}

async function selectPartnerTkuser(id) {
    selectedPartnerIdTkuser = id;
    renderPartnersListTkuser();
    try {
        const r = await api(`/partners/${id}`);
        const p = r.data;
        partnerWorkersList = p.workers || [];
        renderPartnerDetailTkuser(p);
        document.getElementById('partnerDetailTkuser').classList.remove('hidden');
        document.getElementById('partnerEmptyTkuser').classList.add('hidden');
    } catch (e) {
        showToast('상세 조회 실패: ' + e.message, 'error');
    }
}

function renderPartnerDetailTkuser(p) {
    const types = tryParseJsonTkuser(p.business_type) || [];
    const workers = p.workers || [];
    const canManage = hasPartnerPermission();
    const isAdmin = isAdminOnly();
    document.getElementById('partnerDetailTkuser').innerHTML = `
        <div class="bg-white rounded-xl shadow-sm p-5 mb-4">
            <div class="flex items-center justify-between mb-3">
                <h3 class="text-lg font-semibold text-gray-800">${escHtml(p.company_name)}</h3>
                ${isAdmin ? `<button onclick="hardDeletePartnerTkuser(${p.id})" class="px-2.5 py-1 text-xs text-red-400 hover:text-red-600 hover:bg-red-50 rounded border border-red-200" title="완전삭제"><i class="fas fa-trash mr-1"></i>완전삭제</button>` : ''}
            </div>
            <div class="grid grid-cols-2 gap-3 text-sm">
                <div><span class="text-gray-500">사업자번호:</span> <span class="font-medium">${escHtml(p.business_number) || '-'}</span></div>
                <div><span class="text-gray-500">대표자:</span> <span class="font-medium">${escHtml(p.representative) || '-'}</span></div>
                <div><span class="text-gray-500">담당자:</span> <span class="font-medium">${escHtml(p.contact_name) || '-'}</span></div>
                <div><span class="text-gray-500">연락처:</span> <span class="font-medium">${escHtml(p.contact_phone) || '-'}</span></div>
                <div class="col-span-2"><span class="text-gray-500">주소:</span> <span class="font-medium">${escHtml(p.address) || '-'}</span></div>
                <div><span class="text-gray-500">업종:</span> ${types.map(t => `<span class="px-1.5 py-0.5 rounded text-xs bg-blue-50 text-blue-600">${escHtml(t)}</span>`).join(' ') || '-'}</div>
                <div><span class="text-gray-500">산재보험:</span> <span class="font-medium">${escHtml(p.insurance_number) || '-'}</span> ${p.insurance_expiry ? `(만료: ${formatDate(p.insurance_expiry)})` : ''}</div>
                ${p.notes ? `<div class="col-span-2"><span class="text-gray-500">비고:</span> ${escHtml(p.notes)}</div>` : ''}
            </div>
        </div>
        <div class="bg-white rounded-xl shadow-sm p-5">
            <div class="flex items-center justify-between mb-3">
                <h4 class="text-base font-semibold text-gray-800"><i class="fas fa-users text-gray-400 mr-2"></i>소속 작업자 (${workers.length}명)</h4>
                ${canManage ? `<button onclick="openAddWorkerTkuser()" class="px-3 py-1.5 bg-slate-700 text-white rounded-lg text-xs hover:bg-slate-800"><i class="fas fa-user-plus mr-1"></i>작업자 등록</button>` : ''}
            </div>
            ${workers.length ? workers.map(w => `
                <div class="flex items-center justify-between p-2 bg-gray-50 rounded hover:bg-gray-100 mb-1">
                    <div>
                        <span class="text-sm font-medium">${escHtml(w.worker_name)}</span>
                        ${w.is_team_leader ? '<span class="px-1.5 py-0.5 rounded text-xs bg-amber-50 text-amber-600 ml-1">팀장</span>' : ''}
                        ${!w.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="flex items-center gap-2">
                        <div class="text-xs text-gray-500 flex gap-2">
                            ${w.position ? `<span>${escHtml(w.position)}</span>` : ''}
                            ${w.phone ? `<span>${escHtml(w.phone)}</span>` : ''}
                            ${w.safety_training_date ? `<span>안전교육: ${formatDate(w.safety_training_date)}</span>` : ''}
                        </div>
                        ${canManage ? `<div class="flex gap-1 ml-2">
                            <button onclick="openEditWorkerTkuser(${w.id})" class="p-1 text-slate-500 hover:text-slate-700 rounded" title="수정"><i class="fas fa-pen text-xs"></i></button>
                            ${w.is_active ? `<button onclick="deactivateWorkerTkuser(${w.id})" class="p-1 text-red-400 hover:text-red-600 rounded" title="비활성화"><i class="fas fa-ban text-xs"></i></button>` : ''}
                        </div>` : ''}
                    </div>
                </div>`).join('') : '<p class="text-gray-400 text-center py-4 text-sm">등록된 작업자가 없습니다</p>'}
        </div>`;
}

/* ===== 업체 완전삭제 (admin) ===== */
async function hardDeletePartnerTkuser(id) {
    try {
        const r = await api(`/partners/${id}/delete-info`);
        const info = r.data;
        if (info.purchaseRequests > 0 || info.purchases > 0) {
            alert(`"${info.company_name}" 업체는 구매 이력이 있어 삭제할 수 없습니다.\n(구매요청 ${info.purchaseRequests}건, 구매 ${info.purchases}건)\n\n비활성화를 이용해주세요.`);
            return;
        }
        const lines = [];
        if (info.workers > 0) lines.push(`작업자 ${info.workers}명`);
        if (info.schedules > 0) lines.push(`스케줄 ${info.schedules}건`);
        if (info.checkins > 0) lines.push(`출근기록 ${info.checkins}건`);
        if (info.reports > 0) lines.push(`작업보고 ${info.reports}건`);
        if (info.visits > 0) lines.push(`방문기록 ${info.visits}건 (보존, 업체연결 해제)`);
        if (info.accounts > 0) lines.push(`SSO 계정 ${info.accounts}개`);
        const summary = lines.length > 0 ? `\n\n삭제될 데이터:\n- ${lines.join('\n- ')}` : '\n\n관련 데이터가 없습니다.';
        const input = prompt(`"${info.company_name}" 업체를 완전히 삭제합니다.\n이 작업은 되돌릴 수 없습니다.${summary}\n\n계속하려면 "삭제"를 입력하세요:`);
        if (input !== '삭제') {
            if (input !== null) showToast('삭제가 취소되었습니다', 'error');
            return;
        }
        await api(`/partners/${id}/permanent`, { method: 'DELETE' });
        showToast('업체가 완전히 삭제되었습니다');
        await loadPartnersList();
        if (selectedPartnerIdTkuser === id) {
            document.getElementById('partnerDetailTkuser').classList.add('hidden');
            document.getElementById('partnerEmptyTkuser').classList.remove('hidden');
            selectedPartnerIdTkuser = null;
        }
    } catch (e) { showToast(e.message, 'error'); }
}

/* ===== 업체 등록 ===== */
function openAddPartnerTkuser() { document.getElementById('addPartnerModalTkuser').classList.remove('hidden'); }
function closeAddPartnerTkuser() { document.getElementById('addPartnerModalTkuser').classList.add('hidden'); document.getElementById('addPartnerFormTkuser').reset(); }

async function submitAddPartnerTkuser(e) {
    e.preventDefault();
    const typesRaw = document.getElementById('newPartnerBusinessTypeTkuser').value.trim();
    const data = {
        company_name: document.getElementById('newPartnerCompanyNameTkuser').value.trim(),
        business_number: document.getElementById('newPartnerBusinessNumberTkuser').value.trim() || null,
        representative: document.getElementById('newPartnerRepresentativeTkuser').value.trim() || null,
        contact_name: document.getElementById('newPartnerContactNameTkuser').value.trim() || null,
        contact_phone: document.getElementById('newPartnerContactPhoneTkuser').value.trim() || null,
        address: document.getElementById('newPartnerAddressTkuser').value.trim() || null,
        business_type: typesRaw ? typesRaw.split(',').map(s => s.trim()).filter(Boolean) : null,
        insurance_number: document.getElementById('newPartnerInsuranceNumberTkuser').value.trim() || null,
        insurance_expiry: document.getElementById('newPartnerInsuranceExpiryTkuser').value || null,
        notes: document.getElementById('newPartnerNotesTkuser').value.trim() || null,
    };
    if (!data.company_name) { showToast('업체명은 필수입니다', 'error'); return; }
    try {
        await api('/partners', { method: 'POST', body: JSON.stringify(data) });
        showToast('업체가 등록되었습니다');
        closeAddPartnerTkuser();
        await loadPartnersList();
    } catch (e) { showToast(e.message, 'error'); }
}

/* ===== 업체 수정 ===== */
function openEditPartnerTkuser(id) {
    const p = partnersList.find(x => x.id === id);
    if (!p) return;
    const types = tryParseJsonTkuser(p.business_type) || [];
    document.getElementById('editPartnerIdTkuser').value = p.id;
    document.getElementById('editPartnerCompanyNameTkuser').value = p.company_name;
    document.getElementById('editPartnerBusinessNumberTkuser').value = p.business_number || '';
    document.getElementById('editPartnerRepresentativeTkuser').value = p.representative || '';
    document.getElementById('editPartnerContactNameTkuser').value = p.contact_name || '';
    document.getElementById('editPartnerContactPhoneTkuser').value = p.contact_phone || '';
    document.getElementById('editPartnerAddressTkuser').value = p.address || '';
    document.getElementById('editPartnerBusinessTypeTkuser').value = types.join(', ');
    document.getElementById('editPartnerInsuranceNumberTkuser').value = p.insurance_number || '';
    document.getElementById('editPartnerInsuranceExpiryTkuser').value = p.insurance_expiry ? formatDate(p.insurance_expiry) : '';
    document.getElementById('editPartnerNotesTkuser').value = p.notes || '';
    document.getElementById('editPartnerModalTkuser').classList.remove('hidden');
}
function closeEditPartnerTkuser() { document.getElementById('editPartnerModalTkuser').classList.add('hidden'); }

async function submitEditPartnerTkuser(e) {
    e.preventDefault();
    const id = document.getElementById('editPartnerIdTkuser').value;
    const typesRaw = document.getElementById('editPartnerBusinessTypeTkuser').value.trim();
    const data = {
        company_name: document.getElementById('editPartnerCompanyNameTkuser').value.trim(),
        business_number: document.getElementById('editPartnerBusinessNumberTkuser').value.trim() || null,
        representative: document.getElementById('editPartnerRepresentativeTkuser').value.trim() || null,
        contact_name: document.getElementById('editPartnerContactNameTkuser').value.trim() || null,
        contact_phone: document.getElementById('editPartnerContactPhoneTkuser').value.trim() || null,
        address: document.getElementById('editPartnerAddressTkuser').value.trim() || null,
        business_type: typesRaw ? typesRaw.split(',').map(s => s.trim()).filter(Boolean) : null,
        insurance_number: document.getElementById('editPartnerInsuranceNumberTkuser').value.trim() || null,
        insurance_expiry: document.getElementById('editPartnerInsuranceExpiryTkuser').value || null,
        notes: document.getElementById('editPartnerNotesTkuser').value.trim() || null,
    };
    try {
        await api(`/partners/${id}`, { method: 'PUT', body: JSON.stringify(data) });
        showToast('수정되었습니다');
        closeEditPartnerTkuser();
        await loadPartnersList();
        if (selectedPartnerIdTkuser == id) selectPartnerTkuser(id);
    } catch (e) { showToast(e.message, 'error'); }
}

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

/* ===== 작업자 등록 ===== */
function openAddWorkerTkuser() {
    if (!selectedPartnerIdTkuser) { showToast('업체를 먼저 선택해주세요', 'error'); return; }
    document.getElementById('addWorkerModalTkuser').classList.remove('hidden');
}
function closeAddWorkerTkuser() { document.getElementById('addWorkerModalTkuser').classList.add('hidden'); document.getElementById('addWorkerFormTkuser').reset(); }

async function submitAddWorkerTkuser(e) {
    e.preventDefault();
    const data = {
        worker_name: document.getElementById('newWorkerNameTkuser').value.trim(),
        position: document.getElementById('newWorkerPositionTkuser').value.trim() || null,
        is_team_leader: document.getElementById('newWorkerIsLeaderTkuser').checked,
        phone: document.getElementById('newWorkerPhoneTkuser').value.trim() || null,
        safety_training_date: document.getElementById('newWorkerSafetyDateTkuser').value || null,
        notes: document.getElementById('newWorkerNotesTkuser').value.trim() || null,
    };
    if (!data.worker_name) { showToast('작업자명은 필수입니다', 'error'); return; }
    try {
        await api(`/partners/${selectedPartnerIdTkuser}/workers`, { method: 'POST', body: JSON.stringify(data) });
        showToast('작업자가 등록되었습니다');
        closeAddWorkerTkuser();
        await selectPartnerTkuser(selectedPartnerIdTkuser);
    } catch (e) { showToast(e.message, 'error'); }
}

/* ===== 작업자 수정 ===== */
function openEditWorkerTkuser(id) {
    const w = partnerWorkersList.find(x => x.id === id);
    if (!w) return;
    editingWorkerIdTkuser = id;
    document.getElementById('editWorkerNameTkuser').value = w.worker_name;
    document.getElementById('editWorkerPositionTkuser').value = w.position || '';
    document.getElementById('editWorkerIsLeaderTkuser').checked = w.is_team_leader;
    document.getElementById('editWorkerPhoneTkuser').value = w.phone || '';
    document.getElementById('editWorkerSafetyDateTkuser').value = w.safety_training_date ? formatDate(w.safety_training_date) : '';
    document.getElementById('editWorkerNotesTkuser').value = w.notes || '';
    document.getElementById('editWorkerModalTkuser').classList.remove('hidden');
}
function closeEditWorkerTkuser() { document.getElementById('editWorkerModalTkuser').classList.add('hidden'); editingWorkerIdTkuser = null; }

async function submitEditWorkerTkuser(e) {
    e.preventDefault();
    if (!editingWorkerIdTkuser) return;
    const data = {
        worker_name: document.getElementById('editWorkerNameTkuser').value.trim(),
        position: document.getElementById('editWorkerPositionTkuser').value.trim() || null,
        is_team_leader: document.getElementById('editWorkerIsLeaderTkuser').checked,
        phone: document.getElementById('editWorkerPhoneTkuser').value.trim() || null,
        safety_training_date: document.getElementById('editWorkerSafetyDateTkuser').value || null,
        notes: document.getElementById('editWorkerNotesTkuser').value.trim() || null,
    };
    try {
        await api(`/partners/workers/${editingWorkerIdTkuser}`, { method: 'PUT', body: JSON.stringify(data) });
        showToast('수정되었습니다');
        closeEditWorkerTkuser();
        await selectPartnerTkuser(selectedPartnerIdTkuser);
    } catch (e) { showToast(e.message, 'error'); }
}

async function deactivateWorkerTkuser(id) {
    if (!confirm('이 작업자를 비활성화하시겠습니까?')) return;
    try {
        await api(`/partners/workers/${id}`, { method: 'DELETE' });
        showToast('비활성화 완료');
        await selectPartnerTkuser(selectedPartnerIdTkuser);
    } catch (e) { showToast(e.message, 'error'); }
}

function tryParseJsonTkuser(val) {
    if (!val) return null;
    if (Array.isArray(val)) return val;
    try { return JSON.parse(val); } catch { return null; }
}

function isInsuranceExpiringSoonTkuser(expiry) {
    if (!expiry) return false;
    const exp = new Date(expiry);
    const now = new Date();
    const diff = (exp - now) / (1000 * 60 * 60 * 24);
    return diff <= 30 && diff >= 0;
}

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

    document.getElementById('addPartnerFormTkuser')?.addEventListener('submit', submitAddPartnerTkuser);
    document.getElementById('editPartnerFormTkuser')?.addEventListener('submit', submitEditPartnerTkuser);
    document.getElementById('addWorkerFormTkuser')?.addEventListener('submit', submitAddWorkerTkuser);
    document.getElementById('editWorkerFormTkuser')?.addEventListener('submit', submitEditWorkerTkuser);
});
