@extends('layouts.app')

@section('content')
<div class="container mx-auto px-4 sm:px-6 lg:px-8">
    <div class="bg-white rounded-lg shadow-lg p-6">
        <div class="flex justify-between items-center mb-6">
            <h1 class="text-2xl font-bold text-gray-900">إنشاء إذن صرف جديد</h1>
            <a href="{{ route('inventory.issues.index') }}" class="inline-flex items-center px-4 py-2 bg-gray-200 text-gray-700 rounded-md hover:bg-gray-300 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-gray-500">
                <svg class="h-5 w-5 ml-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 19l-7-7m0 0l7-7m-7 7h18" />
                </svg>
                العودة للقائمة
            </a>
        </div>

        @if ($errors->any())
        <div class="mb-6 bg-red-50 p-4 rounded-md">
            <div class="flex">
                <div class="flex-shrink-0">
                    <svg class="h-5 w-5 text-red-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
                        <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clip-rule="evenodd" />
                    </svg>
                </div>
                <div class="mr-3">
                    <h3 class="text-sm font-medium text-red-800">يوجد {{ $errors->count() }} أخطاء في البيانات المدخلة</h3>
                    <div class="mt-2 text-sm text-red-700">
                        <ul class="list-disc list-inside space-y-1">
                            @foreach ($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        @endif

        <form action="{{ route('inventory.issues.store') }}" method="POST">
            @csrf
            
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">
                <div>
                    <label for="document_number" class="block text-sm font-medium text-gray-700 mb-1">رقم إذن الصرف <span class="text-green-600">(تلقائي)</span></label>
                    <input type="text" id="document_number" name="document_number" value="{{ old('document_number', $nextIssueNumber) }}" readonly class="block w-full rounded-md border-gray-300 bg-gray-100 shadow-sm text-gray-700 font-semibold">
                    @error('document_number')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>
                
                <div>
                    <label for="document_date" class="block text-sm font-medium text-gray-700 mb-1">تاريخ المستند</label>
                    <input type="date" id="document_date" name="document_date" value="{{ old('document_date', date('Y-m-d')) }}" required class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                    @error('document_date')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            <div class="grid grid-cols-1 md:grid-cols-3 gap-6 mb-6">
                <div>
                    <label for="from_warehouse_id" class="block text-sm font-medium text-gray-700 mb-1">المخزن</label>
                    <select id="from_warehouse_id" name="from_warehouse_id" required class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                        <option value="">اختر المخزن</option>
                        @foreach($warehouses as $warehouse)
                            <option value="{{ $warehouse->id }}" {{ old('from_warehouse_id') == $warehouse->id ? 'selected' : '' }}>{{ $warehouse->name }}</option>
                        @endforeach
                    </select>
                    @error('from_warehouse_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-medium text-gray-700 mb-1">فاتورة مبيعات العميل</label>
                    <select id="customer_invoice_id" name="customer_invoice_id" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">
                        <option value="">-- اختر فاتورة العميل --</option>
                        @foreach($customerInvoices as $invoice)
                            <option value="{{ $invoice->id }}" {{ (old('customer_invoice_id') ?? $selectedInvoiceId ?? null) == $invoice->id ? 'selected' : '' }}>
                                {{ $invoice->invoice_number }} - {{ $invoice->customer->name ?? $invoice->customer_name }}
                            </option>
                        @endforeach
                    </select>
                    @error('customer_invoice_id')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>

                <div>
                    <label for="reference_number" class="block text-sm font-medium text-gray-700 mb-1">رقم المرجع</label>
                    <input type="text" id="reference_number" name="reference_number" value="{{ old('reference_number') }}" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50" placeholder="رقم المرجع (اختياري)">
                    @error('reference_number')
                        <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                    @enderror
                </div>
            </div>

            <div class="mb-6">
                <label for="notes" class="block text-sm font-medium text-gray-700 mb-1">ملاحظات</label>
                <textarea id="notes" name="notes" rows="3" class="block w-full rounded-md border-gray-300 shadow-sm focus:border-primary-500 focus:ring focus:ring-primary-500 focus:ring-opacity-50">{{ old('notes') }}</textarea>
                @error('notes')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
            </div>
            
            <div class="mb-6">
                <div class="flex justify-between items-center mb-4">
                    <h2 class="text-lg font-semibold text-gray-900">الأصناف</h2>
                    <button type="button" id="add-item" class="inline-flex items-center px-4 py-2 bg-blue-600 text-white text-sm font-medium rounded-lg hover:bg-blue-700 transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 shadow-md">
                        <svg class="h-5 w-5 ml-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 6v6m0 0v6m0-6h6m-6 0H6" />
                        </svg>
                        إضافة صنف جديد
                    </button>
                </div>
                
                <div class="border border-gray-200 rounded-lg overflow-hidden shadow-md bg-white">
                    <div class="overflow-x-auto">
                        <table class="w-full table-fixed" id="items-table">
                            <colgroup>
                                <col style="width: 26%;">
                                <col style="width: 13%;">
                                <col style="width: 10%;">
                                <col style="width: 10%;">
                                <col style="width: 11%;">
                                <col style="width: 18%;">
                                <col style="width: 12%;">
                                <col style="width: 40px;">
                            </colgroup>
                            <thead>
                                <tr class="bg-gradient-to-r from-gray-800 to-gray-900 text-white">
                                    <th scope="col" class="px-1.5 py-2.5 text-right text-sm font-semibold">الصنف</th>
                                    <th scope="col" class="px-1.5 py-2.5 text-right text-sm font-semibold">الوحدة</th>
                                    <th scope="col" class="px-1.5 py-2.5 text-center text-sm font-semibold">الكمية</th>
                                    <th scope="col" class="px-1.5 py-2.5 text-center text-sm font-semibold">التكلفة</th>
                                    <th scope="col" class="px-1.5 py-2.5 text-center text-sm font-semibold">الإجمالي</th>
                                    <th scope="col" class="px-1.5 py-2.5 text-right text-sm font-semibold">مركز التكلفة</th>
                                    <th scope="col" class="px-1.5 py-2.5 text-right text-sm font-semibold">ملاحظات</th>
                                    <th scope="col" class="px-1 py-2.5 text-center text-sm font-semibold">حذف</th>
                                </tr>
                            </thead>
                            <tbody class="divide-y divide-gray-200 bg-white" id="items-container">
                            </tbody>
                            <tfoot class="bg-gradient-to-r from-gray-100 to-gray-50 border-t-2 border-gray-300">
                                <tr>
                                    <td colspan="4" class="px-1.5 py-3 text-right text-sm font-bold text-gray-900">الإجمالي الكلي:</td>
                                    <td class="px-1.5 py-3 text-center text-lg font-bold text-gray-900 bg-blue-100 border-r border-gray-300">
                                        <span id="total-cost">0.00</span>
                                    </td>
                                    <td colspan="3"></td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
                
                @error('item_ids')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
                
                @error('item_ids.*')
                    <p class="mt-1 text-sm text-red-600">{{ $message }}</p>
                @enderror
            </div>
            
            <div class="flex justify-end gap-3">
                <button type="submit" class="inline-flex items-center px-6 py-3 bg-green-600 text-white font-medium rounded-lg hover:bg-green-700 transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 shadow-md">
                    <svg class="h-5 w-5 ml-2" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                    </svg>
                    حفظ الإذن
                </button>
            </div>
        </form>
    </div>
</div>

<template id="item-template">
    <tr class="item-row hover:bg-blue-50 transition-colors">
        <td class="px-1.5 py-2.5 text-right">
            <select name="item_ids[]" required class="item-select block w-full rounded-md border border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50 text-sm">
                <option value="">اختر الصنف</option>
                @foreach($items as $item)
                    <option value="{{ $item->id }}" data-primary-unit="{{ $item->primary_unit_id }}">{{ $item->name }}</option>
                @endforeach
            </select>
        </td>
        
        <td class="px-1.5 py-2.5 text-right">
            <select name="unit_ids[]" required class="unit-select block w-full rounded-md border border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50 text-sm">
                <option value="">اختر الوحدة</option>
            </select>
        </td>
        
        <td class="px-1.5 py-2.5">
            <input type="number" name="quantities[]" step="0.01" min="0.01" required class="quantity-input block w-full rounded-md border border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50 text-sm text-center" placeholder="0.00">
        </td>
        
        <td class="px-1.5 py-2.5">
            <input type="number" name="unit_costs[]" step="0.01" min="0" required class="cost-input block w-full rounded-md border border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50 text-sm text-center" placeholder="0.00">
        </td>
        
        <td class="px-1.5 py-2.5">
            <input type="number" step="0.01" readonly class="total-input block w-full rounded-md border border-gray-300 bg-gray-50 shadow-sm text-sm text-center font-semibold text-gray-900" placeholder="0.00">
        </td>
        
        <td class="px-1.5 py-2.5 text-right">
            <select name="cost_center_ids[]" class="cost-center-select block w-full rounded-md border border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50 text-sm">
                <option value="">-- بدون --</option>
                @foreach($costCenters as $center)
                    <option value="{{ $center->id }}">{{ $center->code }} - {{ $center->name }}</option>
                @endforeach
            </select>
        </td>
        
        <td class="px-1.5 py-2.5">
            <input type="text" name="item_notes[]" class="block w-full rounded-md border border-gray-300 shadow-sm focus:border-blue-500 focus:ring focus:ring-blue-500 focus:ring-opacity-50 text-sm" placeholder="إضافة ملاحظة...">
        </td>
        
        <td class="px-1 py-2.5 text-center">
            <button type="button" class="remove-item text-red-600 hover:text-red-900 hover:bg-red-50 rounded p-1.5 transition-colors" title="حذف الصنف">
                <svg class="h-5 w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
            </button>
        </td>
    </tr>
</template>

@endsection

@push('styles')
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
<style>
    .select2-container--bootstrap-5 .select2-selection--single {
        height: calc(1.5em + .75rem + 2px);
        padding: .375rem .75rem;
    }
    .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered {
        padding-right: .75rem;
    }
    .select2-search__field {
        direction: rtl;
        text-align: right;
    }
    .select2-dropdown {
        direction: rtl;
        text-align: right;
    }
    
    #items-table {
        border-collapse: collapse;
    }
    
    #items-table thead tr {
        border-spacing: 0;
    }
    
    #items-table tbody tr {
        border-bottom: 1px solid #e5e7eb;
        border-spacing: 0;
    }
    
    #items-table tbody tr:hover {
        background-color: #f3f4f6;
    }
    
    #items-table td, #items-table th {
        border-spacing: 0;
    }
    
    #items-table input,
    #items-table select {
        height: 2.25rem;
        box-sizing: border-box;
    }
    
    .quantity-input, .cost-input, .total-input {
        font-variant-numeric: tabular-nums;
    }
    
    th:first-child {
        text-align: right;
    }
</style>
@endpush

@push('scripts')
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
    async function populateInvoiceItems(invoiceId) {
        if (!invoiceId) {
            return;
        }

        try {
            const response = await fetch(`/inventory/invoices/${invoiceId}/items`, {
                headers: {
                    'Accept': 'application/json',
                    'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]')?.getAttribute('content') || ''
                }
            });

            if (!response.ok) {
                console.error('Error fetching invoice items:', response.status);
                return;
            }

            const data = await response.json();
            
            if (!data.success || !data.data || !data.data.items) {
                console.error('Invalid response format');
                return;
            }

            const container = document.getElementById('items-container');
            container.innerHTML = '';

            for (const item of data.data.items) {
                const template = document.getElementById('item-template');
                const newRow = document.importNode(template.content, true);
                
                const itemSelect = newRow.querySelector('.item-select');
                itemSelect.value = item.item_id;
                
                const unitSelect = newRow.querySelector('.unit-select');
                const quantityInput = newRow.querySelector('.quantity-input');
                const costInput = newRow.querySelector('.cost-input');
                
                quantityInput.value = item.quantity;
                costInput.value = item.unit_cost;

                container.appendChild(newRow);

                setTimeout(() => {
                    $(container).find('.item-select:last').select2({
                        theme: 'bootstrap-5',
                        width: '100%',
                        dir: 'rtl'
                    }).val(item.item_id).trigger('change.select2');

                    $(container).find('.unit-select:last').select2({
                        theme: 'bootstrap-5',
                        width: '100%',
                        dir: 'rtl'
                    });

                    $(container).find('.cost-center-select:last').select2({
                        theme: 'bootstrap-5',
                        width: '100%',
                        dir: 'rtl'
                    });

                    const unitSelectElement = $(container).find('.unit-select:last');
                    const costInputElement = $(container).find('.cost-input:last');
                    
                    setTimeout(() => {
                        unitSelectElement.val(item.unit_id).trigger('change.select2');
                        costInputElement.trigger('input');
                    }, 300);
                }, 100);
            }

            updateTotalCost();
        } catch (error) {
            console.error('Error:', error);
        }
    }

    document.addEventListener('DOMContentLoaded', function() {
        const selectedInvoiceId = document.getElementById('customer_invoice_id')?.value || '{{ $selectedInvoiceId ?? '' }}';
        
        if (selectedInvoiceId) {
            setTimeout(() => {
                populateInvoiceItems(selectedInvoiceId);
            }, 500);
        } else {
            addItemRow();
        }
        
        document.getElementById('add-item').addEventListener('click', addItemRow);
        
        document.getElementById('customer_invoice_id').addEventListener('change', function() {
            const invoiceId = this.value;
            if (invoiceId) {
                populateInvoiceItems(invoiceId);
            } else {
                document.getElementById('items-container').innerHTML = '';
                addItemRow();
            }
        });
        
        document.addEventListener('click', function(e) {
            if (e.target.classList.contains('remove-item') || 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).on('change.select2', '.item-select', function() {
            const selectElement = this;
            const row = $(selectElement).closest('.item-row');
            const unitSelect = row.find('.unit-select');
            const itemId = $(selectElement).val();
            
            unitSelect.html('<option value="">اختر الوحدة</option>');
            unitSelect.prop('disabled', true);
            
            if (itemId) {
                const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
                
                fetch(`{{ route("inventory.items.units.api", ":itemId") }}`.replace(':itemId', itemId.toString()), {
                    headers: {
                        'X-CSRF-TOKEN': token,
                        'Accept': 'application/json',
                        'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
                    if (data.success && data.data && data.data.length > 0) {
                        unitSelect.html('<option value="">اختر الوحدة</option>');
                        data.data.forEach(unit => {
                            const option = document.createElement('option');
                            option.value = unit.id;
                            option.textContent = unit.unit_name;
                            if (unit.is_default) option.selected = true;
                            unitSelect.append(option);
                        });
                        unitSelect.prop('disabled', false);
                    } else {
                        unitSelect.html('<option value="">لا توجد وحدات</option>');
                        unitSelect.prop('disabled', true);
                    }
                })
                .catch(error => {
                    console.error('خطأ في جلب الوحدات:', error);
                    unitSelect.html('<option value="">خطأ في تحميل الوحدات</option>');
                    unitSelect.prop('disabled', true);
                });
            }
        });
        
        document.addEventListener('input', function(e) {
            if (e.target.classList.contains('quantity-input') || e.target.classList.contains('cost-input')) {
                const row = e.target.closest('.item-row');
                const qty = parseFloat(row.querySelector('.quantity-input').value) || 0;
                const cost = parseFloat(row.querySelector('.cost-input').value) || 0;
                const total = (qty * cost).toFixed(2);
                row.querySelector('.total-input').value = total;
                updateTotalCost();
            }
        });
        
        function addItemRow() {
            const template = document.getElementById('item-template');
            const container = document.getElementById('items-container');
            const newRow = document.importNode(template.content, true);
            container.appendChild(newRow);
            
            $(container).find('.item-select:last').select2({
                theme: 'bootstrap-5',
                width: '100%',
                dir: 'rtl'
            });
            $(container).find('.unit-select:last').select2({
                theme: 'bootstrap-5',
                width: '100%',
                dir: 'rtl'
            });
            $(container).find('.cost-center-select:last').select2({
                theme: 'bootstrap-5',
                width: '100%',
                dir: 'rtl'
            });
        }
        
        function updateTotalCost() {
            let total = 0;
            document.querySelectorAll('.total-input').forEach(input => {
                total += parseFloat(input.value) || 0;
            });
            document.getElementById('total-cost').textContent = total.toFixed(2);
        }
        
        $('.item-select, .unit-select, .cost-center-select').select2({
            theme: 'bootstrap-5',
            width: '100%',
            dir: 'rtl'
        });
    });
</script>
@endpush
