@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">영업파트너의 등록, 승인, 역할을 관리합니다</p>
        </div>
        @unless(auth()->user()->isGroupPartner())
        <a href="{{ route('sales.managers.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>
        @endunless
    </div>

    <!-- 통계 카드 -->
    <div class="grid grid-cols-2 md:grid-cols-5 gap-4 mb-4 flex-shrink-0">
        <div class="bg-white rounded-lg shadow-sm p-4">
            <div class="text-sm text-gray-500">전체</div>
            <div class="text-2xl font-bold text-gray-800">{{ number_format($stats['total']) }}명</div>
        </div>
        <div class="bg-yellow-50 rounded-lg shadow-sm p-4">
            <div class="text-sm text-yellow-600">승인대기</div>
            <div class="text-2xl font-bold text-yellow-800">{{ number_format($stats['pending']) }}명</div>
        </div>
        <div class="bg-emerald-50 rounded-lg shadow-sm p-4">
            <div class="text-sm text-emerald-600">승인완료</div>
            <div class="text-2xl font-bold text-emerald-800">{{ number_format($stats['approved']) }}명</div>
        </div>
        <div class="bg-blue-50 rounded-lg shadow-sm p-4">
            <div class="text-sm text-blue-600">영업파트너</div>
            <div class="text-2xl font-bold text-blue-800">{{ number_format($stats['sales']) }}명</div>
        </div>
        <div class="bg-purple-50 rounded-lg shadow-sm p-4">
            <div class="text-sm text-purple-600">상담매니저</div>
            <div class="text-2xl font-bold text-purple-800">{{ number_format($stats['manager']) }}명</div>
        </div>
    </div>

    <!-- 필터 영역 (한 줄) -->
    <div class="flex-shrink-0 mb-4">
        <form method="GET" class="flex flex-wrap gap-2 sm:gap-3 items-center bg-white p-3 rounded-lg shadow-sm">
            <!-- 승인 상태 필터 버튼 -->
            <div class="flex gap-1 flex-shrink-0">
                <a href="{{ route('sales.managers.index', array_merge(request()->except('approval_status', 'page'), [])) }}"
                   class="px-3 py-2 rounded-lg text-sm font-medium transition {{ !request('approval_status') ? 'bg-gray-800 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200' }}">
                    전체
                </a>
                <a href="{{ route('sales.managers.index', array_merge(request()->except('page'), ['approval_status' => 'approved'])) }}"
                   class="px-3 py-2 rounded-lg text-sm font-medium transition {{ request('approval_status') === 'approved' ? 'bg-emerald-600 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200' }}">
                    승인완료
                </a>
                <a href="{{ route('sales.managers.index', array_merge(request()->except('page'), ['approval_status' => 'pending'])) }}"
                   class="px-3 py-2 rounded-lg text-sm font-medium transition {{ request('approval_status') === 'pending' ? 'bg-yellow-500 text-white' : 'bg-gray-100 text-gray-700 hover:bg-gray-200' }}">
                    승인대기
                </a>
            </div>

            <!-- 구분선 -->
            <div class="hidden sm:block w-px h-8 bg-gray-300"></div>

            <!-- 현재 approval_status 유지 -->
            @if(request('approval_status'))
            <input type="hidden" name="approval_status" value="{{ request('approval_status') }}">
            @endif

            <!-- 검색 입력 -->
            <div class="flex-1 min-w-0">
                <input type="text"
                       name="search"
                       value="{{ request('search') }}"
                       placeholder="이름, 아이디, 이메일, 전화번호로 검색..."
                       class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
            </div>

            <!-- 역할 선택 -->
            <div class="w-32 flex-shrink-0">
                <select name="role" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm">
                    <option value="">전체 역할</option>
                    <option value="sales" {{ request('role') === 'sales' ? 'selected' : '' }}>영업파트너</option>
                    <option value="manager" {{ request('role') === 'manager' ? 'selected' : '' }}>상담매니저</option>
                </select>
            </div>

            <!-- 검색 버튼 -->
            <button type="submit" class="bg-gray-700 hover:bg-gray-800 text-white px-4 py-2 rounded-lg transition text-sm flex-shrink-0">
                검색
            </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-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($partners as $partner)
                    <tr class="hover:bg-gray-50">
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="font-medium text-gray-900">{{ $partner->name }}</div>
                            @if($partner->email)
                            <div class="text-sm text-gray-500">{{ $partner->email }}</div>
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">
                            {{ $partner->user_id ?? '-' }}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <div class="flex flex-wrap gap-1">
                                @foreach($partner->userRoles as $userRole)
                                @php
                                    $roleColor = match($userRole->role->name ?? '') {
                                        'sales' => 'bg-blue-100 text-blue-800',
                                        'manager' => 'bg-purple-100 text-purple-800',
                                        default => 'bg-gray-100 text-gray-800',
                                    };
                                    $roleLabel = match($userRole->role->name ?? '') {
                                        'sales' => '영업파트너',
                                        'manager' => '상담매니저',
                                        default => $userRole->role->name ?? '-',
                                    };
                                @endphp
                                <span class="px-2 py-1 text-xs font-medium rounded-full {{ $roleColor }}">
                                    {{ $roleLabel }}
                                </span>
                                @endforeach
                            </div>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            @if($partner->salesPartner)
                                @if($partner->salesPartner->partner_type === 'corporate')
                                    <span class="px-2 py-1 text-xs font-medium rounded-full bg-amber-100 text-amber-800">단체</span>
                                @else
                                    <span class="px-2 py-1 text-xs font-medium rounded-full bg-sky-100 text-sky-800">개인</span>
                                @endif
                            @else
                                <span class="text-xs text-gray-400">-</span>
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ $partner->phone ?? '-' }}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            @if($partner->parent)
                            <a href="{{ route('sales.managers.show', $partner->parent->id) }}" class="text-blue-600 hover:underline">
                                {{ $partner->parent->name }}
                            </a>
                            @else
                            <span class="text-gray-400">최상위</span>
                            @endif
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap">
                            <span class="px-2 py-1 text-xs font-medium rounded-full {{ $partner->approval_status_color }}">
                                {{ $partner->approval_status_label }}
                            </span>
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">
                            {{ $partner->created_at->format('Y-m-d') }}
                        </td>
                        <td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                            <button type="button" onclick="openShowModal({{ $partner->id }})" class="text-blue-600 hover:text-blue-900 mr-3">상세</button>
                            <button type="button" onclick="openEditModal({{ $partner->id }})" class="text-indigo-600 hover:text-indigo-900 mr-3">수정</button>
                            @if(auth()->user()->isAdmin())
                                @if($partner->isPendingApproval())
                                <form action="{{ route('sales.managers.approve', $partner->id) }}" method="POST" class="inline"
                                      onsubmit="return confirm('승인하시겠습니까?')">
                                    @csrf
                                    <button type="submit" class="text-green-600 hover:text-green-900 mr-3">승인</button>
                                </form>
                                @endif
                                <form action="{{ route('sales.managers.destroy', $partner->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
                        </td>
                    </tr>
                    @empty
                    <tr>
                        <td colspan="9" class="px-6 py-12 text-center text-gray-500">
                            등록된 파트너가 없습니다.
                        </td>
                    </tr>
                    @endforelse
                </tbody>
            </table>
        </div>

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

<!-- 파트너 모달 -->
<div id="partnerModal" 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="partnerModalContent" class="relative bg-white rounded-xl shadow-2xl w-full max-w-3xl">
            <!-- 로딩 표시 -->
            <div id="modalLoading" class="p-12 text-center">
                <svg class="w-8 h-8 animate-spin text-blue-600 mx-auto" 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="mt-2 text-gray-500">로딩 중...</p>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
// 전역 스코프에 함수 등록 (AJAX로 로드된 HTML에서 접근 가능하도록)
window.openShowModal = function(id) {
    const modal = document.getElementById('partnerModal');
    const content = document.getElementById('partnerModalContent');

    // 모달 표시
    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden'; // 배경 스크롤 방지

    // 로딩 표시
    content.innerHTML = `
        <div id="modalLoading" class="p-12 text-center">
            <svg class="w-8 h-8 animate-spin text-blue-600 mx-auto" 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="mt-2 text-gray-500">로딩 중...</p>
        </div>
    `;

    // AJAX로 상세 정보 가져오기
    fetch(`/sales/managers/${id}/modal-show`, {
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'text/html'
        }
    })
    .then(response => response.text())
    .then(html => {
        content.innerHTML = html;
        // innerHTML로 삽입된 script 태그 수동 실행
        content.querySelectorAll('script').forEach(oldScript => {
            const newScript = document.createElement('script');
            newScript.textContent = oldScript.textContent;
            oldScript.parentNode.replaceChild(newScript, oldScript);
        });
    })
    .catch(error => {
        content.innerHTML = `
            <div class="p-6 text-center">
                <p class="text-red-500">오류가 발생했습니다.</p>
                <button onclick="closePartnerModal()" class="mt-4 px-4 py-2 bg-gray-600 text-white rounded-lg">닫기</button>
            </div>
        `;
    });
}

// 수정 모달 열기
window.openEditModal = function(id) {
    const modal = document.getElementById('partnerModal');
    const content = document.getElementById('partnerModalContent');

    // 모달 표시
    modal.classList.remove('hidden');
    document.body.style.overflow = 'hidden'; // 배경 스크롤 방지

    // 로딩 표시
    content.innerHTML = `
        <div id="modalLoading" class="p-12 text-center">
            <svg class="w-8 h-8 animate-spin text-blue-600 mx-auto" 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="mt-2 text-gray-500">로딩 중...</p>
        </div>
    `;

    // AJAX로 수정 폼 가져오기
    fetch(`/sales/managers/${id}/modal-edit`, {
        headers: {
            'X-Requested-With': 'XMLHttpRequest',
            'Accept': 'text/html'
        }
    })
    .then(response => response.text())
    .then(html => {
        content.innerHTML = html;
        // innerHTML로 삽입된 script 태그 수동 실행
        content.querySelectorAll('script').forEach(oldScript => {
            const newScript = document.createElement('script');
            newScript.textContent = oldScript.textContent;
            oldScript.parentNode.replaceChild(newScript, oldScript);
        });
    })
    .catch(error => {
        content.innerHTML = `
            <div class="p-6 text-center">
                <p class="text-red-500">오류가 발생했습니다.</p>
                <button onclick="closePartnerModal()" class="mt-4 px-4 py-2 bg-gray-600 text-white rounded-lg">닫기</button>
            </div>
        `;
    });
}

// 모달 닫기
window.closePartnerModal = function() {
    const modal = document.getElementById('partnerModal');
    modal.classList.add('hidden');
    document.body.style.overflow = ''; // 배경 스크롤 복원
}

// ESC 키로 모달 닫기
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        closePartnerModal();
    }
});

// 이벤트 델리게이션: data-close-modal 속성을 가진 요소 클릭 시 모달 닫기
document.addEventListener('click', function(e) {
    const closeBtn = e.target.closest('[data-close-modal]');
    if (closeBtn) {
        e.preventDefault();
        e.stopPropagation();
        window.closePartnerModal();
    }
});
</script>
@endpush
