@extends('layouts.app')

@section('title', 'إنشاء أذن صرف خامات جديدة')

@section('content')
<div class="min-h-screen bg-gradient-to-br from-slate-50 to-slate-100 py-8 px-4 md:px-8">
    <div class="max-w-4xl mx-auto">
        <!-- رأس الصفحة -->
        <div class="mb-8">
            <h1 class="text-3xl font-bold text-gray-900 mb-2">إنشاء أذن صرف خامات جديدة</h1>
            <p class="text-gray-600">أضف أذن صرف جديدة لمواد الخام من المخزن إلى موقع الإنتاج</p>
        </div>

        <!-- النموذج -->
        <div class="bg-white rounded-xl shadow-lg overflow-hidden border border-gray-200">
            <div class="p-8">
                <form action="{{ route('inventory.raw-materials-issues.store') }}" method="POST" class="space-y-6">
                    @csrf

                    <!-- البيانات الأساسية -->
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <!-- التاريخ -->
                        <div>
                            <label for="document_date" class="block text-sm font-semibold text-gray-700 mb-2">
                                <i class="fas fa-calendar ml-1 text-blue-600"></i>
                                التاريخ
                            </label>
                            <input type="date" 
                                   id="document_date" 
                                   name="document_date" 
                                   class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                   value="{{ date('Y-m-d') }}"
                                   required>
                            @error('document_date')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>

                        <!-- المخزن -->
                        <div>
                            <label for="warehouse_id" class="block text-sm font-semibold text-gray-700 mb-2">
                                <i class="fas fa-warehouse ml-1 text-blue-600"></i>
                                المخزن
                            </label>
                            <select id="warehouse_id" 
                                    name="warehouse_id" 
                                    class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                    required>
                                <option value="">-- اختر المخزن --</option>
                                @foreach($warehouses as $warehouse)
                                    <option value="{{ $warehouse->id }}">{{ $warehouse->name }}</option>
                                @endforeach
                            </select>
                            @error('warehouse_id')
                                <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                            @enderror
                        </div>
                    </div>

                    <!-- موقع الإنتاج -->
                    <div>
                        <label for="production_site_id" class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-building ml-1 text-blue-600"></i>
                            موقع الإنتاج / خط الإنتاج <span class="text-gray-400 text-xs">(اختياري)</span>
                        </label>
                        <select id="production_site_id" 
                                name="production_site_id" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <option value="">-- اختر موقع الإنتاج --</option>
                            @foreach($productionSites as $site)
                                <option value="{{ $site->id }}">{{ $site->name }}</option>
                            @endforeach
                        </select>
                        @error('production_site_id')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- فاتورة مبيعات العميل -->
                    <div>
                        <label for="customer_invoice_id" class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-file-invoice ml-1 text-blue-600"></i>
                            فاتورة مبيعات العميل <span class="text-gray-400 text-xs">(اختياري)</span>
                        </label>
                        <select id="customer_invoice_id" 
                                name="customer_invoice_id" 
                                class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent">
                            <option value="">-- اختر فاتورة العميل --</option>
                            @foreach($customerInvoices as $invoice)
                                <option value="{{ $invoice->id }}">{{ $invoice->invoice_number }} - {{ $invoice->customer_name }}</option>
                            @endforeach
                        </select>
                        @error('customer_invoice_id')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                        <p class="mt-1 text-xs text-gray-500">الفواتير المعروضة هنا هي الفواتير التي تم إرسالها فقط</p>
                    </div>

                    <!-- الوصف -->
                    <div>
                        <label for="description" class="block text-sm font-semibold text-gray-700 mb-2">
                            <i class="fas fa-file-alt ml-1 text-blue-600"></i>
                            الوصف / ملاحظات
                        </label>
                        <textarea id="description" 
                                  name="description" 
                                  rows="3"
                                  class="w-full px-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent"
                                  placeholder="أضف أي ملاحظات إضافية..."></textarea>
                        @error('description')
                            <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- جدول الأصناف -->
                    <div>
                        <div class="flex justify-between items-center mb-4">
                            <label class="block text-sm font-semibold text-gray-700">
                                <i class="fas fa-list ml-1 text-blue-600"></i>
                                الأصناف
                            </label>
                            <button type="button" 
                                    id="add-item-btn"
                                    class="inline-flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors text-sm font-medium">
                                <i class="fas fa-plus ml-1"></i>
                                إضافة صنف
                            </button>
                        </div>

                        <div class="overflow-x-auto">
                            <table class="w-full border border-gray-300 rounded-lg overflow-hidden">
                                <thead class="bg-gray-100">
                                    <tr>
                                        <th class="px-4 py-3 text-right text-sm font-semibold text-gray-700">الصنف</th>
                                        <th class="px-4 py-3 text-right text-sm font-semibold text-gray-700">الوحدة</th>
                                        <th class="px-4 py-3 text-right text-sm font-semibold text-gray-700">الكمية</th>
                                        <th class="px-4 py-3 text-right text-sm font-semibold text-gray-700">سعر الوحدة</th>
                                        <th class="px-4 py-3 text-right text-sm font-semibold text-gray-700">الإجمالي</th>
                                        <th class="px-4 py-3 text-center text-sm font-semibold text-gray-700">الإجراء</th>
                                    </tr>
                                </thead>
                                <tbody id="items-container" class="divide-y divide-gray-300">
                                    <!-- يتم إضافة الصفوف هنا بواسطة JavaScript -->
                                </tbody>
                                <tfoot class="bg-gray-50">
                                    <tr>
                                        <td colspan="4" class="px-4 py-3 text-left font-semibold text-gray-700">الإجمالي:</td>
                                        <td class="px-4 py-3 text-right font-semibold text-gray-900" id="total-cost">0.00</td>
                                        <td></td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        @error('item_ids')
                            <p class="mt-2 text-sm text-red-600">{{ $message }}</p>
                        @enderror
                    </div>

                    <!-- الأزرار -->
                    <div class="flex justify-between gap-4 pt-4 border-t border-gray-200">
                        <a href="{{ route('inventory.raw-materials-issues.index') }}" 
                           class="px-6 py-2 text-gray-700 bg-gray-200 rounded-lg hover:bg-gray-300 transition-colors font-medium">
                            <i class="fas fa-arrow-right ml-1"></i>
                            إلغاء
                        </a>
                        <button type="submit" 
                                class="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors font-medium">
                            <i class="fas fa-save ml-1"></i>
                            حفظ
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<!-- Template للصف -->
<template id="item-row-template">
    <tr class="item-row">
        <td class="px-4 py-3">
            <select name="item_ids[]" class="item-select w-full px-3 py-2 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500" required>
                <option value="">-- اختر الصنف --</option>
                @foreach($items as $item)
                    <option value="{{ $item->id }}">{{ $item->name }}</option>
                @endforeach
            </select>
        </td>
        <td class="px-4 py-3">
            <select name="unit_ids[]" class="unit-select w-full px-3 py-2 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500" required>
                <option value="">-- اختر الوحدة --</option>
            </select>
        </td>
        <td class="px-4 py-3">
            <input type="number" 
                   name="quantities[]" 
                   step="0.01" 
                   class="quantity-input w-full px-3 py-2 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500"
                   placeholder="0"
                   required>
        </td>
        <td class="px-4 py-3">
            <input type="number" 
                   name="unit_costs[]" 
                   step="0.01" 
                   class="unit-cost-input w-full px-3 py-2 border border-gray-300 rounded focus:ring-2 focus:ring-blue-500"
                   placeholder="0"
                   required>
        </td>
        <td class="px-4 py-3 text-right">
            <input type="number" 
                   step="0.01" 
                   readonly 
                   class="item-total w-full px-3 py-2 border border-gray-300 rounded bg-gray-100"
                   value="0">
        </td>
        <td class="px-4 py-3 text-center">
            <button type="button" 
                    class="remove-item px-3 py-1 bg-red-100 text-red-600 rounded hover:bg-red-200 transition-colors">
                <i class="fas fa-trash"></i>
            </button>
        </td>
    </tr>
</template>

@push('scripts')
<script>
    document.addEventListener('DOMContentLoaded', function() {
        addItemRow();

        document.getElementById('add-item-btn').addEventListener('click', addItemRow);

        document.addEventListener('click', function(e) {
            if (e.target.closest('.remove-item')) {
                const row = e.target.closest('.item-row');
                if (document.querySelectorAll('.item-row').length > 1) {
                    row.remove();
                    updateTotalCost();
                } else {
                    alert('يجب أن تحتوي الأذن على صنف واحد على الأقل');
                }
            }
        });

        document.addEventListener('change', function(e) {
            if (e.target.classList.contains('item-select')) {
                const row = e.target.closest('.item-row');
                const unitSelect = row.querySelector('.unit-select');
                unitSelect.innerHTML = '<option value="">-- اختر الوحدة --</option>';
                
                if (e.target.value) {
                    fetch(`{{ route("inventory.items.units.api", ":itemId") }}`.replace(':itemId', e.target.value))
                        .then(r => r.json())
                        .then(data => {
                            if (data.success && data.data) {
                                data.data.forEach(unit => {
                                    const option = document.createElement('option');
                                    option.value = unit.id;
                                    option.textContent = unit.unit_name;
                                    unitSelect.appendChild(option);
                                });
                            }
                        })
                        .catch(err => console.error('Error loading units:', err));
                }
            }
        });

        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('quantity-input') || e.target.classList.contains('unit-cost-input')) {
                const row = e.target.closest('.item-row');
                const quantity = parseFloat(row.querySelector('.quantity-input').value) || 0;
                const unitCost = parseFloat(row.querySelector('.unit-cost-input').value) || 0;
                const itemTotal = row.querySelector('.item-total');
                itemTotal.value = (quantity * unitCost).toFixed(2);
                updateTotalCost();
            }
        });

        function addItemRow() {
            const template = document.getElementById('item-row-template');
            const container = document.getElementById('items-container');
            container.appendChild(document.importNode(template.content, true));
        }

        function updateTotalCost() {
            let total = 0;
            document.querySelectorAll('.item-total').forEach(input => {
                total += parseFloat(input.value) || 0;
            });
            document.getElementById('total-cost').textContent = total.toFixed(2);
        }
    });
</script>
@endpush
@endsection
