@extends('layouts.app')

@section('title', '영업파트너 상세')

@section('content')
<div class="max-w-4xl mx-auto">
    <!-- 페이지 헤더 -->
    <div class="mb-6 flex justify-between items-start">
        <div>
            <a href="{{ route('sales.managers.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">{{ $partner->name }}</h1>
            <p class="text-sm text-gray-500 mt-1">레벨 {{ $level }} 영업파트너</p>
            <div class="flex items-center gap-2 mt-2">
                @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
                <span class="px-2 py-1 text-xs font-medium rounded-full {{ $partner->approval_status_color }}">
                    {{ $partner->approval_status_label }}
                </span>
            </div>
        </div>
        <a href="{{ route('sales.managers.edit', $partner->id) }}"
           class="bg-indigo-600 hover:bg-indigo-700 text-white px-4 py-2 rounded-lg transition">
            수정
        </a>
    </div>

    <!-- 승인 대기 알림 및 액션 -->
    @if($partner->isPendingApproval())
    <div class="mb-6 bg-yellow-50 border border-yellow-200 rounded-lg p-4">
        <div class="flex items-start gap-3">
            <svg class="w-6 h-6 text-yellow-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <div class="flex-1">
                <h3 class="font-semibold text-yellow-800">승인 대기 중</h3>
                <p class="text-sm text-yellow-700 mt-1">이 파트너는 승인 대기 중입니다. 첨부된 서류를 확인 후 승인 또는 반려해주세요.</p>
                <div class="mt-4 flex gap-3">
                    <form action="{{ route('sales.managers.approve', $partner->id) }}" method="POST" class="inline">
                        @csrf
                        <button type="submit" onclick="return confirm('승인하시겠습니까?')"
                                class="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 transition text-sm">
                            승인
                        </button>
                    </form>
                    <button type="button" onclick="document.getElementById('rejectModal').classList.remove('hidden')"
                            class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition text-sm">
                        반려
                    </button>
                </div>
            </div>
        </div>
    </div>
    @endif

    <!-- 반려된 경우 사유 표시 -->
    @if($partner->isRejected() && $partner->rejection_reason)
    <div class="mb-6 bg-red-50 border border-red-200 rounded-lg p-4">
        <div class="flex items-start gap-3">
            <svg class="w-6 h-6 text-red-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            <div>
                <h3 class="font-semibold text-red-800">반려됨</h3>
                <p class="text-sm text-red-700 mt-1">{{ $partner->rejection_reason }}</p>
                @if($partner->approver)
                <p class="text-xs text-red-600 mt-2">처리자: {{ $partner->approver->name }} ({{ $partner->approved_at->format('Y-m-d H:i') }})</p>
                @endif
            </div>
        </div>
    </div>
    @endif

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <!-- 기본 정보 -->
        <div class="bg-white rounded-lg shadow-sm p-6">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">기본 정보</h2>
            <dl class="space-y-3">
                <div class="flex justify-between">
                    <dt class="text-gray-500">로그인 ID</dt>
                    <dd class="font-medium text-gray-900">{{ $partner->user_id ?? $partner->email }}</dd>
                </div>
                <div class="flex justify-between">
                    <dt class="text-gray-500">이름</dt>
                    <dd class="font-medium text-gray-900">{{ $partner->name }}</dd>
                </div>
                <div class="flex justify-between">
                    <dt class="text-gray-500">이메일</dt>
                    <dd class="font-medium text-gray-900">{{ $partner->email }}</dd>
                </div>
                <div class="flex justify-between">
                    <dt class="text-gray-500">전화번호</dt>
                    <dd class="font-medium text-gray-900">{{ $partner->phone ?? '-' }}</dd>
                </div>
                <div class="flex justify-between">
                    <dt class="text-gray-500">계층 레벨</dt>
                    <dd class="font-medium text-gray-900">레벨 {{ $level }}</dd>
                </div>
                <div class="flex justify-between">
                    <dt class="text-gray-500">추천인(유치자)</dt>
                    <dd class="font-medium text-gray-900">
                        @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
                    </dd>
                </div>
                <div class="flex justify-between">
                    <dt class="text-gray-500">등록일</dt>
                    <dd class="font-medium text-gray-900">{{ $partner->created_at->format('Y-m-d H:i') }}</dd>
                </div>
                @if($partner->isApproved() && $partner->approved_at)
                <div class="flex justify-between">
                    <dt class="text-gray-500">승인일</dt>
                    <dd class="font-medium text-gray-900">{{ $partner->approved_at->format('Y-m-d H:i') }}</dd>
                </div>
                @endif
            </dl>
        </div>

        <!-- 통계 -->
        <div class="bg-white rounded-lg shadow-sm p-6">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">활동 통계</h2>
            <div class="grid grid-cols-2 gap-4">
                <div class="bg-blue-50 rounded-lg p-4 text-center">
                    <div class="text-2xl font-bold text-blue-800">{{ $children->count() }}</div>
                    <div class="text-sm text-blue-600">하위 파트너</div>
                </div>
                <div class="bg-green-50 rounded-lg p-4 text-center">
                    <div class="text-2xl font-bold text-green-800">{{ $partner->salesDocuments->count() }}</div>
                    <div class="text-sm text-green-600">첨부 서류</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 역할 관리 (승인된 파트너만) -->
    @if($partner->isApproved())
    <div class="mt-6 bg-white rounded-lg shadow-sm p-6">
        <h2 class="text-lg font-semibold text-gray-800 mb-4">역할 관리</h2>

        <!-- 현재 역할 -->
        <div class="mb-6">
            <h3 class="text-sm font-medium text-gray-700 mb-2">현재 보유 역할</h3>
            <div class="flex flex-wrap gap-2">
                @php
                    $currentRoles = $partner->userRoles->pluck('role.name')->toArray();
                    $roleLabels = ['sales' => '영업파트너', 'manager' => '상담매니저'];
                    $roleColors = [
                        'sales' => 'bg-blue-100 text-blue-800 border-blue-200',
                        'manager' => 'bg-purple-100 text-purple-800 border-purple-200',
                    ];
                @endphp
                @forelse($currentRoles as $roleName)
                    @if(isset($roleLabels[$roleName]))
                    <div class="flex items-center gap-1 px-3 py-1 rounded-full border {{ $roleColors[$roleName] ?? 'bg-gray-100' }}">
                        <span class="text-sm font-medium">{{ $roleLabels[$roleName] }}</span>
                        <form action="{{ route('sales.managers.remove-role', $partner->id) }}" method="POST" class="inline">
                            @csrf
                            <input type="hidden" name="role_name" value="{{ $roleName }}">
                            <button type="submit" onclick="return confirm('이 역할을 제거하시겠습니까?')"
                                    class="ml-1 text-gray-400 hover:text-red-500">
                                <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>
                        </form>
                    </div>
                    @endif
                @empty
                    <span class="text-gray-400 text-sm">역할이 없습니다</span>
                @endforelse
            </div>
        </div>

        <!-- 역할 부여 -->
        <div class="mb-6">
            <h3 class="text-sm font-medium text-gray-700 mb-2">역할 부여</h3>
            <div class="flex flex-wrap gap-2">
                @foreach(['sales' => '영업파트너', 'manager' => '상담매니저'] as $roleName => $label)
                    @if(!in_array($roleName, $currentRoles))
                    <form action="{{ route('sales.managers.assign-role', $partner->id) }}" method="POST" class="inline">
                        @csrf
                        <input type="hidden" name="role_name" value="{{ $roleName }}">
                        <button type="submit"
                                class="px-3 py-1 text-sm border border-gray-300 rounded-full hover:bg-gray-50 transition">
                            + {{ $label }}
                        </button>
                    </form>
                    @endif
                @endforeach
            </div>
        </div>

        <!-- 역할 위임 (manager 역할이 있고 위임 가능한 하위 파트너가 있을 때) -->
        @if(in_array('manager', $currentRoles) && $delegationCandidates->isNotEmpty())
        <div class="border-t border-gray-200 pt-6">
            <h3 class="text-sm font-medium text-gray-700 mb-3">역할 위임</h3>
            <p class="text-xs text-gray-500 mb-3">보유 중인 역할을 하위 파트너에게 위임할 수 있습니다. 위임하면 해당 역할이 제거됩니다.</p>

            <form action="{{ route('sales.managers.delegate-role', $partner->id) }}" method="POST" class="space-y-3">
                @csrf
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">위임할 역할</label>
                        <select name="role_name" required 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">
                            @if(in_array('manager', $currentRoles))
                            <option value="manager">상담매니저</option>
                            @endif
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm text-gray-600 mb-1">위임 대상</label>
                        <select name="to_user_id" required 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">
                            @foreach($delegationCandidates as $candidate)
                            <option value="{{ $candidate->id }}">{{ $candidate->name }} ({{ $candidate->email }})</option>
                            @endforeach
                        </select>
                    </div>
                </div>
                <button type="submit" onclick="return confirm('역할을 위임하면 본인의 해당 역할이 제거됩니다. 계속하시겠습니까?')"
                        class="px-4 py-2 bg-indigo-600 text-white rounded-lg hover:bg-indigo-700 transition text-sm">
                    역할 위임
                </button>
            </form>
        </div>
        @endif
    </div>
    @endif

    <!-- 첨부 서류 -->
    @if($partner->salesDocuments->isNotEmpty())
    <div class="mt-6 bg-white rounded-lg shadow-sm p-6">
        <h2 class="text-lg font-semibold text-gray-800 mb-4">첨부 서류</h2>
        <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
            @foreach($partner->salesDocuments as $document)
            <div class="border border-gray-200 rounded-lg p-4 flex items-start gap-4">
                @if($document->isImage())
                <div class="w-20 h-20 bg-gray-100 rounded-lg overflow-hidden flex-shrink-0">
                    <img src="{{ $document->getUrl() }}" alt="{{ $document->original_name }}" class="w-full h-full object-cover">
                </div>
                @else
                <div class="w-20 h-20 bg-gray-100 rounded-lg flex items-center justify-center flex-shrink-0">
                    <svg class="w-10 h-10 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 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>
                </div>
                @endif
                <div class="flex-1 min-w-0">
                    <div class="flex items-center gap-2">
                        <span class="px-2 py-0.5 text-xs bg-gray-100 text-gray-600 rounded">{{ $document->document_type_label }}</span>
                    </div>
                    <p class="font-medium text-gray-900 truncate mt-1">{{ $document->original_name }}</p>
                    <p class="text-xs text-gray-500 mt-1">{{ $document->formatted_size }}</p>
                    @if($document->description)
                    <p class="text-sm text-gray-600 mt-1">{{ $document->description }}</p>
                    @endif
                    <div class="mt-2">
                        <a href="{{ route('sales.managers.documents.download', [$partner->id, $document->id]) }}"
                           class="text-sm text-blue-600 hover:underline">다운로드</a>
                    </div>
                </div>
            </div>
            @endforeach
        </div>
    </div>
    @endif

    <!-- 하위 파트너 목록 -->
    @if($children->isNotEmpty())
    <div class="mt-6 bg-white rounded-lg shadow-sm p-6">
        <h2 class="text-lg font-semibold text-gray-800 mb-4">하위 파트너 (유치한 파트너)</h2>
        <div class="overflow-x-auto">
            <table class="min-w-full divide-y divide-gray-200">
                <thead class="bg-gray-50">
                    <tr>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">이름</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">역할</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">연락처</th>
                        <th class="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">상태</th>
                    </tr>
                </thead>
                <tbody class="divide-y divide-gray-200">
                    @foreach($children as $child)
                    <tr>
                        <td class="px-4 py-3">
                            <a href="{{ route('sales.managers.show', $child->id) }}" class="text-blue-600 hover:underline">
                                {{ $child->name }}
                            </a>
                        </td>
                        <td class="px-4 py-3">
                            @foreach($child->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
                        </td>
                        <td class="px-4 py-3 text-gray-500">{{ $child->phone ?? '-' }}</td>
                        <td class="px-4 py-3">
                            <span class="px-2 py-1 text-xs font-medium rounded-full {{ $child->approval_status_color }}">
                                {{ $child->approval_status_label }}
                            </span>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
        </div>
    </div>
    @endif
</div>

<!-- 반려 모달 -->
<div id="rejectModal" class="hidden fixed inset-0 bg-black bg-opacity-50 z-50 flex items-center justify-center">
    <div class="bg-white rounded-lg shadow-xl max-w-md w-full mx-4">
        <div class="p-6">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">반려 사유 입력</h3>
            <form action="{{ route('sales.managers.reject', $partner->id) }}" method="POST">
                @csrf
                <textarea name="rejection_reason" rows="4" required
                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-red-500"
                          placeholder="반려 사유를 입력해주세요."></textarea>
                <div class="mt-4 flex justify-end gap-3">
                    <button type="button" onclick="document.getElementById('rejectModal').classList.add('hidden')"
                            class="px-4 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 transition">
                        취소
                    </button>
                    <button type="submit" class="px-4 py-2 bg-red-600 text-white rounded-lg hover:bg-red-700 transition">
                        반려
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>
@endsection
