@extends('layouts.app')

@section('title', '프로필 설정')

@section('content')
<div class="container mx-auto max-w-2xl">
    <!-- 페이지 헤더 -->
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800">프로필 설정</h1>
    </div>

    <!-- 비밀번호 변경 필요 알림 -->
    @if(auth()->user()->must_change_password)
    <div class="bg-amber-50 border border-amber-200 rounded-lg p-4 mb-6">
        <div class="flex items-start gap-3">
            <svg class="w-6 h-6 text-amber-500 flex-shrink-0 mt-0.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <div>
                <h3 class="text-sm font-semibold text-amber-800">비밀번호 변경이 필요합니다</h3>
                <p class="text-sm text-amber-700 mt-1">
                    보안을 위해 비밀번호를 변경해주세요. 비밀번호를 변경하기 전까지 다른 기능을 이용할 수 없습니다.
                </p>
            </div>
        </div>
    </div>
    @endif

    @if(session('warning'))
    <div class="bg-amber-50 border border-amber-200 rounded-lg p-4 mb-6">
        <div class="flex items-center gap-2">
            <svg class="w-5 h-5 text-amber-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            <p class="text-sm text-amber-700">{{ session('warning') }}</p>
        </div>
    </div>
    @endif

    <!-- 기본 정보 -->
    <div class="bg-white rounded-lg shadow-sm p-6 mb-6">
        <h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b flex items-center gap-2">
            <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
            </svg>
            기본 정보
        </h2>

        <form id="profileForm">
            <div class="space-y-4">
                <!-- 사용자 ID (읽기 전용) -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        사용자 ID
                    </label>
                    <input type="text" value="{{ auth()->user()->user_id ?? '-' }}" readonly
                           class="w-full px-4 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-500 cursor-not-allowed">
                </div>

                <!-- 이름 -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        이름 @if(!auth()->user()->isSuperAdmin())<span class="text-xs text-gray-400">(관리자만 수정 가능)</span>@else<span class="text-red-500">*</span>@endif
                    </label>
                    @if(auth()->user()->isSuperAdmin())
                    <input type="text" name="name" required maxlength="100"
                           value="{{ auth()->user()->name }}"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    @else
                    <input type="text" value="{{ auth()->user()->name }}" readonly
                           class="w-full px-4 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-500 cursor-not-allowed">
                    @endif
                </div>

                <!-- 이메일 (읽기 전용) -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        이메일
                    </label>
                    <input type="email" value="{{ auth()->user()->email }}" readonly
                           class="w-full px-4 py-2 border border-gray-200 rounded-lg bg-gray-50 text-gray-500 cursor-not-allowed">
                </div>

                <!-- 연락처 -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        연락처
                    </label>
                    <input type="text" name="phone" maxlength="20"
                           value="{{ auth()->user()->phone }}"
                           placeholder="010-1234-5678"
                           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="flex justify-end mt-6">
                <button type="submit" id="profileSubmitBtn"
                        class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition">
                    저장
                </button>
            </div>
        </form>
    </div>

    <!-- 비밀번호 변경 -->
    <div class="bg-white rounded-lg shadow-sm p-6">
        <h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b flex items-center gap-2">
            <svg class="w-5 h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
            </svg>
            비밀번호 변경
        </h2>

        <form id="passwordForm">
            <div class="space-y-4">
                <!-- 현재 비밀번호 -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        현재 비밀번호 <span class="text-red-500">*</span>
                    </label>
                    <input type="password" name="current_password" required
                           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-1">
                        새 비밀번호 <span class="text-red-500">*</span>
                    </label>
                    <input type="password" name="password" required minlength="8"
                           class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <p class="text-xs text-gray-500 mt-1">최소 8자 이상 입력해주세요.</p>
                </div>

                <!-- 새 비밀번호 확인 -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 mb-1">
                        새 비밀번호 확인 <span class="text-red-500">*</span>
                    </label>
                    <input type="password" name="password_confirmation" required minlength="8"
                           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="flex justify-end mt-6">
                <button type="submit" id="passwordSubmitBtn"
                        class="px-6 py-2 bg-orange-500 hover:bg-orange-600 text-white rounded-lg transition">
                    비밀번호 변경
                </button>
            </div>
        </form>
    </div>
</div>
@endsection

@push('scripts')
<script>
    // 프로필 정보 수정
    document.getElementById('profileForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const btn = document.getElementById('profileSubmitBtn');
        const originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '저장 중...';

        const formData = new FormData(this);
        const data = Object.fromEntries(formData.entries());

        fetch('{{ route("profile.update") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast(data.message, 'success');
            } else {
                showToast(data.message || '프로필 수정에 실패했습니다.', 'error');
            }
        })
        .catch(error => {
            console.error(error);
            if (error.errors) {
                let errorMsg = '입력 오류: ';
                for (let field in error.errors) {
                    errorMsg += error.errors[field].join(', ') + ' ';
                }
                showToast(errorMsg, 'error');
            } else {
                showToast('서버 오류가 발생했습니다.', 'error');
            }
        })
        .finally(() => {
            btn.disabled = false;
            btn.innerHTML = originalText;
        });
    });

    // 비밀번호 변경
    document.getElementById('passwordForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const btn = document.getElementById('passwordSubmitBtn');
        const originalText = btn.innerHTML;
        btn.disabled = true;
        btn.innerHTML = '변경 중...';

        const formData = new FormData(this);
        const data = Object.fromEntries(formData.entries());

        fetch('{{ route("profile.password") }}', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json'
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                showToast(data.message, 'success');
                this.reset(); // 폼 초기화
            } else {
                showToast(data.message || '비밀번호 변경에 실패했습니다.', 'error');
            }
        })
        .catch(error => {
            console.error(error);
            if (error.errors) {
                let errorMsg = '입력 오류: ';
                for (let field in error.errors) {
                    errorMsg += error.errors[field].join(', ') + ' ';
                }
                showToast(errorMsg, 'error');
            } else {
                showToast('서버 오류가 발생했습니다.', 'error');
            }
        })
        .finally(() => {
            btn.disabled = false;
            btn.innerHTML = originalText;
        });
    });
</script>
@endpush