@extends('layouts.app')

@section('title', '전자세금계산서')

@section('content')
<div class="flex flex-col h-full">
    <div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">전자세금계산서</h1>
            <p class="text-sm text-gray-500 mt-1">전자세금계산서 발행</p>
        </div>
        <div class="flex gap-2">
            <button type="button" class="px-4 py-2 bg-gray-500 text-white text-sm font-medium rounded-lg hover:bg-gray-600 transition-colors">
                목록
            </button>
            <button type="submit" form="tax-invoice-form" class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors">
                발행
            </button>
        </div>
    </div>

    <form id="tax-invoice-form" class="space-y-6">
        {{-- 공급자 / 공급받는자 영역 --}}
        <div class="bg-white rounded-lg shadow overflow-hidden">
            <div class="grid grid-cols-1 lg:grid-cols-2">
                {{-- 공급자 (왼쪽 - 분홍색) --}}
                <div class="border-r border-gray-200">
                    <table class="w-full text-sm">
                        <tbody>
                            {{-- 등록번호 / 종사업장 --}}
                            <tr class="border-b border-gray-200">
                                <td class="w-20 px-3 py-2 bg-red-100 text-red-700 font-medium text-center border-r border-gray-200 align-middle" rowspan="7">
                                    <span class="writing-mode-vertical">공급자</span>
                                </td>
                                <td class="w-20 px-3 py-2 bg-red-50 text-red-600 font-medium text-center border-r border-gray-200">등록번호</td>
                                <td class="px-3 py-2 border-r border-gray-200">
                                    <input type="text" name="supplier_business_number" value="664-86-03713" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" readonly>
                                </td>
                                <td class="w-20 px-3 py-2 bg-red-50 text-red-600 font-medium text-center border-r border-gray-200">종사업장</td>
                                <td class="px-3 py-2 w-20">
                                    <input type="text" name="supplier_sub_business" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                            </tr>
                            {{-- 상호 / 성명 --}}
                            <tr class="border-b border-gray-200">
                                <td class="px-3 py-2 bg-red-50 text-red-600 font-medium text-center border-r border-gray-200">상호</td>
                                <td class="px-3 py-2 border-r border-gray-200">
                                    <input type="text" name="supplier_company_name" value="(주)코드브릿지엑스" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" readonly>
                                </td>
                                <td class="px-3 py-2 bg-red-50 text-red-600 font-medium text-center border-r border-gray-200">성명</td>
                                <td class="px-3 py-2">
                                    <input type="text" name="supplier_ceo_name" value="이의찬" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" readonly>
                                </td>
                            </tr>
                            {{-- 사업장주소 --}}
                            <tr class="border-b border-gray-200">
                                <td class="px-3 py-2 bg-red-50 text-red-600 font-medium text-center border-r border-gray-200">사업장<br>주소</td>
                                <td colspan="3" class="px-3 py-2">
                                    <input type="text" name="supplier_address" value="서울 강서구 양천로 583 (염창동, 우림블루나인비즈니스센터)B동 1602호" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" readonly>
                                </td>
                            </tr>
                            {{-- 업태 / 종목 --}}
                            <tr class="border-b border-gray-200">
                                <td class="px-3 py-2 bg-red-50 text-red-600 font-medium text-center border-r border-gray-200">업태</td>
                                <td class="px-3 py-2 border-r border-gray-200">
                                    <input type="text" name="supplier_business_type" value="정보통신업" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" readonly>
                                </td>
                                <td class="px-3 py-2 bg-red-50 text-red-600 font-medium text-center border-r border-gray-200">종목</td>
                                <td class="px-3 py-2">
                                    <input type="text" name="supplier_business_item" value="스마트 자동화ERP시스템 개발 및 공급업" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent" readonly>
                                </td>
                            </tr>
                            {{-- 담당자 / 연락처 --}}
                            <tr class="border-b border-gray-200">
                                <td class="px-3 py-2 bg-red-50 text-red-600 font-medium text-center border-r border-gray-200">담당자</td>
                                <td class="px-3 py-2 border-r border-gray-200">
                                    <input type="text" name="supplier_contact_name" value="전진선" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                                <td class="px-3 py-2 bg-red-50 text-red-600 font-medium text-center border-r border-gray-200">연락처</td>
                                <td class="px-3 py-2">
                                    <input type="text" name="supplier_contact_phone" value="02-6347-0005" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                            </tr>
                            {{-- 이메일 --}}
                            <tr>
                                <td class="px-3 py-2 bg-red-50 text-red-600 font-medium text-center border-r border-gray-200">이메일</td>
                                <td colspan="3" class="px-3 py-2">
                                    <input type="email" name="supplier_email" value="admin@codebridge-x.com" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>

                {{-- 공급받는자 (오른쪽 - 파란색) --}}
                <div>
                    <table class="w-full text-sm">
                        <tbody>
                            {{-- 등록번호 / 종사업장 --}}
                            <tr class="border-b border-gray-200">
                                <td class="w-20 px-3 py-2 bg-blue-100 text-blue-700 font-medium text-center border-r border-gray-200 align-middle" rowspan="7">
                                    <span class="writing-mode-vertical">공급받는자</span>
                                </td>
                                <td class="w-20 px-3 py-2 bg-blue-50 text-blue-600 font-medium text-center border-r border-gray-200">등록번호</td>
                                <td class="px-3 py-2 border-r border-gray-200">
                                    <div class="flex gap-1">
                                        <input type="text" name="buyer_business_number" placeholder="000-00-00000" class="flex-1 px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                        <button type="button" onclick="searchBuyer()" class="px-3 py-1 bg-blue-500 text-white text-xs font-medium rounded hover:bg-blue-600 transition-colors whitespace-nowrap">
                                            검색
                                        </button>
                                    </div>
                                </td>
                                <td class="w-20 px-3 py-2 bg-blue-50 text-blue-600 font-medium text-center border-r border-gray-200">종사업장</td>
                                <td class="px-3 py-2 w-20">
                                    <input type="text" name="buyer_sub_business" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                            </tr>
                            {{-- 상호 / 성명 --}}
                            <tr class="border-b border-gray-200">
                                <td class="px-3 py-2 bg-blue-50 text-blue-600 font-medium text-center border-r border-gray-200">상호</td>
                                <td class="px-3 py-2 border-r border-gray-200">
                                    <input type="text" name="buyer_company_name" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                                <td class="px-3 py-2 bg-blue-50 text-blue-600 font-medium text-center border-r border-gray-200">성명</td>
                                <td class="px-3 py-2">
                                    <input type="text" name="buyer_ceo_name" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                            </tr>
                            {{-- 사업장주소 --}}
                            <tr class="border-b border-gray-200">
                                <td class="px-3 py-2 bg-blue-50 text-blue-600 font-medium text-center border-r border-gray-200">사업장<br>주소</td>
                                <td colspan="3" class="px-3 py-2">
                                    <input type="text" name="buyer_address" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                            </tr>
                            {{-- 업태 / 종목 --}}
                            <tr class="border-b border-gray-200">
                                <td class="px-3 py-2 bg-blue-50 text-blue-600 font-medium text-center border-r border-gray-200">업태</td>
                                <td class="px-3 py-2 border-r border-gray-200">
                                    <input type="text" name="buyer_business_type" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                                <td class="px-3 py-2 bg-blue-50 text-blue-600 font-medium text-center border-r border-gray-200">종목</td>
                                <td class="px-3 py-2">
                                    <input type="text" name="buyer_business_item" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                            </tr>
                            {{-- 담당자 / 연락처 --}}
                            <tr class="border-b border-gray-200">
                                <td class="px-3 py-2 bg-blue-50 text-blue-600 font-medium text-center border-r border-gray-200">담당자</td>
                                <td class="px-3 py-2 border-r border-gray-200">
                                    <input type="text" name="buyer_contact_name" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                                <td class="px-3 py-2 bg-blue-50 text-blue-600 font-medium text-center border-r border-gray-200">연락처</td>
                                <td class="px-3 py-2">
                                    <input type="text" name="buyer_contact_phone" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                            </tr>
                            {{-- 이메일 --}}
                            <tr>
                                <td class="px-3 py-2 bg-blue-50 text-blue-600 font-medium text-center border-r border-gray-200">
                                    <div class="flex items-center justify-center gap-1">
                                        <svg class="w-4 h-4 text-blue-400" fill="currentColor" viewBox="0 0 20 20">
                                            <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-3a1 1 0 00-.867.5 1 1 0 11-1.731-1A3 3 0 0113 8a3.001 3.001 0 01-2 2.83V11a1 1 0 11-2 0v-1a1 1 0 011-1 1 1 0 100-2zm0 8a1 1 0 100-2 1 1 0 000 2z" clip-rule="evenodd" />
                                        </svg>
                                        이메일
                                    </div>
                                </td>
                                <td colspan="3" class="px-3 py-2">
                                    <input type="email" name="buyer_email" placeholder="세금계산서 수신 이메일" class="w-full px-2 py-1 border border-gray-300 rounded text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>

        {{-- 세금계산서 상세 영역 (추후 구현) --}}
        <div class="bg-white rounded-lg shadow p-6">
            <div class="text-center text-gray-500">
                <p>세금계산서 품목 및 금액 입력 영역</p>
                <p class="text-sm mt-1">(추후 구현 예정)</p>
            </div>
        </div>
    </form>
</div>

<style>
    .writing-mode-vertical {
        writing-mode: vertical-rl;
        text-orientation: upright;
        letter-spacing: 0.1em;
    }
</style>

{{-- 거래처 검색 모달 --}}
<div id="partner-search-modal" class="fixed inset-0 z-50 hidden">
    <div class="fixed inset-0 bg-black/50" onclick="closePartnerModal()"></div>
    <div class="fixed inset-0 flex items-center justify-center p-4">
        <div class="bg-white rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] flex flex-col" onclick="event.stopPropagation()">
            {{-- 모달 헤더 --}}
            <div class="flex items-center justify-between px-6 py-4 border-b">
                <h3 class="text-lg font-semibold text-gray-800">거래처 검색</h3>
                <button type="button" onclick="closePartnerModal()" class="text-gray-400 hover:text-gray-600">
                    <svg class="w-5 h-5" 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>
            </div>

            {{-- 검색 입력 --}}
            <div class="px-6 py-3 border-b bg-gray-50">
                <div class="flex gap-2">
                    <input type="text" id="partner-search-input"
                           placeholder="상호명, 사업자번호, 담당자명으로 검색"
                           class="flex-1 px-3 py-2 border border-gray-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                           onkeydown="if(event.key==='Enter'){event.preventDefault();searchPartners();}">
                    <button type="button" onclick="searchPartners()"
                            class="px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors">
                        검색
                    </button>
                </div>
            </div>

            {{-- 검색 결과 --}}
            <div class="flex-1 overflow-y-auto px-6 py-3">
                <div id="partner-search-loading" class="hidden text-center py-8">
                    <svg class="animate-spin h-8 w-8 text-blue-500 mx-auto" xmlns="http://www.w3.org/2000/svg" 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 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                    <p class="text-sm text-gray-500 mt-2">검색 중...</p>
                </div>

                <div id="partner-search-empty" class="text-center py-8">
                    <svg class="w-12 h-12 text-gray-300 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/>
                    </svg>
                    <p class="text-sm text-gray-500 mt-2">상호명, 사업자번호 또는 담당자명으로 검색하세요</p>
                </div>

                <div id="partner-search-no-result" class="hidden text-center py-8">
                    <svg class="w-12 h-12 text-gray-300 mx-auto" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M12 2a10 10 0 100 20 10 10 0 000-20z"/>
                    </svg>
                    <p class="text-sm text-gray-500 mt-2">검색 결과가 없습니다</p>
                </div>

                <table id="partner-search-results" class="hidden w-full text-sm">
                    <thead class="bg-gray-50 sticky top-0">
                        <tr>
                            <th class="px-3 py-2 text-left font-medium text-gray-600 border-b">상호명</th>
                            <th class="px-3 py-2 text-left font-medium text-gray-600 border-b">사업자번호</th>
                            <th class="px-3 py-2 text-left font-medium text-gray-600 border-b">담당자</th>
                            <th class="px-3 py-2 text-left font-medium text-gray-600 border-b">이메일</th>
                            <th class="px-3 py-2 text-center font-medium text-gray-600 border-b w-16">선택</th>
                        </tr>
                    </thead>
                    <tbody id="partner-search-tbody"></tbody>
                </table>
            </div>

            {{-- 모달 푸터 --}}
            <div class="px-6 py-3 border-t bg-gray-50 text-right">
                <button type="button" onclick="closePartnerModal()"
                        class="px-4 py-2 text-sm font-medium text-gray-700 bg-white border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors">
                    닫기
                </button>
            </div>
        </div>
    </div>
</div>

<script>
function searchBuyer() {
    openPartnerModal();
}

function openPartnerModal() {
    const modal = document.getElementById('partner-search-modal');
    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';

    setTimeout(() => {
        document.getElementById('partner-search-input').focus();
    }, 100);

    // 사업자번호가 이미 입력되어 있으면 자동 검색
    const bizNo = document.querySelector('input[name="buyer_business_number"]').value.trim();
    if (bizNo) {
        document.getElementById('partner-search-input').value = bizNo;
        searchPartners();
    }
}

function closePartnerModal() {
    const modal = document.getElementById('partner-search-modal');
    modal.classList.add('hidden');
    document.body.style.overflow = '';
}

async function searchPartners() {
    const keyword = document.getElementById('partner-search-input').value.trim();

    const loading = document.getElementById('partner-search-loading');
    const empty = document.getElementById('partner-search-empty');
    const noResult = document.getElementById('partner-search-no-result');
    const resultsTable = document.getElementById('partner-search-results');
    const tbody = document.getElementById('partner-search-tbody');

    // 상태 초기화
    empty.classList.add('hidden');
    noResult.classList.add('hidden');
    resultsTable.classList.add('hidden');
    loading.classList.remove('hidden');

    try {
        const params = new URLSearchParams({ keyword });
        const response = await fetch(`{{ route('barobill.tax-invoice.search-partners') }}?${params}`);
        const data = await response.json();

        loading.classList.add('hidden');

        if (data.length === 0) {
            noResult.classList.remove('hidden');
            return;
        }

        tbody.innerHTML = '';
        data.forEach(partner => {
            const tr = document.createElement('tr');
            tr.className = 'hover:bg-blue-50 border-b border-gray-100 cursor-pointer';
            tr.onclick = () => selectPartner(partner);
            tr.innerHTML = `
                <td class="px-3 py-2 font-medium text-gray-800">${escapeHtml(partner.name)}</td>
                <td class="px-3 py-2 text-gray-600">${escapeHtml(formatBizNo(partner.biz_no || ''))}</td>
                <td class="px-3 py-2 text-gray-600">${escapeHtml(partner.manager || '-')}</td>
                <td class="px-3 py-2 text-gray-600">${escapeHtml(partner.email || '-')}</td>
                <td class="px-3 py-2 text-center">
                    <button type="button" class="px-2 py-1 bg-blue-500 text-white text-xs rounded hover:bg-blue-600 transition-colors"
                            onclick="event.stopPropagation(); selectPartner(${escapeAttr(JSON.stringify(partner))})">
                        선택
                    </button>
                </td>
            `;
            tbody.appendChild(tr);
        });

        resultsTable.classList.remove('hidden');
    } catch (error) {
        loading.classList.add('hidden');
        empty.classList.remove('hidden');
        console.error('거래처 검색 오류:', error);
    }
}

function selectPartner(partner) {
    // 사업자번호 포맷팅 (000-00-00000)
    const bizNo = formatBizNo(partner.biz_no || '');

    document.querySelector('input[name="buyer_business_number"]').value = bizNo;
    document.querySelector('input[name="buyer_company_name"]').value = partner.name || '';
    document.querySelector('input[name="buyer_contact_name"]').value = partner.manager || '';
    document.querySelector('input[name="buyer_contact_phone"]').value = partner.manager_phone || partner.contact || '';
    document.querySelector('input[name="buyer_email"]').value = partner.email || '';

    closePartnerModal();
}

function formatBizNo(bizNo) {
    if (!bizNo) return '';
    const digits = bizNo.replace(/[^0-9]/g, '');
    if (digits.length === 10) {
        return digits.slice(0, 3) + '-' + digits.slice(3, 5) + '-' + digits.slice(5);
    }
    return bizNo;
}

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

function escapeAttr(str) {
    return str.replace(/&/g, '&amp;').replace(/'/g, '&#39;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
</script>
@endsection
