@extends('layouts.app')
@section('title', '설비 등록대장')
@section('content')

<!-- 헤더 -->
<div class="flex flex-col sm:flex-row sm:justify-between sm:items-center gap-4 mb-6">
    <h1 class="text-2xl font-bold text-gray-800">설비 등록대장</h1>
    <div class="flex gap-2">
        <a href="{{ route('equipment.import') }}"
           class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg transition text-center">
            엑셀 Import
        </a>
        <a href="{{ route('equipment.create') }}"
           class="bg-blue-600 hover:bg-blue-700 text-white px-4 py-2 rounded-lg transition text-center">
            + 설비 등록
        </a>
    </div>
</div>

<!-- 필터 -->
<x-filter-collapsible id="filterForm">
    <form id="filterForm" class="flex flex-wrap gap-2 sm:gap-4">
        <input type="hidden" name="per_page" id="perPageInput" value="20">
        <input type="hidden" name="page" id="pageInput" value="1">

        <div style="flex: 1 1 200px; max-width: 300px;">
            <input type="text" name="search" 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 class="shrink-0" style="width: 140px;">
            <select name="status" 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="active">가동</option>
                <option value="idle">유휴</option>
                <option value="disposed">폐기</option>
            </select>
        </div>

        <div class="shrink-0" style="width: 140px;">
            <select name="production_line" 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="스라트">스라트</option>
                <option value="스크린">스크린</option>
                <option value="절곡">절곡</option>
                <option value="기타">기타</option>
            </select>
        </div>

        <div class="shrink-0" style="width: 140px;">
            <select name="equipment_type" 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="포밍기">포밍기</option>
                <option value="미싱기">미싱기</option>
                <option value="샤링기">샤링기</option>
                <option value="V컷팅기">V컷팅기</option>
                <option value="절곡기">절곡기</option>
                <option value="프레스">프레스</option>
                <option value="드릴">드릴</option>
                <option value="기타">기타</option>
            </select>
        </div>

        <button type="submit" class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-2 rounded-lg transition shrink-0">
            검색
        </button>
    </form>
</x-filter-collapsible>

<!-- 테이블 영역 -->
<div id="equipment-table"
     hx-get="/api/admin/equipment"
     hx-trigger="load, filterSubmit from:body"
     hx-include="#filterForm"
     hx-headers='{"X-CSRF-TOKEN": "{{ csrf_token() }}"}'
     class="bg-white rounded-lg shadow-sm">
    <div class="flex justify-center items-center p-12">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
    </div>
</div>

@endsection

@push('scripts')
<script>
    const FILTER_KEY = 'equipment_filter';
    const filterForm = document.getElementById('filterForm');
    const filterFields = ['search', 'status', 'production_line', 'equipment_type', 'per_page', 'page'];

    // 필터 상태 저장
    function saveFilter() {
        const data = {};
        filterFields.forEach(name => {
            const el = filterForm.querySelector(`[name="${name}"]`);
            if (el) data[name] = el.value;
        });
        sessionStorage.setItem(FILTER_KEY, JSON.stringify(data));
    }

    // 필터 상태 복원 (페이지 로드 시)
    (function restoreFilter() {
        const saved = sessionStorage.getItem(FILTER_KEY);
        if (!saved) return;
        try {
            const data = JSON.parse(saved);
            filterFields.forEach(name => {
                const el = filterForm.querySelector(`[name="${name}"]`);
                if (el && data[name] !== undefined) el.value = data[name];
            });
        } catch (e) {}
    })();

    filterForm.addEventListener('submit', function(e) {
        e.preventDefault();
        document.getElementById('pageInput').value = 1;
        saveFilter();
        htmx.trigger('#equipment-table', 'filterSubmit');
    });

    // select 변경 시에도 저장
    filterForm.querySelectorAll('select').forEach(el => {
        el.addEventListener('change', saveFilter);
    });

    // HTMX 요청 직전 필터 저장 (페이지네이션 등)
    document.body.addEventListener('htmx:configRequest', function() {
        saveFilter();
    });

    function confirmDelete(id, name) {
        showDeleteConfirm(name, () => {
            fetch(`/api/admin/equipment/${id}`, {
                method: 'DELETE',
                headers: {
                    'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    'Accept': 'application/json',
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    htmx.trigger('#equipment-table', 'filterSubmit');
                    showToast(data.message, 'success');
                } else {
                    showToast(data.message, 'error');
                }
            });
        });
    }
</script>
@endpush
