@extends('layouts.admin')

@section('title', 'Edit Stock Opname')

@section('content')
    <!-- Header -->
    <div class="flex items-center justify-between mb-6">
        <div class="flex items-center space-x-3">
            <a href="{{ route('admin.backoffice.stock-opname.index') }}"
                class="flex items-center justify-center w-10 h-10 text-gray-600 dark:text-gray-300 hover:text-gray-900 dark:hover:text-white hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors duration-200"
                title="Kembali">
                <i class="fas fa-arrow-left text-lg"></i>
            </a>
            <div>
                <h1 class="text-2xl font-bold text-gray-800 dark:text-white">Edit Stock Opname</h1>
                <p class="text-sm text-gray-500 dark:text-gray-400 mt-0.5">
                    {{ $stockOpname->opname_number }}
                </p>
            </div>
        </div>
    </div>

    <!-- Success/Error Messages -->
    @if (session('error'))
        <div class="mb-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 px-4 py-3 rounded-lg text-sm">
            <i class="fas fa-exclamation-circle mr-2"></i>{{ session('error') }}
        </div>
    @endif

    @if ($errors->any())
        <div class="mb-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 text-red-800 dark:text-red-200 px-4 py-3 rounded-lg text-sm">
            <div class="font-medium mb-2">Terdapat kesalahan:</div>
            <ul class="list-disc list-inside space-y-1 text-xs">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <!-- Form Container -->
    <div class="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 transition-colors duration-300">
        <form action="{{ route('admin.backoffice.stock-opname.update', $stockOpname->id) }}" method="POST" id="stockOpnameForm" class="p-5">
            @csrf
            @method('PUT')

            <!-- Header Info -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-5 mb-6">
                <!-- Tanggal Opname -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Tanggal Opname <span class="text-red-500">*</span>
                    </label>
                    <input type="date" name="opname_date" value="{{ old('opname_date', $stockOpname->opname_date->format('Y-m-d')) }}" required
                        max="{{ date('Y-m-d') }}"
                        class="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm @error('opname_date') border-red-500 @enderror">
                    @error('opname_date')
                        <p class="text-red-600 dark:text-red-400 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>

                <!-- Catatan -->
                <div>
                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        Catatan
                    </label>
                    <input type="text" name="notes" value="{{ old('notes', $stockOpname->notes) }}"
                        placeholder="Catatan tambahan (opsional)..."
                        class="w-full px-4 py-2.5 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white text-sm @error('notes') border-red-500 @enderror">
                    @error('notes')
                        <p class="text-red-600 dark:text-red-400 text-xs mt-1">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            <!-- Items Section -->
            <div class="mb-6">
                <div class="flex justify-between items-center mb-4">
                    <h3 class="text-base font-semibold text-gray-800 dark:text-white">
                        <i class="fas fa-list-ul mr-2 text-blue-600 dark:text-blue-400"></i>Daftar Item ({{ $stockOpname->items->count() }} Item)
                    </h3>
                    <div class="px-3 py-1.5 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg text-xs text-blue-700 dark:text-blue-300">
                        <i class="fas fa-info-circle mr-1"></i>
                        Edit hanya untuk update quantity dan alasan
                    </div>
                </div>

                <div class="overflow-x-auto border border-gray-300 dark:border-gray-600 rounded-lg">
                    <table class="w-full" id="itemsTable">
                        <thead class="bg-gray-50 dark:bg-gray-700">
                            <tr>
                                <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-200">No</th>
                                <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-200">Tipe</th>
                                <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-200">Item</th>
                                <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-200">Kode</th>
                                <th class="px-4 py-3 text-right text-xs font-semibold text-gray-700 dark:text-gray-200">Stok Sistem</th>
                                <th class="px-4 py-3 text-right text-xs font-semibold text-gray-700 dark:text-gray-200">Stok Fisik</th>
                                <th class="px-4 py-3 text-right text-xs font-semibold text-gray-700 dark:text-gray-200">Selisih</th>
                                <th class="px-4 py-3 text-left text-xs font-semibold text-gray-700 dark:text-gray-200">Alasan</th>
                            </tr>
                        </thead>
                        <tbody id="itemsTableBody" class="divide-y divide-gray-200 dark:divide-gray-600">
                            @foreach ($stockOpname->items as $index => $item)
                                @php
                                    $itemType = str_contains($item->itemable_type, 'Material')
                                        ? 'Material'
                                        : 'Sparepart';
                                    $difference = $item->physical_qty - $item->system_qty;
                                @endphp
                                <tr class="bg-white dark:bg-gray-800 hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors duration-200" id="row-{{ $index }}">
                                    <td class="px-4 py-3 text-xs text-gray-700 dark:text-gray-300">{{ $index + 1 }}</td>
                                    <td class="px-4 py-3">
                                        @php
                                            $bgClass =
                                                $itemType === 'Material'
                                                    ? 'bg-blue-100 dark:bg-blue-900/40 text-blue-700 dark:text-blue-300'
                                                    : 'bg-purple-100 dark:bg-purple-900/40 text-purple-700 dark:text-purple-300';
                                        @endphp

                                        <span class="px-2 py-1 rounded text-xs font-semibold {{ $bgClass }}">
                                            {{ $itemType }}
                                        </span>
                                    </td>
                                    <td class="px-4 py-3 text-xs font-medium text-gray-800 dark:text-gray-200">
                                        {{ $item->item_name }}
                                    </td>
                                    <td class="px-4 py-3 text-xs font-mono text-gray-700 dark:text-gray-300">
                                        {{ $item->item_code }}
                                    </td>
                                    <td class="px-4 py-3">
                                        <input type="text" readonly
                                            value="{{ $item->system_qty }} {{ $item->unit }}"
                                            id="system-{{ $index }}" data-qty="{{ $item->system_qty }}"
                                            data-unit="{{ $item->unit }}"
                                            class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right bg-gray-100 dark:bg-gray-600 font-medium text-gray-900 dark:text-white">
                                    </td>
                                    <td class="px-4 py-3">
                                        <input type="number" name="items[{{ $index }}][physical_qty]"
                                            step="1" min="0"
                                            value="{{ old('items.' . $index . '.physical_qty', $item->physical_qty) }}"
                                            id="physical-{{ $index }}" required
                                            oninput="calculateDifference({{ $index }})"
                                            class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right focus:ring-2 focus:ring-blue-500 transition-colors duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                                    </td>
                                    <td class="px-4 py-3">
                                        <input type="text" id="difference-{{ $index }}" readonly
                                            class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right font-semibold bg-gray-100 dark:bg-gray-600 text-gray-900 dark:text-white">
                                    </td>
                                    <td class="px-4 py-3">
                                        <input type="text" name="items[{{ $index }}][reason]"
                                            value="{{ old('items.' . $index . '.reason', $item->reason) }}"
                                            placeholder="Alasan selisih..."
                                            class="w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs focus:ring-2 focus:ring-blue-500 transition-colors duration-200 bg-white dark:bg-gray-700 text-gray-900 dark:text-white">
                                    </td>

                                    {{-- Hidden inputs --}}
                                    <input type="hidden" name="items[{{ $index }}][id]"
                                        value="{{ $item->id }}">
                                    <input type="hidden" name="items[{{ $index }}][itemable_type]"
                                        value="{{ $item->itemable_type }}">
                                    <input type="hidden" name="items[{{ $index }}][itemable_id]"
                                        value="{{ $item->itemable_id }}">
                                </tr>
                            @endforeach
                        </tbody>
                    </table>
                </div>

                @if ($stockOpname->items->count() === 0)
                    <p class="text-sm text-gray-500 dark:text-gray-400 mt-3 flex items-center">
                        <i class="fas fa-info-circle mr-2"></i>
                        Tidak ada item untuk diedit
                    </p>
                @endif
            </div>

            <!-- Submit Buttons -->
            <div class="flex justify-end space-x-3 pt-6 border-t border-gray-200 dark:border-gray-700 mt-6">
                <a href="{{ route('admin.backoffice.stock-opname.index') }}"
                    class="px-6 py-2.5 text-gray-600 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors duration-200 font-medium text-sm">
                    Batal
                </a>
                <button type="submit"
                    class="px-6 py-2.5 bg-blue-600 hover:bg-blue-700 text-white font-medium rounded-lg transition-colors duration-200 flex items-center space-x-2 text-sm">
                    <i class="fas fa-save"></i>
                    <span>Update Stock Opname</span>
                </button>
            </div>
        </form>
    </div>

    <script>
        // Calculate difference for all items on page load
        window.addEventListener('DOMContentLoaded', function() {
            @foreach ($stockOpname->items as $index => $item)
                calculateDifference({{ $index }});
            @endforeach
        });

        function calculateDifference(index) {
            const systemEl = document.getElementById(`system-${index}`);
            const physicalInput = document.getElementById(`physical-${index}`);

            const physicalQty = parseFloat(physicalInput.value);
            const systemQty = parseFloat(systemEl.dataset.qty);
            const unit = systemEl.dataset.unit || '';

            if (isNaN(physicalQty) || isNaN(systemQty)) {
                document.getElementById(`difference-${index}`).value = '';
                return;
            }

            // Hitung selisih: Fisik - Sistem
            const diff = physicalQty - systemQty;

            const diffEl = document.getElementById(`difference-${index}`);
            diffEl.value = (diff >= 0 ? '+' : '') + Math.round(diff) + ' ' + unit;

            // Styling berdasarkan selisih
            if (diff > 0) {
                diffEl.className =
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right font-semibold bg-green-50 dark:bg-green-900/40 text-green-600 dark:text-green-300';
            } else if (diff < 0) {
                diffEl.className =
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right font-semibold bg-red-50 dark:bg-red-900/40 text-red-600 dark:text-red-300';
            } else {
                diffEl.className =
                    'w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-lg text-xs text-right font-semibold bg-gray-100 dark:bg-gray-600 text-gray-600 dark:text-gray-200';
            }
        }

        // Validasi sebelum submit
        document.getElementById('stockOpnameForm').addEventListener('submit', function(e) {
            const tbody = document.getElementById('itemsTableBody');

            if (tbody.children.length === 0) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Item Kosong',
                    text: 'Tidak ada item untuk diupdate!',
                    confirmButtonColor: '#3b82f6'
                });
                return false;
            }

            // Validasi physical qty harus diisi
            let isValid = true;
            const physicalInputs = tbody.querySelectorAll('input[name*="[physical_qty]"]');

            physicalInputs.forEach((input) => {
                if (!input.value || input.value === '') {
                    isValid = false;
                }
            });

            if (!isValid) {
                e.preventDefault();
                Swal.fire({
                    icon: 'warning',
                    title: 'Data Tidak Lengkap',
                    text: 'Lengkapi semua stok fisik sebelum menyimpan!',
                    confirmButtonColor: '#3b82f6'
                });
                return false;
            }
        });
    </script>
@endsection
