@extends('layouts.app')

@section('title', '사업소득자 임금대장')

@section('content')
<div class="px-4 py-6">
    {{-- 페이지 헤더 --}}
    <div class="flex flex-col lg:flex-row lg:justify-between lg:items-center gap-4 mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">사업소득자 임금대장</h1>
            <div class="flex items-center gap-2 mt-1">
                <select id="bipYear" class="px-2 py-1 border border-gray-300 rounded text-sm text-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        onchange="refreshBIP()">
                    @for($y = now()->year; $y >= now()->year - 2; $y--)
                        <option value="{{ $y }}" {{ $year == $y ? 'selected' : '' }}>{{ $y }}년</option>
                    @endfor
                </select>
                <select id="bipMonth" class="px-2 py-1 border border-gray-300 rounded text-sm text-gray-600 focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                        onchange="refreshBIP()">
                    @for($m = 1; $m <= 12; $m++)
                        <option value="{{ $m }}" {{ $month == $m ? 'selected' : '' }}>{{ $m }}월</option>
                    @endfor
                </select>
                <span class="text-sm text-gray-400 ml-1">소득세 3% + 지방소득세 0.3%</span>
            </div>
        </div>
        <div class="flex flex-wrap items-center gap-2 sm:gap-3">
            <button type="button" onclick="exportBIP()"
                    class="inline-flex items-center gap-2 px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-white text-sm font-medium rounded-lg transition-colors">
                <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>
                엑셀 내보내기
            </button>
            <button type="button" onclick="saveBIP()"
                    id="bipSaveBtn"
                    class="inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white text-sm font-medium rounded-lg transition-colors">
                <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="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"/>
                </svg>
                일괄 저장
            </button>
        </div>
    </div>

    {{-- 통계 카드 --}}
    <div id="bipStatsContainer" class="mb-6">
        @include('hr.business-income-payments.partials.stats', ['stats' => $stats])
    </div>

    {{-- 스프레드시트 --}}
    <div class="bg-white rounded-lg shadow-sm overflow-hidden">
        <div id="bipSpreadsheet">
            @include('hr.business-income-payments.partials.spreadsheet', [
                'payments' => $payments,
                'earnersForJs' => $earnersForJs,
                'year' => $year,
                'month' => $month,
            ])
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
// =========================================================================
// Money Input 유틸리티
// =========================================================================
function formatMoneyInput(el) {
    const pos = el.selectionStart;
    const oldLen = el.value.length;
    const isNeg = el.value.indexOf('-') === 0;
    const raw = el.value.replace(/[^0-9]/g, '');
    const num = parseInt(raw, 10);
    if (isNaN(num)) { el.value = isNeg ? '-' : ''; return; }
    el.value = (isNeg ? '-' : '') + num.toLocaleString('ko-KR');
    const newLen = el.value.length;
    el.setSelectionRange(Math.max(0, pos + (newLen - oldLen)), Math.max(0, pos + (newLen - oldLen)));
}

function moneyFocus(el) { if (parseMoneyValue(el) === 0) el.value = ''; }
function moneyBlur(el) { if (el.value.trim() === '') el.value = '0'; calcRow(el); }

function parseMoneyValue(el) {
    if (typeof el === 'string') return parseFloat(el.replace(/,/g, '')) || 0;
    return parseFloat((el.value || '').replace(/,/g, '')) || 0;
}

function fmtNum(n) {
    return Number(Math.round(n)).toLocaleString('ko-KR');
}

// =========================================================================
// 행 자동 계산 (지급총액 → 소득세/지방소득세/공제합계/실지급액)
// =========================================================================
function calcRow(el) {
    const row = el.closest('tr.bip-row');
    if (!row) return;

    const gross = parseMoneyValue(row.querySelector('[name="gross_amount"]'));
    const incomeTax = Math.floor(gross * 0.03 / 10) * 10;
    const localTax = Math.floor(gross * 0.003 / 10) * 10;
    const totalDed = incomeTax + localTax;
    const net = Math.max(0, gross - totalDed);

    row.querySelector('.bip-income-tax').textContent = fmtNum(incomeTax);
    row.querySelector('.bip-local-tax').textContent = fmtNum(localTax);
    row.querySelector('.bip-total-ded').textContent = fmtNum(totalDed);
    row.querySelector('.bip-net').textContent = fmtNum(net);

    updateFooterSums();
}

function updateFooterSums() {
    let sumGross = 0, sumIT = 0, sumLT = 0, sumDed = 0, sumNet = 0;
    document.querySelectorAll('#bipTable tbody tr.bip-row').forEach(row => {
        const g = parseMoneyValue(row.querySelector('[name="gross_amount"]'));
        sumGross += g;
        sumIT += Math.floor(g * 0.03 / 10) * 10;
        sumLT += Math.floor(g * 0.003 / 10) * 10;
    });
    sumDed = sumIT + sumLT;
    sumNet = Math.max(0, sumGross - sumDed);

    const el = id => document.getElementById(id);
    if (el('bipSumGross'))    el('bipSumGross').textContent = fmtNum(sumGross);
    if (el('bipSumIncomeTax'))el('bipSumIncomeTax').textContent = fmtNum(sumIT);
    if (el('bipSumLocalTax')) el('bipSumLocalTax').textContent = fmtNum(sumLT);
    if (el('bipSumDed'))      el('bipSumDed').textContent = fmtNum(sumDed);
    if (el('bipSumNet'))      el('bipSumNet').textContent = fmtNum(sumNet);
}

// =========================================================================
// 행 추가/삭제/번호 재정렬
// =========================================================================
function addBipRow() {
    const tbody = document.getElementById('bipTbody');
    const rowCount = tbody.querySelectorAll('tr.bip-row').length;
    const num = rowCount + 1;

    const tr = document.createElement('tr');
    tr.className = 'hover:bg-gray-50 transition-colors bip-row';
    tr.dataset.paymentId = '';
    tr.dataset.userId = '';

    tr.innerHTML = `
        <td class="px-3 py-2 text-center text-sm text-gray-500 bip-row-num">${num}</td>
        <td class="px-3 py-2">
            <input type="text" name="display_name" list="bipEarnerDatalist" value="" placeholder="상호/성명"
                   oninput="onEarnerInput(this)" onchange="onEarnerSelect(this)"
                   class="w-full px-2 py-1 border border-gray-200 rounded text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                   style="min-width: 120px;">
        </td>
        <td class="px-3 py-2">
            <input type="text" name="business_reg_number" value="" placeholder="사업자등록번호"
                   class="w-full px-2 py-1 border border-gray-200 rounded text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                   style="min-width: 110px;">
        </td>
        <td class="px-3 py-2">
            <input type="text" name="service_content" value="" placeholder="용역내용"
                   class="w-full px-2 py-1 border border-gray-200 rounded text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                   style="min-width: 120px;">
        </td>
        <td class="px-3 py-2">
            <input type="text" name="gross_amount" inputmode="numeric" value="0"
                   oninput="formatMoneyInput(this); calcRow(this)" onfocus="moneyFocus(this)" onblur="moneyBlur(this)"
                   class="w-full px-2 py-1 border border-gray-200 rounded text-sm text-right money-input focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                   style="min-width: 100px;">
        </td>
        <td class="px-3 py-2 text-right text-sm text-red-600 bg-red-50/30 bip-income-tax">0</td>
        <td class="px-3 py-2 text-right text-sm text-red-600 bg-red-50/30 bip-local-tax">0</td>
        <td class="px-3 py-2 text-right text-sm font-medium text-red-700 bg-red-50/30 bip-total-ded">0</td>
        <td class="px-3 py-2 text-right text-sm font-medium text-emerald-700 bg-emerald-50/30 bip-net">0</td>
        <td class="px-3 py-2">
            <input type="date" name="payment_date" value=""
                   class="w-full px-2 py-1 border border-gray-200 rounded text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                   style="min-width: 110px;">
        </td>
        <td class="px-3 py-2">
            <input type="text" name="note" value="" placeholder="비고"
                   class="w-full px-2 py-1 border border-gray-200 rounded text-sm focus:ring-1 focus:ring-blue-500 focus:border-blue-500"
                   style="min-width: 80px;">
        </td>
        <td class="px-3 py-2 text-center">
            <button type="button" onclick="removeBipRow(this)"
                    class="text-red-400 hover:text-red-600 transition-colors" title="행 삭제">
                <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="M6 18L18 6M6 6l12 12"/>
                </svg>
            </button>
        </td>
    `;

    tbody.appendChild(tr);
    tr.querySelector('[name="display_name"]').focus();
}

function removeBipRow(el) {
    const row = el.closest('tr.bip-row');
    if (!row) return;
    row.remove();
    renumberBipRows();
    updateFooterSums();
}

function renumberBipRows() {
    document.querySelectorAll('#bipTbody tr.bip-row').forEach((row, idx) => {
        const numCell = row.querySelector('.bip-row-num');
        if (numCell) {
            const badge = numCell.querySelector('span');
            const num = document.createTextNode(idx + 1);
            numCell.textContent = '';
            numCell.appendChild(num);
            if (badge) numCell.appendChild(badge);
        }
    });
}

// =========================================================================
// datalist 선택 → user_id + 사업자등록번호 자동 채움
// =========================================================================
function onEarnerInput(input) {
    const row = input.closest('tr.bip-row');
    if (!row) return;
    row.dataset.userId = '';
}

function onEarnerSelect(input) {
    const row = input.closest('tr.bip-row');
    if (!row) return;

    const val = input.value.trim();
    const earners = window.__bipEarners || [];

    const match = earners.find(e =>
        e.business_name === val || e.user_name === val
    );

    if (match) {
        row.dataset.userId = match.user_id;
        const regInput = row.querySelector('[name="business_reg_number"]');
        if (regInput) regInput.value = match.business_reg_number || '';
    } else {
        row.dataset.userId = '';
    }
}

// =========================================================================
// 연월 변경 → HTMX 갱신
// =========================================================================
function refreshBIP() {
    const year = document.getElementById('bipYear').value;
    const month = document.getElementById('bipMonth').value;

    fetch(`{{ route('api.admin.hr.business-income-payments.index') }}?year=${year}&month=${month}`, {
        headers: {
            'HX-Request': 'true',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
        }
    })
    .then(r => r.text())
    .then(html => {
        const parts = html.split('<!-- SPLIT -->');
        if (parts.length === 2) {
            document.getElementById('bipStatsContainer').innerHTML = parts[0];
            document.getElementById('bipSpreadsheet').innerHTML = parts[1];

            // script 태그 수동 실행 (innerHTML로 삽입된 script는 실행되지 않음)
            document.getElementById('bipSpreadsheet').querySelectorAll('script').forEach(oldScript => {
                const newScript = document.createElement('script');
                newScript.textContent = oldScript.textContent;
                oldScript.parentNode.replaceChild(newScript, oldScript);
            });
        }
    });
}

// =========================================================================
// 일괄 저장
// =========================================================================
function saveBIP() {
    const btn = document.getElementById('bipSaveBtn');
    const origText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<svg class="w-4 h-4 animate-spin" fill="none" viewBox="0 0 24 24"><circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle><path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z"></path></svg> 저장중...';

    const year = document.getElementById('bipYear').value;
    const month = document.getElementById('bipMonth').value;
    const items = [];
    const seenUserIds = new Set();
    let hasDuplicate = false;

    document.querySelectorAll('#bipTbody tr.bip-row').forEach(row => {
        const grossEl = row.querySelector('[name="gross_amount"]');

        // locked (confirmed/paid) 행은 건너뜀
        if (grossEl && grossEl.disabled) return;

        const displayNameEl = row.querySelector('[name="display_name"]');
        const displayName = displayNameEl?.value?.trim() || '';

        // display_name이 비어있으면 건너뜀 (빈 행)
        if (!displayName) return;

        const userId = row.dataset.userId ? parseInt(row.dataset.userId) : null;

        // 동일 earner 중복 체크
        if (userId) {
            if (seenUserIds.has(userId)) hasDuplicate = true;
            seenUserIds.add(userId);
        }

        items.push({
            payment_id: row.dataset.paymentId ? parseInt(row.dataset.paymentId) : null,
            user_id: userId,
            display_name: displayName,
            business_reg_number: row.querySelector('[name="business_reg_number"]')?.value || '',
            gross_amount: parseMoneyValue(grossEl),
            service_content: row.querySelector('[name="service_content"]')?.value || '',
            payment_date: row.querySelector('[name="payment_date"]')?.value || '',
            note: row.querySelector('[name="note"]')?.value || '',
        });
    });

    if (hasDuplicate && !confirm('동일한 사업소득자가 중복 입력되어 있습니다. 그래도 저장하시겠습니까?')) {
        btn.disabled = false;
        btn.innerHTML = origText;
        return;
    }

    if (items.length === 0) {
        if (!confirm('모든 행이 삭제되었습니다. 저장하면 해당 월의 임시저장 데이터가 모두 삭제됩니다. 계속하시겠습니까?')) {
            btn.disabled = false;
            btn.innerHTML = origText;
            return;
        }
    }

    fetch('{{ route("api.admin.hr.business-income-payments.bulk-save") }}', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content,
        },
        body: JSON.stringify({ year: parseInt(year), month: parseInt(month), items }),
    })
    .then(r => r.json())
    .then(result => {
        btn.disabled = false;
        btn.innerHTML = origText;
        if (result.success) {
            showToast(result.message, 'success');
            refreshBIP();
        } else {
            showToast(result.message || '저장 실패', 'error');
        }
    })
    .catch(err => {
        btn.disabled = false;
        btn.innerHTML = origText;
        showToast('네트워크 오류', 'error');
    });
}

// =========================================================================
// 엑셀 내보내기
// =========================================================================
function exportBIP() {
    const year = document.getElementById('bipYear').value;
    const month = document.getElementById('bipMonth').value;
    window.location.href = `{{ route('api.admin.hr.business-income-payments.export') }}?year=${year}&month=${month}`;
}

// =========================================================================
// 토스트 (전역 showToast가 없을 때 대비)
// =========================================================================
if (typeof showToast === 'undefined') {
    window.showToast = function(msg, type) {
        const div = document.createElement('div');
        div.className = `fixed top-4 right-4 z-50 px-4 py-3 rounded-lg shadow-lg text-white text-sm ${type === 'error' ? 'bg-red-600' : 'bg-emerald-600'}`;
        div.textContent = msg;
        document.body.appendChild(div);
        setTimeout(() => div.remove(), 3000);
    };
}
</script>
@endpush
