@extends('layouts.app')

@section('title', '테넌트 수정')

@section('content')
<div class="container mx-auto max-w-4xl">
    <!-- 페이지 헤더 -->
    <div class="flex justify-between items-center mb-6">
        <h1 class="text-2xl font-bold text-gray-800">테넌트 수정</h1>
        <a href="{{ route('tenants.index') }}" class="text-gray-600 hover:text-gray-800">
            ← 목록으로
        </a>
    </div>

    <!-- 폼 영역 -->
    <div class="bg-white rounded-lg shadow-sm p-6">
        <form id="tenantForm"
              action="/api/admin/tenants/{{ $tenant->id }}"
              method="POST"
              hx-put="{{ url('/api/admin/tenants/' . $tenant->id) }}"
              hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
              hx-swap="none">
            @method('PUT')
            @csrf

            <!-- 기본 정보 -->
            <div class="mb-8">
                <h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">기본 정보</h2>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            회사명 <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="company_name" value="{{ old('company_name', $tenant->company_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">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            테넌트 코드 <span class="text-red-500">*</span>
                        </label>
                        <input type="text" name="code" value="{{ old('code', $tenant->code) }}" 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">이메일</label>
                        <input type="email" name="email" value="{{ old('email', $tenant->email) }}"
                               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">전화번호</label>
                        <input type="text" name="phone" value="{{ old('phone', $tenant->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>
            </div>

            <!-- 회사 정보 -->
            <div class="mb-8">
                <h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">회사 정보</h2>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">사업자등록번호</label>
                        <input type="text" name="business_num" value="{{ old('business_num', $tenant->business_num) }}"
                               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">법인등록번호</label>
                        <input type="text" name="corp_reg_no" value="{{ old('corp_reg_no', $tenant->corp_reg_no) }}"
                               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">대표자명</label>
                        <input type="text" name="ceo_name" value="{{ old('ceo_name', $tenant->ceo_name) }}"
                               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">팩스</label>
                        <input type="text" name="fax" value="{{ old('fax', $tenant->fax) }}"
                               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 class="col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-1">주소</label>
                        <input type="text" name="address" value="{{ old('address', $tenant->address) }}"
                               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 class="col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-1">홈페이지</label>
                        <input type="url" name="homepage" value="{{ old('homepage', $tenant->homepage) }}"
                               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="mb-8">
                <h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">구독 정보</h2>
                <div class="grid grid-cols-2 gap-4">
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            상태 <span class="text-red-500">*</span>
                        </label>
                        <select name="tenant_st_code" required
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="trial" {{ old('tenant_st_code', $tenant->tenant_st_code) === 'trial' ? 'selected' : '' }}>트라이얼</option>
                            <option value="active" {{ old('tenant_st_code', $tenant->tenant_st_code) === 'active' ? 'selected' : '' }}>활성</option>
                            <option value="suspended" {{ old('tenant_st_code', $tenant->tenant_st_code) === 'suspended' ? 'selected' : '' }}>정지</option>
                            <option value="expired" {{ old('tenant_st_code', $tenant->tenant_st_code) === 'expired' ? 'selected' : '' }}>만료</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            테넌트 유형 <span class="text-red-500">*</span>
                        </label>
                        <div class="flex items-center gap-4 mt-2">
                            <label class="inline-flex items-center cursor-pointer">
                                <input type="radio" name="tenant_type" value="STD"
                                       {{ old('tenant_type', $tenant->tenant_type ?? 'STD') === 'STD' ? 'checked' : '' }}
                                       class="w-4 h-4 text-gray-600 bg-gray-100 border-gray-300 focus:ring-gray-500">
                                <span class="ml-2 px-2 py-1 text-sm font-medium bg-gray-100 text-gray-700 rounded">일반</span>
                            </label>
                            <label class="inline-flex items-center cursor-pointer">
                                <input type="radio" name="tenant_type" value="TPL"
                                       {{ old('tenant_type', $tenant->tenant_type) === 'TPL' ? 'checked' : '' }}
                                       class="w-4 h-4 text-purple-600 bg-gray-100 border-gray-300 focus:ring-purple-500">
                                <span class="ml-2 px-2 py-1 text-sm font-medium bg-purple-100 text-purple-700 rounded">템플릿</span>
                            </label>
                            <label class="inline-flex items-center cursor-pointer">
                                <input type="radio" name="tenant_type" value="HQ"
                                       {{ old('tenant_type', $tenant->tenant_type) === 'HQ' ? 'checked' : '' }}
                                       class="w-4 h-4 text-blue-600 bg-gray-100 border-gray-300 focus:ring-blue-500">
                                <span class="ml-2 px-2 py-1 text-sm font-medium bg-blue-100 text-blue-700 rounded">본사</span>
                            </label>
                        </div>
                        <p class="mt-1 text-xs text-gray-500">템플릿: 새 테넌트 생성 시 메뉴 복사 원본 / 본사: 모든 테넌트 관리 가능</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">결제 유형</label>
                        <select name="billing_tp_code"
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                            <option value="">선택 안함</option>
                            <option value="monthly" {{ old('billing_tp_code', $tenant->billing_tp_code) === 'monthly' ? 'selected' : '' }}>월간</option>
                            <option value="yearly" {{ old('billing_tp_code', $tenant->billing_tp_code) === 'yearly' ? 'selected' : '' }}>연간</option>
                            <option value="free" {{ old('billing_tp_code', $tenant->billing_tp_code) === 'free' ? 'selected' : '' }}>무료</option>
                        </select>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">최대 사용자 수</label>
                        <input type="number" name="max_users" value="{{ old('max_users', $tenant->max_users) }}" 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">
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">트라이얼 종료일</label>
                        <input type="datetime-local" name="trial_ends_at"
                               value="{{ old('trial_ends_at', $tenant->trial_ends_at?->format('Y-m-d\TH:i')) }}"
                               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">구독 만료일</label>
                        <input type="datetime-local" name="expires_at"
                               value="{{ old('expires_at', $tenant->expires_at?->format('Y-m-d\TH:i')) }}"
                               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">마지막 결제일</label>
                        <input type="datetime-local" name="last_paid_at"
                               value="{{ old('last_paid_at', $tenant->last_paid_at?->format('Y-m-d\TH:i')) }}"
                               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="mb-8">
                <h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">관리자 메모</h2>
                <textarea name="admin_memo" 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">{{ old('admin_memo', $tenant->admin_memo) }}</textarea>
            </div>

            <!-- 통계 정보 -->
            <div class="mb-8">
                <h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">통계</h2>
                <div class="grid grid-cols-4 gap-4">
                    <div class="bg-gray-50 p-4 rounded-lg text-center">
                        <div class="text-2xl font-bold text-blue-600">{{ $tenant->users_count ?? 0 }}</div>
                        <div class="text-sm text-gray-600">사용자</div>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg text-center">
                        <div class="text-2xl font-bold text-green-600">{{ $tenant->departments_count ?? 0 }}</div>
                        <div class="text-sm text-gray-600">부서</div>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg text-center">
                        <div class="text-2xl font-bold text-purple-600">{{ $tenant->menus_count ?? 0 }}</div>
                        <div class="text-sm text-gray-600">메뉴</div>
                    </div>
                    <div class="bg-gray-50 p-4 rounded-lg text-center">
                        <div class="text-2xl font-bold text-orange-600">{{ $tenant->roles_count ?? 0 }}</div>
                        <div class="text-sm text-gray-600">역할</div>
                    </div>
                </div>
            </div>

            <!-- 버튼 영역 -->
            <div class="flex justify-end gap-3">
                <a href="{{ route('tenants.index') }}"
                   class="px-6 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 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>
    // HTMX 응답 처리
    document.body.addEventListener('htmx:afterRequest', function(event) {
        if (event.detail.target.id === 'tenantForm') {
            const response = JSON.parse(event.detail.xhr.response);
            if (response.success) {
                showToast(response.message, 'success');
                window.location.href = response.redirect;
            } else {
                showToast(response.message || '테넌트 수정에 실패했습니다.', 'error');
            }
        }
    });

    // 에러 처리
    document.body.addEventListener('htmx:responseError', function(event) {
        if (event.detail.xhr.status === 422) {
            const errors = JSON.parse(event.detail.xhr.response).errors;
            let errorMsg = '입력 오류: ';
            for (let field in errors) {
                errorMsg += errors[field].join(', ') + ' ';
            }
            showToast(errorMsg, 'error');
        } else {
            showToast('서버 오류가 발생했습니다.', 'error');
        }
    });
</script>
@endpush