@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 flex-shrink-0">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">명함등록 (영업권)</h1>
            <p class="text-sm text-gray-500 mt-1">명함을 등록하여 2개월간 영업권을 확보하세요</p>
        </div>
        <a href="{{ route('sales.prospects.create') }}"
           class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition text-center w-full sm:w-auto flex items-center justify-center gap-2">
            <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="M12 4v16m8-8H4" />
            </svg>
            명함 등록
        </a>
    </div>

    <!-- 통계 카드 -->
    <div class="grid grid-cols-2 md:grid-cols-4 gap-4 mb-6 flex-shrink-0">
        <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="text-sm text-gray-500">전체</div>
            <div class="text-xl font-bold text-gray-800">{{ number_format($stats['total']) }}</div>
        </div>
        <div class="bg-blue-50 rounded-lg shadow-sm p-4">
            <div class="text-sm text-blue-600">영업중</div>
            <div class="text-xl font-bold text-blue-800">{{ number_format($stats['active']) }}</div>
        </div>
        <div class="bg-gray-50 rounded-lg shadow-sm p-4">
            <div class="text-sm text-gray-600">만료</div>
            <div class="text-xl font-bold text-gray-800">{{ number_format($stats['expired']) }}</div>
        </div>
        <div class="bg-green-50 rounded-lg shadow-sm p-4">
            <div class="text-sm text-green-600">성공</div>
            <div class="text-xl font-bold text-green-800">{{ number_format($stats['converted']) }}</div>
        </div>
    </div>

    <!-- 필터 영역 -->
    <div class="flex-shrink-0 mb-4">
        <form method="GET" class="flex flex-wrap gap-2 sm:gap-4 items-center bg-white p-4 rounded-lg shadow-sm">
            <div class="flex-1 min-w-0 w-full sm:w-auto">
                <input type="text"
                       name="search"
                       value="{{ request('search') }}"
                       placeholder="회사명, 사업자번호, 대표자, 연락처로 검색..."
                       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 class="w-full sm:w-40">
                <select name="status" class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">전체 상태</option>
                    <option value="active" {{ request('status') === 'active' ? 'selected' : '' }}>영업중</option>
                    <option value="expired" {{ request('status') === 'expired' ? 'selected' : '' }}>만료</option>
                    <option value="converted" {{ request('status') === 'converted' ? 'selected' : '' }}>성공</option>
                </select>
            </div>
            <button type="submit" class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-2 rounded-lg transition w-full sm:w-auto">
                검색
            </button>
        </form>
    </div>

    <!-- 테이블 -->
    <div class="bg-white rounded-lg shadow-sm overflow-hidden flex-1 flex flex-col min-h-0">
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">회사정보</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">상태</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">등록자</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">연락처</th>
                        <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">유효기간</th>
                        <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">관리</th>
                    </tr>
                </thead>
                <tbody class="bg-white divide-y divide-gray-200">
                    @forelse($prospects as $prospect)
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4">
                            <div class="font-medium text-gray-900">{{ $prospect->company_name }}</div>
                            <div class="text-sm text-gray-500">{{ $prospect->business_number }}</div>
                            @if($prospect->ceo_name)
                            <div class="text-sm text-gray-500">{{ $prospect->ceo_name }}</div>
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 text-xs font-medium rounded-full {{ $prospect->status_color }}">
                                {{ $prospect->status_label }}
                            </span>
                            @if($prospect->isActive() && $prospect->remaining_days <= 14)
                            <div class="text-xs text-red-500 mt-1">D-{{ $prospect->remaining_days }}</div>
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="text-sm text-gray-900">{{ $prospect->registeredBy?->name ?? '-' }}</div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ $prospect->contact_phone ?? '-' }}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm">
                            @if($prospect->isConverted())
                            <div class="text-green-600">{{ $prospect->converted_at?->format('Y-m-d') }} 성공</div>
                            @elseif($prospect->isActive())
                            <div class="text-blue-600">{{ $prospect->expires_at->format('Y-m-d') }} 까지</div>
                            @else
                            <div class="text-gray-500">{{ $prospect->expires_at->format('Y-m-d') }} 만료</div>
                            @if($prospect->isInCooldown())
                            <div class="text-xs text-yellow-600">대기: {{ $prospect->cooldown_ends_at->format('Y-m-d') }}</div>
                            @endif
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button type="button" onclick="openProspectShowModal({{ $prospect->id }})" class="text-blue-600 hover:text-blue-900 mr-3">상세</button>
                            @if(!$prospect->isConverted())
                            <button type="button" onclick="openProspectEditModal({{ $prospect->id }})" class="text-indigo-600 hover:text-indigo-900 mr-3">수정</button>
                            @if(auth()->user()->isAdmin())
                            <form action="{{ route('sales.prospects.destroy', $prospect->id) }}" method="POST" class="inline"
                                  onsubmit="return confirm('정말 삭제하시겠습니까?')">
                                @csrf
                                @method('DELETE')
                                <button type="submit" class="text-red-600 hover:text-red-900">삭제</button>
                            </form>
                            @endif
                            @endif
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="6" class="px-6 py-12 text-center text-gray-500">
                            등록된 명함이 없습니다.
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

        <!-- 페이지네이션 -->
        @if($prospects->hasPages())
        <div class="px-6 py-4 border-t border-gray-200">
            {{ $prospects->withQueryString()->links() }}
        </div>
        @endif
    </div>
</div>

<!-- 고객 모달 -->
<div id="prospectModal" class="hidden fixed inset-0 z-50 overflow-y-auto">
    <!-- 배경 오버레이 -->
    <div class="fixed inset-0 bg-black bg-opacity-50 transition-opacity"></div>
    <!-- 모달 컨텐츠 wrapper -->
    <div class="flex min-h-full items-center justify-center p-4">
        <div id="prospectModalContent" class="relative bg-white rounded-xl shadow-2xl w-full max-w-3xl">
            <!-- AJAX로 로드되는 내용 -->
            <div class="flex items-center justify-center p-12">
                <svg class="animate-spin h-8 w-8 text-blue-600" 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>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
// 전역 함수 등록
window.openProspectShowModal = function(id) {
    const modal = document.getElementById('prospectModal');
    const content = document.getElementById('prospectModalContent');

    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';

    // 로딩 표시
    content.innerHTML = `
        <div class="flex items-center justify-center p-12">
            <svg class="animate-spin h-8 w-8 text-blue-600" 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>
        </div>
    `;

    // AJAX로 내용 로드
    fetch(`/sales/prospects/${id}/modal-show`)
        .then(response => response.text())
        .then(html => {
            content.innerHTML = html;
        })
        .catch(error => {
            console.error('Error:', error);
            content.innerHTML = '<div class="p-6 text-center text-red-500">내용을 불러올 수 없습니다.</div>';
        });
};

window.openProspectEditModal = function(id) {
    const modal = document.getElementById('prospectModal');
    const content = document.getElementById('prospectModalContent');

    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden';

    // 로딩 표시
    content.innerHTML = `
        <div class="flex items-center justify-center p-12">
            <svg class="animate-spin h-8 w-8 text-blue-600" 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>
        </div>
    `;

    // AJAX로 내용 로드
    fetch(`/sales/prospects/${id}/modal-edit`)
        .then(response => response.text())
        .then(html => {
            content.innerHTML = html;
        })
        .catch(error => {
            console.error('Error:', error);
            content.innerHTML = '<div class="p-6 text-center text-red-500">내용을 불러올 수 없습니다.</div>';
        });
};

window.closeProspectModal = function() {
    document.getElementById('prospectModal').classList.add('hidden');
    document.body.style.overflow = '';
};

// ESC 키로 모달 닫기
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const modal = document.getElementById('prospectModal');
        if (!modal.classList.contains('hidden')) {
            window.closeProspectModal();
        }
    }
});

// 이벤트 델리게이션 (닫기 버튼)
document.addEventListener('click', function(e) {
    const closeBtn = e.target.closest('[data-close-modal]');
    if (closeBtn) {
        e.preventDefault();
        window.closeProspectModal();
    }
});
</script>
@endpush
