@extends('layouts.app')
@section('title', '수리이력 등록')
@section('content')

<div class="max-w-3xl mx-auto">
    <div class="flex justify-between items-center mb-6">
        <div class="flex items-center gap-2">
            <h1 class="text-2xl font-bold text-gray-800">수리이력 등록</h1>
            <button type="button" id="mockFillBtn" title="목업 데이터 자동 입력"
                    class="text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50 rounded-lg p-1.5 transition">
                <svg class="w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                    <path d="M11.3 1.046A1 1 0 0112 2v5h4a1 1 0 01.82 1.573l-7 10A1 1 0 018 18v-5H4a1 1 0 01-.82-1.573l7-10a1 1 0 011.12-.38z"/>
                </svg>
            </button>
        </div>
        <a href="{{ route('equipment.repairs') }}" class="text-gray-600 hover:text-gray-800">
            &larr; 목록으로
        </a>
    </div>

    <div class="bg-white rounded-lg shadow-sm p-6">
        <form id="repairForm" class="space-y-4">
            @csrf

            <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">
                        설비 <span class="text-red-500">*</span>
                    </label>
                    <select name="equipment_id" 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="">선택</option>
                        @foreach($equipmentList as $eq)
                            <option value="{{ $eq->id }}">{{ $eq->equipment_code }} - {{ $eq->name }}</option>
                        @endforeach
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">
                        수리일 <span class="text-red-500">*</span>
                    </label>
                    <input type="date" name="repair_date" required value="{{ now()->format('Y-m-d') }}"
                           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-semibold text-gray-700 mb-2">
                        보전구분 <span class="text-red-500">*</span>
                    </label>
                    <select name="repair_type" 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="">선택</option>
                        <option value="internal">사내</option>
                        <option value="external">외주</option>
                    </select>
                </div>
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">수리시간 (h)</label>
                    <input type="number" name="repair_hours" min="0" step="0.5"
                           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>
                <label class="block text-sm font-semibold text-gray-700 mb-2">수리내용</label>
                <textarea name="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 class="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-2">수리비용 (원)</label>
                    <input type="number" name="cost" min="0" step="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-semibold text-gray-700 mb-2">외주업체</label>
                    <input type="text" name="vendor"
                           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-semibold text-gray-700 mb-2">수리자</label>
                    <select name="repaired_by"
                            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>
                        @foreach($users as $user)
                            <option value="{{ $user->id }}">{{ $user->name }}</option>
                        @endforeach
                    </select>
                </div>
            </div>

            <div>
                <label class="block text-sm font-semibold text-gray-700 mb-2">비고</label>
                <textarea name="memo" rows="2"
                          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 class="flex gap-3 pt-2">
                <button type="submit" class="bg-blue-600 hover:bg-blue-700 text-white px-6 py-2 rounded-lg transition">
                    등록
                </button>
                <a href="{{ route('equipment.repairs') }}"
                   class="bg-gray-200 hover:bg-gray-300 text-gray-800 px-6 py-2 rounded-lg transition">
                    취소
                </a>
            </div>
        </form>
    </div>
</div>

@endsection

@push('scripts')
<script>
    // 목업 데이터 자동 입력
    document.getElementById('mockFillBtn').addEventListener('click', function() {
        const form = document.getElementById('repairForm');
        const pick = arr => arr[Math.floor(Math.random() * arr.length)];
        const rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

        // 설비 랜덤 선택
        const eqSelect = form.querySelector('[name="equipment_id"]');
        const eqOptions = [...eqSelect.options].filter(o => o.value);
        if (eqOptions.length) eqSelect.value = pick(eqOptions).value;

        // 수리일 (최근 30일 이내 랜덤)
        const d = new Date();
        d.setDate(d.getDate() - rand(0, 30));
        form.querySelector('[name="repair_date"]').value = d.toISOString().slice(0, 10);

        // 보전구분
        form.querySelector('[name="repair_type"]').value = pick(['internal', 'external']);

        // 수리시간
        form.querySelector('[name="repair_hours"]').value = pick([0.5, 1, 1.5, 2, 3, 4, 5, 8]);

        // 수리내용
        const descriptions = [
            '베어링 마모로 인한 교체 작업 완료',
            '모터 과열 현상 점검 및 냉각팬 교체',
            '컨베이어 벨트 장력 조절 및 정렬 작업',
            '유압실린더 오일 누유 패킹 교체',
            '센서 오작동으로 인한 리미트 스위치 교체',
            '기어박스 윤활유 교체 및 이음 점검',
            '에어필터 교체 및 공압 라인 청소',
            '전기배선 절연 불량 부위 보수',
            '브레이크 패드 마모 교체 및 조정',
            '제어반 PCB 기판 수리 및 펌웨어 업데이트',
        ];
        form.querySelector('[name="description"]').value = pick(descriptions);

        // 수리비용
        form.querySelector('[name="cost"]').value = pick([0, 50000, 100000, 150000, 250000, 500000, 800000, 1200000]);

        // 외주업체 (외주일 때만)
        const vendors = ['', '대한설비', '한국기계서비스', '삼성엔지니어링', '동아기전', 'KM테크'];
        const isExternal = form.querySelector('[name="repair_type"]').value === 'external';
        form.querySelector('[name="vendor"]').value = isExternal ? pick(vendors.slice(1)) : '';

        // 수리자 랜덤 선택
        const userSelect = form.querySelector('[name="repaired_by"]');
        const userOptions = [...userSelect.options].filter(o => o.value);
        if (userOptions.length) userSelect.value = pick(userOptions).value;

        // 비고
        const memos = ['', '', '', '정기점검 시 발견', '긴급 수리', '재발 방지 대책 수립 필요', '부품 입고 대기 후 작업'];
        form.querySelector('[name="memo"]').value = pick(memos);

        showToast('목업 데이터가 입력되었습니다.', 'success');
    });

    document.getElementById('repairForm').addEventListener('submit', function(e) {
        e.preventDefault();

        const formData = new FormData(this);
        const data = Object.fromEntries(formData.entries());

        fetch('/api/admin/equipment/repairs', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}',
                'Accept': 'application/json',
            },
            body: JSON.stringify(data)
        })
        .then(r => r.json())
        .then(data => {
            if (data.success) {
                showToast(data.message, 'success');
                window.location.href = '{{ route("equipment.repairs") }}';
            } else {
                showToast(data.message || '등록에 실패했습니다.', 'error');
            }
        })
        .catch(() => showToast('서버 오류가 발생했습니다.', 'error'));
    });
</script>
@endpush
