@extends('layouts.app')

@section('title', '명함 등록')

@push('styles')
<style>
    .ocr-drop-zone {
        border: 2px dashed #d1d5db;
        border-radius: 12px;
        padding: 24px;
        text-align: center;
        transition: all 0.2s;
        cursor: pointer;
        background: #f9fafb;
    }
    .ocr-drop-zone:hover, .ocr-drop-zone.dragover {
        border-color: #3b82f6;
        background: #eff6ff;
    }
    .ocr-drop-zone-icon { width: 40px; height: 40px; margin: 0 auto 8px; color: #9ca3af; }
    .ocr-drop-zone.dragover .ocr-drop-zone-icon { color: #3b82f6; }

    #ocr-preview-image {
        max-width: 100%;
        max-height: 200px;
        border-radius: 8px;
        margin-top: 12px;
        display: none;
    }

    .ocr-status {
        display: inline-flex;
        align-items: center;
        gap: 6px;
        padding: 4px 10px;
        border-radius: 16px;
        font-size: 12px;
        font-weight: 500;
    }
    .ocr-status-processing { background: #dbeafe; color: #1d4ed8; }
    .ocr-status-completed { background: #dcfce7; color: #16a34a; }
    .ocr-status-error { background: #fee2e2; color: #dc2626; }

    .auto-filled {
        background: #fef3c7 !important;
        border-color: #f59e0b !important;
        animation: highlight-fade 3s ease-out forwards;
    }
    @keyframes highlight-fade {
        0% { background: #fef3c7; border-color: #f59e0b; }
        100% { background: white; border-color: #d1d5db; }
    }

    .ocr-spinner {
        width: 14px;
        height: 14px;
        border: 2px solid #3b82f6;
        border-top-color: transparent;
        border-radius: 50%;
        animation: spin 0.8s linear infinite;
        display: inline-block;
    }
    @keyframes spin { to { transform: rotate(360deg); } }
</style>
@endpush

@section('content')
<div class="max-w-2xl mx-auto">
    <!-- 페이지 헤더 -->
    <div class="mb-6">
        <a href="{{ route('sales.prospects.index') }}" class="text-gray-500 hover:text-gray-700 text-sm mb-2 inline-flex items-center">
            <svg class="w-4 h-4 mr-1" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7" />
            </svg>
            목록으로
        </a>
        <h1 class="text-2xl font-bold text-gray-800">명함 등록</h1>
        <p class="text-sm text-gray-500 mt-1">명함 등록 시 2개월간 영업권이 부여됩니다</p>
    </div>

    <!-- 알림 메시지 -->
    @if(session('error'))
    <div class="mb-4 p-4 bg-red-50 border border-red-200 rounded-lg text-red-700">
        {{ session('error') }}
    </div>
    @endif

    <!-- 명함 OCR 영역 -->
    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <div class="flex items-center justify-between mb-4">
            <h2 class="text-lg font-semibold text-gray-800">
                <svg class="w-5 h-5 inline-block mr-1 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z" />
                </svg>
                AI 명함 인식
            </h2>
            <span id="ocr-status" class="hidden"></span>
        </div>

        <div class="ocr-drop-zone" id="ocr-drop-zone">
            <input type="file" id="ocr-file-input" accept="image/*" class="hidden">
            <input type="file" id="ocr-camera-input" accept="image/*" capture="environment" class="hidden">
            <svg class="ocr-drop-zone-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z" />
            </svg>
            <p class="text-gray-600 font-medium text-sm">명함 이미지를 드래그하거나 클릭하여 업로드</p>
            <p class="text-gray-400 text-xs mt-1">AI가 자동으로 정보를 추출합니다 (JPG, PNG)</p>

            <!-- 모바일 카메라 촬영 버튼 -->
            <div class="mt-4 pt-4 border-t border-gray-200">
                <button type="button" id="ocr-camera-btn" class="inline-flex items-center gap-2 px-4 py-2 bg-blue-500 hover:bg-blue-600 text-white text-sm font-medium rounded-lg transition">
                    <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="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                    카메라로 촬영
                </button>
            </div>
        </div>
        <img id="ocr-preview-image" alt="Preview">
    </div>

    <!-- 폼 -->
    <form action="{{ route('sales.prospects.store') }}" method="POST" enctype="multipart/form-data" class="bg-white rounded-lg shadow-sm p-6 space-y-6">
        @csrf
        <input type="hidden" name="business_card_image_data" id="business_card_image_data" value="">

        <!-- 사업자번호 (중복 체크) -->
        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">사업자번호 <span class="text-red-500">*</span></label>
            <div class="flex gap-2">
                <input type="text" name="business_number" id="business_number" value="{{ old('business_number') }}" required
                       placeholder="000-00-00000" maxlength="12"
                       class="flex-1 px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 @error('business_number') border-red-500 @enderror">
                <button type="button" id="checkBusinessNumber"
                        class="px-4 py-2 bg-gray-600 hover:bg-gray-700 text-white rounded-lg transition">
                    중복확인
                </button>
            </div>
            <p id="businessNumberResult" class="mt-1 text-sm"></p>
            @error('business_number')
            <p class="mt-1 text-sm text-red-500">{{ $message }}</p>
            @enderror
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">회사명 <span class="text-red-500">*</span></label>
                <input type="text" name="company_name" id="company_name" value="{{ old('company_name') }}" required
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 @error('company_name') border-red-500 @enderror">
                @error('company_name')
                <p class="mt-1 text-sm text-red-500">{{ $message }}</p>
                @enderror
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">대표자명</label>
                <input type="text" name="ceo_name" id="ceo_name" value="{{ old('ceo_name') }}"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
        </div>

        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">연락처</label>
                <input type="text" name="contact_phone" id="contact_phone" value="{{ old('contact_phone') }}"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <div>
                <label class="block text-sm font-medium text-gray-700 mb-2">이메일</label>
                <input type="email" name="contact_email" id="contact_email" value="{{ old('contact_email') }}"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">주소</label>
            <input type="text" name="address" id="address" value="{{ old('address') }}"
                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>

        <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">메모</label>
            <textarea name="memo" rows="3"
                      class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">{{ old('memo') }}</textarea>
        </div>

        <div class="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <h3 class="font-medium text-blue-800 mb-2">영업권 안내</h3>
            <ul class="text-sm text-blue-700 space-y-1">
                <li>등록일로부터 <strong>2개월간</strong> 영업권이 유효합니다.</li>
                <li>유효기간 내 테넌트로 전환 시 영업 실적으로 인정됩니다.</li>
                <li>만료 후 <strong>1개월간</strong> 재등록 대기 기간이 적용됩니다.</li>
                <li>대기 기간 이후 다른 영업파트너가 등록할 수 있습니다.</li>
            </ul>
        </div>

        <div class="flex justify-end gap-3 pt-4 border-t">
            <a href="{{ route('sales.prospects.index') }}"
               class="px-6 py-2 border border-gray-300 text-gray-700 rounded-lg hover:bg-gray-50 transition">
                취소
            </a>
            <button type="submit"
                    class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition">
                등록
            </button>
        </div>
    </form>
</div>

@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    const fileInput = document.getElementById('ocr-file-input');
    const cameraInput = document.getElementById('ocr-camera-input');
    const cameraBtn = document.getElementById('ocr-camera-btn');
    const dropZone = document.getElementById('ocr-drop-zone');
    const previewImage = document.getElementById('ocr-preview-image');
    const statusEl = document.getElementById('ocr-status');
    const csrfToken = '{{ csrf_token() }}';

    // 카메라 버튼 클릭 시 카메라 입력 트리거
    cameraBtn.addEventListener('click', (e) => {
        e.stopPropagation(); // dropZone 클릭 이벤트 전파 방지
        cameraInput.click();
    });

    // 카메라 입력 처리
    cameraInput.addEventListener('change', (e) => {
        if (e.target.files.length) handleFile(e.target.files[0]);
    });

    // 드래그 앤 드롭 (드롭존 클릭 시 파일 선택)
    dropZone.addEventListener('click', (e) => {
        // 카메라 버튼 클릭이 아닌 경우에만 파일 선택
        if (e.target !== cameraBtn && !cameraBtn.contains(e.target)) {
            fileInput.click();
        }
    });
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.classList.add('dragover');
    });
    dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover'));
    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.classList.remove('dragover');
        if (e.dataTransfer.files.length) {
            handleFile(e.dataTransfer.files[0]);
        }
    });
    fileInput.addEventListener('change', (e) => {
        if (e.target.files.length) handleFile(e.target.files[0]);
    });

    // 파일 처리
    async function handleFile(file) {
        if (!file.type.startsWith('image/')) {
            showStatus('error', '이미지 파일만 지원합니다.');
            return;
        }

        showStatus('processing', 'AI 분석 중...');

        // 이미지 미리보기
        const base64 = await fileToBase64(file);
        previewImage.src = base64;
        previewImage.style.display = 'block';

        try {
            const response = await fetch('{{ route("api.business-card-ocr") }}', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': csrfToken
                },
                body: JSON.stringify({ image: base64 })
            });

            // 응답이 JSON인지 확인
            const contentType = response.headers.get('content-type');
            if (!contentType || !contentType.includes('application/json')) {
                const text = await response.text();
                console.error('Non-JSON response:', response.status, text.substring(0, 500));
                showStatus('error', '서버 오류가 발생했습니다 (HTTP ' + response.status + ')');
                return;
            }

            const result = await response.json();

            if (result.ok) {
                fillFormFromData(result.data);
                // 명함 이미지 데이터를 hidden input에 저장
                document.getElementById('business_card_image_data').value = base64;
                showStatus('completed', '인식 완료');
            } else {
                showStatus('error', result.error || '인식 실패');
            }
        } catch (error) {
            console.error(error);
            showStatus('error', '처리 중 오류 발생');
        }
    }

    // File to Base64
    function fileToBase64(file) {
        return new Promise((resolve, reject) => {
            const reader = new FileReader();
            reader.onload = () => resolve(reader.result);
            reader.onerror = reject;
            reader.readAsDataURL(file);
        });
    }

    // 폼 채우기
    function fillFormFromData(data) {
        const fieldMap = {
            'business_number': 'business_number',
            'company_name': 'company_name',
            'ceo_name': 'ceo_name',
            'contact_phone': 'contact_phone',
            'contact_email': 'contact_email',
            'address': 'address'
        };

        for (const [dataKey, fieldId] of Object.entries(fieldMap)) {
            const value = data[dataKey];
            if (value) {
                const el = document.getElementById(fieldId);
                if (el) {
                    el.value = value;
                    el.classList.add('auto-filled');
                }
            }
        }
    }

    // 상태 표시
    function showStatus(type, text) {
        statusEl.className = 'ocr-status ocr-status-' + type;
        statusEl.innerHTML = type === 'processing'
            ? '<span class="ocr-spinner"></span> ' + text
            : text;
        statusEl.classList.remove('hidden');

        if (type === 'completed') {
            setTimeout(() => statusEl.classList.add('hidden'), 5000);
        }
    }

    // 사업자번호 자동 포맷팅 (000-00-00000)
    document.getElementById('business_number').addEventListener('input', function(e) {
        let value = e.target.value.replace(/[^0-9]/g, '');

        if (value.length > 10) {
            value = value.substring(0, 10);
        }

        if (value.length > 5) {
            value = value.substring(0, 3) + '-' + value.substring(3, 5) + '-' + value.substring(5);
        } else if (value.length > 3) {
            value = value.substring(0, 3) + '-' + value.substring(3);
        }

        e.target.value = value;
    });

    // 중복 확인
    document.getElementById('checkBusinessNumber').addEventListener('click', function() {
        const businessNumber = document.getElementById('business_number').value;
        const resultEl = document.getElementById('businessNumberResult');

        if (!businessNumber) {
            resultEl.textContent = '사업자번호를 입력해주세요.';
            resultEl.className = 'mt-1 text-sm text-red-500';
            return;
        }

        if (!/^\d{3}-\d{2}-\d{5}$/.test(businessNumber)) {
            resultEl.textContent = '사업자번호 형식이 올바르지 않습니다. (000-00-00000)';
            resultEl.className = 'mt-1 text-sm text-red-500';
            return;
        }

        fetch('{{ route("sales.prospects.check-business-number") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': csrfToken
            },
            body: JSON.stringify({ business_number: businessNumber })
        })
        .then(response => response.json())
        .then(data => {
            if (data.can_register) {
                resultEl.textContent = '등록 가능한 사업자번호입니다.';
                resultEl.className = 'mt-1 text-sm text-green-500';
            } else {
                resultEl.textContent = data.reason;
                resultEl.className = 'mt-1 text-sm text-red-500';
            }
        })
        .catch(error => {
            resultEl.textContent = '확인 중 오류가 발생했습니다.';
            resultEl.className = 'mt-1 text-sm text-red-500';
        });
    });
});
</script>
@endpush
@endsection
