@extends('layouts.app')

@section('title', '영업파트너 수정')

@push('styles')
<style>
    .doc-drop-zone {
        border: 2px dashed #d1d5db;
        border-radius: 8px;
        padding: 16px;
        text-align: center;
        transition: all 0.2s;
        cursor: pointer;
        background: #f9fafb;
        min-height: 80px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }
    .doc-drop-zone:hover, .doc-drop-zone.dragover {
        border-color: #3b82f6;
        background: #eff6ff;
    }
    .doc-drop-zone.has-file {
        border-color: #10b981;
        background: #ecfdf5;
        border-style: solid;
    }
    .doc-drop-zone-icon {
        width: 24px;
        height: 24px;
        color: #9ca3af;
    }
    .doc-drop-zone.dragover .doc-drop-zone-icon,
    .doc-drop-zone:hover .doc-drop-zone-icon {
        color: #3b82f6;
    }
    .doc-drop-zone.has-file .doc-drop-zone-icon {
        color: #10b981;
    }
    .doc-preview {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px;
        background: white;
        border-radius: 6px;
        margin-top: 8px;
        width: 100%;
    }
    .doc-preview img {
        width: 40px;
        height: 40px;
        object-fit: cover;
        border-radius: 4px;
    }
    .doc-preview-info {
        flex: 1;
        min-width: 0;
        text-align: left;
    }
    .doc-preview-name {
        font-size: 12px;
        font-weight: 500;
        color: #374151;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
    }
    .doc-preview-size {
        font-size: 11px;
        color: #9ca3af;
    }
    .doc-preview-remove {
        padding: 4px;
        color: #9ca3af;
        cursor: pointer;
        transition: color 0.2s;
    }
    .doc-preview-remove:hover {
        color: #ef4444;
    }
</style>
@endpush

@section('content')
<div class="max-w-3xl mx-auto">
    <!-- 페이지 헤더 -->
    <div class="mb-6">
        <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">영업파트너 수정</h1>
        <p class="text-sm text-gray-500 mt-1">{{ $partner->name }} ({{ $partner->email }})</p>
    </div>

    <!-- 폼 -->
    <form action="{{ route('sales.managers.update', $partner->id) }}" method="POST" enctype="multipart/form-data" class="space-y-6">
        @csrf
        @method('PUT')

        <!-- 기본 정보 -->
        <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-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">로그인 ID</label>
                    <input type="text" value="{{ $partner->user_id ?? $partner->email }}" disabled
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg bg-gray-100 text-gray-500">
                </div>

                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">이름 <span class="text-red-500">*</span></label>
                    <input type="text" name="name" value="{{ old('name', $partner->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('name') border-red-500 @enderror">
                    @error('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">이메일 <span class="text-red-500">*</span></label>
                    <input type="email" name="email" value="{{ old('email', $partner->email) }}" 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('email') border-red-500 @enderror">
                    @error('email')
                    <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="phone" value="{{ old('phone', $partner->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="password" name="password" placeholder="변경 시에만 입력"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 @error('password') border-red-500 @enderror">
                    @error('password')
                    <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="password" name="password_confirmation" 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>
        </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="space-y-4">
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">역할 <span class="text-red-500">*</span></label>
                    <div class="space-y-2">
                        @foreach($roles as $role)
                        <label class="flex items-center">
                            <input type="checkbox" name="role_ids[]" value="{{ $role->id }}"
                                   {{ in_array($role->id, old('role_ids', $currentRoleIds)) ? 'checked' : '' }}
                                   class="w-4 h-4 text-blue-600 border-gray-300 rounded focus:ring-blue-500">
                            <span class="ml-2 text-sm text-gray-700">
                                {{ $role->description ?? $role->name }}
                                <span class="text-gray-400">({{ $role->name }})</span>
                            </span>
                        </label>
                        @endforeach
                    </div>
                    @error('role_ids')
                    <p class="mt-1 text-sm text-red-500">{{ $message }}</p>
                    @enderror
                </div>

                @if($partner->parent)
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-2">추천인(유치자)</label>
                    <div class="px-4 py-2 bg-gray-50 border border-gray-200 rounded-lg text-gray-700">
                        {{ $partner->parent->name }} ({{ $partner->parent->email }})
                    </div>
                    <p class="mt-1 text-xs text-gray-500">추천인은 변경할 수 없습니다.</p>
                </div>
                @endif
            </div>
        </div>

        <!-- 기존 첨부 서류 -->
        @if($partner->salesDocuments->isNotEmpty())
        <div class="bg-white rounded-lg shadow-sm p-6">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">기존 첨부 서류</h2>
            <div class="space-y-3">
                @foreach($partner->salesDocuments as $document)
                <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                    <div class="flex items-center gap-3">
                        <span class="px-2 py-0.5 text-xs bg-gray-200 text-gray-600 rounded">{{ $document->document_type_label }}</span>
                        <span class="text-sm text-gray-700">{{ $document->original_name }}</span>
                        <span class="text-xs text-gray-400">{{ $document->formatted_size }}</span>
                    </div>
                    <form action="{{ route('sales.managers.documents.delete', [$partner->id, $document->id]) }}" method="POST"
                          onsubmit="return confirm('이 서류를 삭제하시겠습니까?')">
                        @csrf
                        @method('DELETE')
                        <button type="submit" class="text-red-500 hover:text-red-700">
                            <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="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                        </button>
                    </form>
                </div>
                @endforeach
            </div>
        </div>
        @endif

        <!-- 새 첨부 서류 -->
        <div class="bg-white rounded-lg shadow-sm p-6">
            <h2 class="text-lg font-semibold text-gray-800 mb-4">새 서류 추가</h2>

            <div id="document-list" class="space-y-4">
                <div class="document-item border border-gray-200 rounded-lg p-4" data-index="0">
                    <div class="flex items-start gap-4">
                        <div class="w-40 flex-shrink-0">
                            <label class="block text-sm font-medium text-gray-700 mb-1">문서 유형</label>
                            <select name="documents[0][document_type]"
                                    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($documentTypes as $value => $label)
                                <option value="{{ $value }}">{{ $label }}</option>
                                @endforeach
                            </select>
                        </div>
                        <div class="flex-1">
                            <label class="block text-sm font-medium text-gray-700 mb-1">파일</label>
                            <div class="doc-drop-zone" data-index="0">
                                <input type="file" name="documents[0][file]" class="hidden" accept="image/*,.pdf,.doc,.docx">
                                <svg class="doc-drop-zone-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                                </svg>
                                <p class="text-xs text-gray-500 mt-1">클릭 또는 드래그하여 업로드</p>
                            </div>
                        </div>
                        <div class="w-40 flex-shrink-0">
                            <label class="block text-sm font-medium text-gray-700 mb-1">설명</label>
                            <input type="text" name="documents[0][description]"
                                   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"
                                   placeholder="선택사항">
                        </div>
                    </div>
                </div>
            </div>

            <button type="button" id="add-document-btn"
                    class="mt-4 inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg text-sm font-medium text-gray-700 bg-white hover:bg-gray-50">
                <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
                </svg>
                서류 추가
            </button>
        </div>

        <!-- 제출 버튼 -->
        <div class="flex justify-end gap-3">
            <a href="{{ route('sales.managers.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>
@endsection

@push('scripts')
<script>
let documentIndex = 1;

// 드래그 앤 드롭 초기화
function initDropZone(dropZone) {
    const fileInput = dropZone.querySelector('input[type="file"]');

    dropZone.addEventListener('click', (e) => {
        if (!e.target.closest('.doc-preview-remove')) {
            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(dropZone, e.dataTransfer.files[0]);
        }
    });

    fileInput.addEventListener('change', (e) => {
        if (e.target.files.length) {
            handleFile(dropZone, e.target.files[0]);
        }
    });
}

function handleFile(dropZone, file) {
    const fileInput = dropZone.querySelector('input[type="file"]');

    // DataTransfer로 파일 설정
    const dt = new DataTransfer();
    dt.items.add(file);
    fileInput.files = dt.files;

    // UI 업데이트
    dropZone.classList.add('has-file');

    // 기존 미리보기 제거
    const existingPreview = dropZone.querySelector('.doc-preview');
    if (existingPreview) existingPreview.remove();

    // 아이콘과 텍스트 숨기기
    const icon = dropZone.querySelector('.doc-drop-zone-icon');
    const text = dropZone.querySelector('p');
    if (icon) icon.style.display = 'none';
    if (text) text.style.display = 'none';

    // 미리보기 생성
    const preview = document.createElement('div');
    preview.className = 'doc-preview';

    const isImage = file.type.startsWith('image/');
    const fileSize = formatFileSize(file.size);

    if (isImage) {
        const reader = new FileReader();
        reader.onload = (e) => {
            preview.innerHTML = `
                <img src="${e.target.result}" alt="Preview">
                <div class="doc-preview-info">
                    <div class="doc-preview-name">${file.name}</div>
                    <div class="doc-preview-size">${fileSize}</div>
                </div>
                <button type="button" class="doc-preview-remove" onclick="removeFile(this)">
                    <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>
            `;
        };
        reader.readAsDataURL(file);
    } else {
        const ext = file.name.split('.').pop().toUpperCase();
        preview.innerHTML = `
            <div class="w-10 h-10 bg-gray-100 rounded flex items-center justify-center text-xs font-medium text-gray-500">${ext}</div>
            <div class="doc-preview-info">
                <div class="doc-preview-name">${file.name}</div>
                <div class="doc-preview-size">${fileSize}</div>
            </div>
            <button type="button" class="doc-preview-remove" onclick="removeFile(this)">
                <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>
        `;
    }

    dropZone.appendChild(preview);
}

function removeFile(btn) {
    const dropZone = btn.closest('.doc-drop-zone');
    const fileInput = dropZone.querySelector('input[type="file"]');
    const preview = dropZone.querySelector('.doc-preview');
    const icon = dropZone.querySelector('.doc-drop-zone-icon');
    const text = dropZone.querySelector('p');

    // 파일 input 초기화
    fileInput.value = '';

    // 미리보기 제거
    if (preview) preview.remove();

    // 아이콘과 텍스트 다시 표시
    if (icon) icon.style.display = '';
    if (text) text.style.display = '';

    dropZone.classList.remove('has-file');
}

function formatFileSize(bytes) {
    if (bytes >= 1048576) return (bytes / 1048576).toFixed(1) + ' MB';
    if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB';
    return bytes + ' bytes';
}

// 문서 추가 버튼
document.getElementById('add-document-btn').addEventListener('click', function() {
    const container = document.getElementById('document-list');
    const template = `
        <div class="document-item border border-gray-200 rounded-lg p-4 relative" data-index="${documentIndex}">
            <button type="button" onclick="this.parentElement.remove()"
                    class="absolute top-2 right-2 text-gray-400 hover:text-red-500 z-10">
                <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 class="flex items-start gap-4">
                <div class="w-40 flex-shrink-0">
                    <label class="block text-sm font-medium text-gray-700 mb-1">문서 유형</label>
                    <select name="documents[${documentIndex}][document_type]"
                            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($documentTypes as $value => $label)
                        <option value="{{ $value }}">{{ $label }}</option>
                        @endforeach
                    </select>
                </div>
                <div class="flex-1">
                    <label class="block text-sm font-medium text-gray-700 mb-1">파일</label>
                    <div class="doc-drop-zone" data-index="${documentIndex}">
                        <input type="file" name="documents[${documentIndex}][file]" class="hidden" accept="image/*,.pdf,.doc,.docx">
                        <svg class="doc-drop-zone-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                        </svg>
                        <p class="text-xs text-gray-500 mt-1">클릭 또는 드래그하여 업로드</p>
                    </div>
                </div>
                <div class="w-40 flex-shrink-0">
                    <label class="block text-sm font-medium text-gray-700 mb-1">설명</label>
                    <input type="text" name="documents[${documentIndex}][description]"
                           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"
                           placeholder="선택사항">
                </div>
            </div>
        </div>
    `;
    container.insertAdjacentHTML('beforeend', template);

    // 새로 추가된 드롭존 초기화
    const newItem = container.lastElementChild;
    const newDropZone = newItem.querySelector('.doc-drop-zone');
    initDropZone(newDropZone);

    documentIndex++;
});

// 초기 드롭존 초기화
document.querySelectorAll('.doc-drop-zone').forEach(initDropZone);
</script>
@endpush
