@extends('layouts.app')

@section('title', '카테고리 수정')

@section('content')
<div class="container mx-auto max-w-2xl">
    <!-- 헤더 -->
    <div class="flex justify-between items-center mb-6">
        <div>
            <h1 class="text-2xl font-bold text-gray-800">카테고리 수정</h1>
            <p class="text-sm text-gray-500 mt-1">카테고리 정보를 수정합니다.</p>
        </div>
        <a href="{{ route('quote-formulas.categories.index') }}"
           class="text-gray-600 hover:text-gray-800 text-sm font-medium">
            &larr; 목록으로
        </a>
    </div>

    <!-- 로딩 -->
    <div id="loading" class="bg-white rounded-lg shadow-sm p-12 text-center">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto"></div>
        <p class="text-gray-500 mt-4">데이터를 불러오는 중...</p>
    </div>

    <!-- 폼 (로드 후 표시) -->
    <div id="formContainer" class="bg-white rounded-lg shadow-sm p-6 hidden">
        <form id="categoryForm" class="space-y-6">
            <!-- 카테고리 코드 -->
            <div>
                <label for="code" class="block text-sm font-medium text-gray-700 mb-1">
                    카테고리 코드 <span class="text-red-500">*</span>
                </label>
                <input type="text" name="code" id="code"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                       required>
                <p class="text-xs text-gray-500 mt-1">대문자로 시작하고 대문자, 숫자, 언더스코어만 사용 가능</p>
            </div>

            <!-- 카테고리명 -->
            <div>
                <label for="name" class="block text-sm font-medium text-gray-700 mb-1">
                    카테고리명 <span class="text-red-500">*</span>
                </label>
                <input type="text" name="name" id="name"
                       class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
                       required>
            </div>

            <!-- 설명 -->
            <div>
                <label for="description" class="block text-sm font-medium text-gray-700 mb-1">
                    설명
                </label>
                <textarea name="description" id="description" rows="3"
                          class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
            </div>

            <!-- 정렬 순서 -->
            <div>
                <label for="sort_order" class="block text-sm font-medium text-gray-700 mb-1">
                    정렬 순서
                </label>
                <input type="number" name="sort_order" id="sort_order"
                       min="1"
                       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">수식 실행 순서에 영향을 줍니다.</p>
            </div>

            <!-- 활성 상태 -->
            <div class="flex items-center">
                <input type="checkbox" name="is_active" id="is_active" value="1"
                       class="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded">
                <label for="is_active" class="ml-2 block text-sm text-gray-700">
                    활성화
                </label>
            </div>

            <!-- 에러 메시지 -->
            <div id="errorMessage" class="hidden bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-700"></div>

            <!-- 버튼 -->
            <div class="flex justify-end gap-3 pt-4 border-t">
                <a href="{{ route('quote-formulas.categories.index') }}"
                   class="px-4 py-2 text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg transition">
                    취소
                </a>
                <button type="submit"
                        class="px-6 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-lg transition">
                    저장
                </button>
            </div>
        </form>
    </div>
</div>
@endsection

@push('scripts')
<script>
    const categoryId = {{ $id }};

    // 데이터 로드
    async function loadCategory() {
        try {
            const response = await fetch(`/api/admin/quote-formulas/categories/${categoryId}`, {
                headers: {
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                }
            });

            const result = await response.json();

            if (response.ok && result.success) {
                const data = result.data;
                document.getElementById('code').value = data.code || '';
                document.getElementById('name').value = data.name || '';
                document.getElementById('description').value = data.description || '';
                document.getElementById('sort_order').value = data.sort_order || '';
                document.getElementById('is_active').checked = data.is_active;

                document.getElementById('loading').classList.add('hidden');
                document.getElementById('formContainer').classList.remove('hidden');
            } else {
                showToast(result.message || '데이터를 불러오는데 실패했습니다.', 'error');
                window.location.href = '{{ route("quote-formulas.categories.index") }}';
            }
        } catch (err) {
            showToast('서버 오류가 발생했습니다.', 'error');
            window.location.href = '{{ route("quote-formulas.categories.index") }}';
        }
    }

    // 폼 제출
    document.getElementById('categoryForm').addEventListener('submit', async function(e) {
        e.preventDefault();

        const errorDiv = document.getElementById('errorMessage');
        errorDiv.classList.add('hidden');

        const formData = new FormData(this);
        const data = {
            code: formData.get('code'),
            name: formData.get('name'),
            description: formData.get('description') || null,
            sort_order: formData.get('sort_order') ? parseInt(formData.get('sort_order')) : null,
            is_active: formData.has('is_active')
        };

        try {
            const response = await fetch(`/api/admin/quote-formulas/categories/${categoryId}`, {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/json',
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': '{{ csrf_token() }}'
                },
                body: JSON.stringify(data)
            });

            const result = await response.json();

            if (response.ok && result.success) {
                window.location.href = '{{ route("quote-formulas.categories.index") }}';
            } else {
                errorDiv.textContent = result.message || '저장에 실패했습니다.';
                errorDiv.classList.remove('hidden');
            }
        } catch (err) {
            errorDiv.textContent = '서버 오류가 발생했습니다.';
            errorDiv.classList.remove('hidden');
        }
    });

    // 코드 자동 대문자 변환
    document.getElementById('code').addEventListener('input', function(e) {
        this.value = this.value.toUpperCase().replace(/[^A-Z0-9_]/g, '');
    });

    // 초기 로드
    loadCategory();
</script>
@endpush
