@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>

<!-- 주기 탭 -->
<div class="flex gap-1 mb-4 bg-gray-100 rounded-lg p-1" style="width: fit-content;">
    @foreach($cycles as $code => $label)
        <button type="button"
                class="cycle-tab px-4 py-2 rounded-lg text-sm font-medium transition {{ $code === 'daily' ? 'bg-white text-blue-700 shadow-sm' : 'text-gray-600 hover:text-gray-800 hover:bg-gray-50' }}"
                data-cycle="{{ $code }}"
                onclick="switchCycle('{{ $code }}')">
            {{ $label }}
        </button>
    @endforeach
</div>

<!-- 필터 -->
<x-filter-collapsible id="inspectionFilterWrap" :defaultOpen="true">
    <form id="inspectionFilter" class="flex flex-wrap gap-2 sm:gap-4">
        <input type="hidden" name="cycle" id="filterCycle" value="daily">

        <!-- daily 전용: 점검년월 -->
        <div class="shrink-0 filter-daily" style="width: 160px;">
            <label class="block text-xs text-gray-500 mb-1">점검년월</label>
            <input type="month" name="period" id="periodMonth" value="{{ now()->format('Y-m') }}"
                   class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
        </div>

        <!-- 그 외 주기: 점검연도 -->
        <div class="shrink-0 filter-year" style="width: 120px; display: none;">
            <label class="block text-xs text-gray-500 mb-1">점검연도</label>
            <select name="period_year" id="periodYear"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                @for($y = now()->year; $y >= now()->year - 3; $y--)
                    <option value="{{ $y }}">{{ $y }}년</option>
                @endfor
            </select>
        </div>

        <div class="shrink-0" style="width: 140px;">
            <label class="block text-xs text-gray-500 mb-1">생산라인</label>
            <select name="production_line"
                    class="w-full px-3 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>
            </select>
        </div>
        <div class="shrink-0" style="width: 200px;">
            <label class="block text-xs text-gray-500 mb-1">설비</label>
            <select name="equipment_id"
                    class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                <option value="">전체</option>
                @foreach($equipmentList as $eq)
                    <option value="{{ $eq->id }}">{{ $eq->equipment_code }} - {{ $eq->name }}</option>
                @endforeach
            </select>
        </div>
        <div class="self-end flex gap-2">
            <button type="submit" class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-2 rounded-lg transition">
                조회
            </button>
            <button type="button" onclick="resetAllInspections()" class="bg-red-50 hover:bg-red-100 text-red-600 border border-red-200 px-4 py-2 rounded-lg transition text-sm font-medium">
                전체 초기화
            </button>
        </div>
    </form>
</x-filter-collapsible>

<!-- 점검 그리드 -->
<div id="inspection-grid"
     hx-get="/api/admin/equipment/inspections"
     hx-trigger="load, filterSubmit from:body"
     hx-include="#inspectionFilter"
     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>
    let currentCycle = 'daily';

    document.getElementById('inspectionFilter').addEventListener('submit', function(e) {
        e.preventDefault();
        updatePeriodValue();
        htmx.trigger('#inspection-grid', 'filterSubmit');
    });

    function switchCycle(cycle) {
        currentCycle = cycle;
        document.getElementById('filterCycle').value = cycle;

        // 탭 UI 전환
        document.querySelectorAll('.cycle-tab').forEach(btn => {
            if (btn.dataset.cycle === cycle) {
                btn.className = 'cycle-tab px-4 py-2 rounded-lg text-sm font-medium transition bg-white text-blue-700 shadow-sm';
            } else {
                btn.className = 'cycle-tab px-4 py-2 rounded-lg text-sm font-medium transition text-gray-600 hover:text-gray-800 hover:bg-gray-50';
            }
        });

        // 필터 전환
        const isDaily = cycle === 'daily';
        document.querySelectorAll('.filter-daily').forEach(el => el.style.display = isDaily ? '' : 'none');
        document.querySelectorAll('.filter-year').forEach(el => el.style.display = isDaily ? 'none' : '');

        updatePeriodValue();
        htmx.trigger('#inspection-grid', 'filterSubmit');
    }

    function updatePeriodValue() {
        // hidden period 필드에 올바른 값 설정
        if (currentCycle === 'daily') {
            document.getElementById('periodMonth').name = 'period';
            document.getElementById('periodYear').name = 'period_year';
        } else {
            document.getElementById('periodMonth').name = 'period_month_unused';
            document.getElementById('periodYear').name = 'period';
        }
    }

    function getCurrentPeriod() {
        if (currentCycle === 'daily') {
            return document.getElementById('periodMonth').value;
        }
        return document.getElementById('periodYear').value;
    }

    function resetEquipment(equipmentId, equipmentName) {
        const period = getCurrentPeriod();
        showConfirm(
            `<strong>${equipmentName}</strong>의 <strong>${period}</strong> 점검 데이터를 모두 초기화하시겠습니까?<br><span class="text-sm text-gray-500">이 작업은 되돌릴 수 없습니다.</span>`,
            function() {
                fetch('/api/admin/equipment/inspections/reset', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json',
                    },
                    body: JSON.stringify({
                        equipment_id: equipmentId,
                        cycle: currentCycle,
                        period: period,
                    })
                })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        showToast(data.message, 'success');
                        htmx.trigger('#inspection-grid', 'filterSubmit');
                    } else {
                        showToast(data.message || '초기화에 실패했습니다.', 'error');
                    }
                });
            },
            { title: '점검 초기화', icon: 'warning', confirmText: '초기화', cancelText: '취소' }
        );
    }

    function resetAllInspections() {
        const period = getCurrentPeriod();
        const cycleLabel = document.querySelector('.cycle-tab.bg-white')?.textContent?.trim() || currentCycle;
        showConfirm(
            `<strong>${period}</strong> ${cycleLabel} 점검의 <span class="text-red-600 font-bold">전체 데이터</span>를 초기화하시겠습니까?<br><span class="text-sm text-gray-500">모든 설비의 점검 기록이 삭제됩니다. 이 작업은 되돌릴 수 없습니다.</span>`,
            function() {
                fetch('/api/admin/equipment/inspections/reset-all', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                        'Accept': 'application/json',
                    },
                    body: JSON.stringify({
                        cycle: currentCycle,
                        period: period,
                    })
                })
                .then(r => r.json())
                .then(data => {
                    if (data.success) {
                        showToast(data.message, 'success');
                        htmx.trigger('#inspection-grid', 'filterSubmit');
                    } else {
                        showToast(data.message || '초기화에 실패했습니다.', 'error');
                    }
                });
            },
            { title: '전체 점검 초기화', icon: 'warning', confirmText: '전체 초기화', cancelText: '취소' }
        );
    }

    function toggleCell(equipmentId, templateItemId, checkDate, cell) {
        fetch('/api/admin/equipment/inspections/detail', {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
            },
            body: JSON.stringify({
                equipment_id: equipmentId,
                template_item_id: templateItemId,
                check_date: checkDate,
                cycle: currentCycle,
            })
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                const span = cell.querySelector('.inspection-cell') || cell;
                span.textContent = data.data.symbol;
                span.className = 'inspection-cell text-lg font-bold select-none ' + data.data.color;
            } else if (data.message) {
                showToast(data.message, 'error');
            }
        });
    }
</script>
@endpush
