@extends('layouts.app')

@section('title', '역할 생성')

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

    @if(!empty($requireTenant))
    <!-- 테넌트 선택 필요 안내 -->
    <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-6 text-center">
        <div class="text-yellow-600 text-5xl mb-4">⚠️</div>
        <h2 class="text-xl font-semibold text-yellow-800 mb-2">테넌트 선택이 필요합니다</h2>
        <p class="text-yellow-700 mb-4">역할을 생성하려면 먼저 상단 헤더에서 테넌트를 선택해주세요.</p>
        <a href="{{ route('roles.index') }}" class="inline-block px-4 py-2 bg-yellow-600 hover:bg-yellow-700 text-white rounded-lg transition">
            목록으로 돌아가기
        </a>
    </div>
    @else
    <!-- 폼 영역 -->
    <div class="bg-white rounded-lg shadow-sm p-6">
        <form id="roleForm"
              hx-post="/api/admin/roles"
              hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
              hx-swap="none">

            <!-- 기본 정보 -->
            <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-1 md: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="name" required maxlength="100"
                               placeholder="예: 관리자, 일반사용자"
                               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">최대 100자까지 입력 가능합니다.</p>
                    </div>
                    <div>
                        <label class="block text-sm font-medium text-gray-700 mb-1">
                            Guard <span class="text-red-500">*</span>
                        </label>
                        <select name="guard_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">
                            <option value="api">API</option>
                            <option value="web">Web</option>
                        </select>
                        <p class="text-xs text-gray-500 mt-1">API: REST API용, Web: 웹 인증용</p>
                    </div>
                    <div class="md:col-span-2">
                        <label class="block text-sm font-medium text-gray-700 mb-1">설명</label>
                        <textarea name="description" rows="2" maxlength="500"
                                  placeholder="역할에 대한 설명을 입력하세요"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
                        <p class="text-xs text-gray-500 mt-1">최대 500자까지 입력 가능합니다.</p>
                    </div>
                </div>
            </div>

            <!-- 권한 선택 (메뉴 기반 매트릭스) -->
            <div class="mb-8">
                <h2 class="text-lg font-semibold text-gray-800 mb-4 pb-2 border-b">권한 선택</h2>
                @if($menus->isEmpty())
                    <div class="text-center py-8 text-gray-500">
                        <p>선택 가능한 메뉴가 없습니다.</p>
                        <p class="text-sm mt-2">테넌트를 선택하거나 메뉴를 먼저 생성해주세요.</p>
                    </div>
                @else
                    <!-- 일괄 선택 버튼 -->
                    <div class="mb-4 flex gap-2">
                        <button type="button" onclick="selectAllPermissions()"
                                class="px-3 py-1 text-sm bg-blue-100 text-blue-700 rounded hover:bg-blue-200 transition">
                            전체 선택
                        </button>
                        <button type="button" onclick="deselectAllPermissions()"
                                class="px-3 py-1 text-sm bg-gray-100 text-gray-700 rounded hover:bg-gray-200 transition">
                            전체 해제
                        </button>
                        <button type="button" onclick="selectViewOnly()"
                                class="px-3 py-1 text-sm bg-green-100 text-green-700 rounded hover:bg-green-200 transition">
                            조회만 선택
                        </button>
                    </div>

                    <!-- 권한 매트릭스 테이블 -->
                    <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-semibold text-gray-700 uppercase tracking-wider" style="width: 50px;">#</th>
                                    <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 uppercase tracking-wider">메뉴명</th>
                                    <th class="px-4 py-3 text-center text-xs font-semibold text-gray-700 uppercase tracking-wider" style="width: 60px;">조회</th>
                                    <th class="px-4 py-3 text-center text-xs font-semibold text-gray-700 uppercase tracking-wider" style="width: 60px;">생성</th>
                                    <th class="px-4 py-3 text-center text-xs font-semibold text-gray-700 uppercase tracking-wider" style="width: 60px;">수정</th>
                                    <th class="px-4 py-3 text-center text-xs font-semibold text-gray-700 uppercase tracking-wider" style="width: 60px;">삭제</th>
                                    <th class="px-4 py-3 text-center text-xs font-semibold text-gray-700 uppercase tracking-wider" style="width: 60px;">승인</th>
                                    <th class="px-4 py-3 text-center text-xs font-semibold text-gray-700 uppercase tracking-wider" style="width: 70px;">내보내기</th>
                                    <th class="px-4 py-3 text-center text-xs font-semibold text-gray-700 uppercase tracking-wider" style="width: 60px;">관리</th>
                                </tr>
                            </thead>
                            <tbody class="bg-white divide-y divide-gray-200">
                                @foreach($menus as $index => $menu)
                                <tr class="{{ ($menu->depth ?? 0) === 0 ? 'bg-gray-50' : '' }}">
                                    <td class="px-4 py-3 whitespace-nowrap text-sm text-gray-500 text-center">
                                        {{ $index + 1 }}
                                    </td>
                                    <td class="px-4 py-3 whitespace-nowrap">
                                        <div class="flex items-center text-sm text-gray-900" style="padding-left: {{ ($menu->depth ?? 0) * 20 }}px;">
                                            @if(($menu->depth ?? 0) > 0)
                                                <span class="mr-2 text-gray-400">└</span>
                                            @endif
                                            <span class="{{ ($menu->depth ?? 0) === 0 ? 'font-medium' : '' }}">{{ $menu->name }}</span>
                                        </div>
                                    </td>
                                    @foreach($permissionTypes as $type)
                                    <td class="px-4 py-3 whitespace-nowrap text-center">
                                        <input type="checkbox"
                                               name="menu_permissions[{{ $menu->id }}][]"
                                               value="{{ $type }}"
                                               data-menu-id="{{ $menu->id }}"
                                               data-permission-type="{{ $type }}"
                                               class="h-4 w-4 rounded border-gray-300 text-blue-600 focus:ring-blue-500 cursor-pointer permission-checkbox">
                                    </td>
                                    @endforeach
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                @endif
            </div>

            <!-- 버튼 영역 -->
            <div class="flex justify-end gap-3">
                <a href="{{ route('roles.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>
    @endif
</div>
@endsection

@push('scripts')
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<script>
    // 전체 선택
    function selectAllPermissions() {
        document.querySelectorAll('.permission-checkbox').forEach(checkbox => {
            checkbox.checked = true;
        });
    }

    // 전체 해제
    function deselectAllPermissions() {
        document.querySelectorAll('.permission-checkbox').forEach(checkbox => {
            checkbox.checked = false;
        });
    }

    // 조회만 선택
    function selectViewOnly() {
        document.querySelectorAll('.permission-checkbox').forEach(checkbox => {
            checkbox.checked = (checkbox.dataset.permissionType === 'view');
        });
    }

    // HTMX 응답 처리
    document.body.addEventListener('htmx:afterRequest', function(event) {
        if (event.detail.target.id === 'roleForm') {
            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
