﻿<x-app-layout>
    <x-slot name="header">
        <h2 class="font-semibold text-l text-gray-800 leading-tight">
            {{ __('إضافة دفعة جديدة للمورد') }}
        </h2>
    </x-slot>

    <div class="py-2">
        <div class="max-w-full mx-auto sm:px-4 lg:px-6">
            <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg">
                <div class="p-4 bg-white border-b border-gray-200">
                    <form action="{{ route('supplier-payments.store') }}" method="POST" enctype="multipart/form-data">
                        @csrf

                        <div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-4">
                            <!-- المورد -->
                            <div>
                                <x-input-label for="supplier_id" :value="__('المورد')" class="text-xs font-bold" />
                                <select id="supplier_id" name="supplier_id" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm text-sm py-1.5" required>
                                    <option value="">{{ __('اختر المورد') }}</option>
                                    @foreach($suppliers as $supplier)
                                        <option value="{{ $supplier->id }}" {{ (old('supplier_id', $selected_supplier_id ?? '') == $supplier->id) ? 'selected' : '' }}>
                                            {{ $supplier->name }}
                                        </option>
                                    @endforeach
                                </select>
                                <x-input-error :messages="$errors->get('supplier_id')" class="mt-1 text-xs" />
                            </div>

                            <!-- الفاتورة -->
                            <div>
                                <x-input-label for="supplier_invoice_id" :value="__('الفاتورة')" class="text-xs font-bold" />
                                <select id="supplier_invoice_id" name="supplier_invoice_id" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm text-sm py-1.5">
                                    <option value="">{{ __('اختر الفاتورة (اختياري)') }}</option>
                                    @foreach($invoices as $invoice)
                                        <option value="{{ $invoice->id }}" data-supplier="{{ $invoice->supplier_id }}" data-remaining="{{ $invoice->remaining_amount }}" {{ (old('supplier_invoice_id', $selected_invoice_id ?? '') == $invoice->id) ? 'selected' : '' }}>
                                            {{ $invoice->invoice_number }} - {{ __('المبلغ المتبقي') }}: {{ number_format($invoice->remaining_amount, 2) }}
                                        </option>
                                    @endforeach
                                </select>
                                <x-input-error :messages="$errors->get('supplier_invoice_id')" class="mt-1 text-xs" />
                            </div>

                            <!-- رقم الدفعة -->
                            <div>
                                <x-input-label for="payment_number" :value="__('رقم الدفعة')" class="text-xs font-bold" />
                                <x-text-input id="payment_number" type="text" name="payment_number" :value="old('payment_number')" class="mt-1 block w-full text-sm py-1.5" required />
                                <x-input-error :messages="$errors->get('payment_number')" class="mt-1 text-xs" />
                            </div>

                            <!-- تاريخ الدفع -->
                            <div>
                                <x-input-label for="payment_date" :value="__('تاريخ الدفع')" class="text-xs font-bold" />
                                <x-text-input id="payment_date" type="date" name="payment_date" :value="old('payment_date', date('Y-m-d'))" class="mt-1 block w-full text-sm py-1.5" required />
                                <x-input-error :messages="$errors->get('payment_date')" class="mt-1 text-xs" />
                            </div>

                            <!-- المبلغ -->
                            <div>
                                <x-input-label for="amount" :value="__('المبلغ')" class="text-xs font-bold" />
                                <x-text-input id="amount" type="number" step="0.01" name="amount" :value="old('amount')" class="mt-1 block w-full text-sm py-1.5" required />
                                <x-input-error :messages="$errors->get('amount')" class="mt-1 text-xs" />
                            </div>

                            <!-- طريقة الدفع -->
                            <div>
                                <x-input-label for="payment_method" :value="__('طريقة الدفع')" class="text-xs font-bold" />
                                <select id="payment_method" name="payment_method" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm text-sm py-1.5" required>
                                    <option value="">{{ __('اختر طريقة الدفع') }}</option>
                                    <option value="cash" {{ old('payment_method') == 'cash' ? 'selected' : '' }}>{{ __('نقدي') }}</option>
                                    <option value="bank_transfer" {{ old('payment_method') == 'bank_transfer' ? 'selected' : '' }}>{{ __('تحويل بنكي') }}</option>
                                    <option value="cheque" {{ old('payment_method') == 'cheque' ? 'selected' : '' }}>{{ __('شيك') }}</option>
                                    <option value="credit_card" {{ old('payment_method') == 'credit_card' ? 'selected' : '' }}>{{ __('بطاقة ائتمان') }}</option>
                                    <option value="other" {{ old('payment_method') == 'other' ? 'selected' : '' }}>{{ __('أخرى') }}</option>
                                </select>
                                <x-input-error :messages="$errors->get('payment_method')" class="mt-1 text-xs" />
                            </div>

                            <!-- الحساب البنكي (يظهر فقط مع التحويل البنكي أو الشيك) -->
                            <div id="bank_account_container" class="hidden">
                                <x-input-label for="bank_account_id" :value="__('الحساب البنكي')" class="text-xs font-bold" />
                                <select id="bank_account_id" name="bank_account_id" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm text-sm py-1.5">
                                    <option value="">{{ __('اختر الحساب البنكي') }}</option>
                                    @foreach($bankAccounts as $account)
                                        <option value="{{ $account->id }}" {{ old('bank_account_id') == $account->id ? 'selected' : '' }}>
                                            {{ $account->bank_name }} - {{ $account->account_number }}
                                        </option>
                                    @endforeach
                                </select>
                                <x-input-error :messages="$errors->get('bank_account_id')" class="mt-1 text-xs" />
                            </div>

                            <!-- الخزينة (تظهر فقط مع الدفع النقدي) -->
                            <div id="treasury_container" class="hidden">
                                <x-input-label for="treasury_id" :value="__('الخزينة')" class="text-xs font-bold" />
                                <select id="treasury_id" name="treasury_id" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm text-sm py-1.5">
                                    <option value="">{{ __('اختر الخزينة') }}</option>
                                    @foreach($treasuries as $treasury)
                                        <option value="{{ $treasury->id }}" {{ old('treasury_id') == $treasury->id ? 'selected' : '' }}>
                                            {{ $treasury->name }}
                                        </option>
                                    @endforeach
                                </select>
                                <x-input-error :messages="$errors->get('treasury_id')" class="mt-1 text-xs" />
                            </div>

                            <!-- رقم المرجع -->
                            <div>
                                <x-input-label for="reference_number" :value="__('رقم المرجع')" class="text-xs font-bold" />
                                <x-text-input id="reference_number" type="text" name="reference_number" :value="old('reference_number')" class="mt-1 block w-full text-sm py-1.5" />
                                <x-input-error :messages="$errors->get('reference_number')" class="mt-1 text-xs" />
                            </div>

                            <!-- المرفق -->
                            <div>
                                <x-input-label for="attachment" :value="__('المرفق')" class="text-xs font-bold" />
                                <input id="attachment" type="file" name="attachment" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm text-sm py-1" />
                                <x-input-error :messages="$errors->get('attachment')" class="mt-1 text-xs" />
                            </div>

                            <!-- ملاحظات -->
                            <div class="md:col-span-2 lg:col-span-4">
                                <x-input-label for="notes" :value="__('ملاحظات')" class="text-xs font-bold" />
                                <textarea id="notes" name="notes" rows="2" class="mt-1 block w-full border-gray-300 rounded-md shadow-sm text-sm">{{ old('notes') }}</textarea>
                                <x-input-error :messages="$errors->get('notes')" class="mt-1 text-xs" />
                            </div>
                        </div>

                        <div class="flex justify-end mt-4 space-x-2 space-x-reverse">
                            <x-primary-button class="text-sm px-6 py-2">
                                {{ __('حفظ') }}
                            </x-primary-button>
                            <a href="{{ route('supplier-payments.index') }}" class="inline-flex items-center px-4 py-2 bg-gray-300 border border-transparent rounded-md font-semibold text-xs text-gray-800 tracking-widest hover:bg-gray-400 active:bg-gray-500 focus:outline-none focus:border-gray-500 focus:ring ring-gray-300 disabled:opacity-25 transition ease-in-out duration-150">
                                {{ __('إلغاء') }}
                            </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            // تحديث قائمة الفواتير عند تغيير المورد
            const supplierSelect = document.getElementById('supplier_id');
            const invoiceSelect = document.getElementById('supplier_invoice_id');
            const invoiceOptions = Array.from(invoiceSelect.options);

            supplierSelect.addEventListener('change', function() {
                const selectedSupplierId = this.value;
                
                // إعادة تعيين قائمة الفواتير
                invoiceSelect.innerHTML = '<option value="">{{ __("اختر الفاتورة (اختياري)") }}</option>';
                
                if (selectedSupplierId) {
                    // إضافة الفواتير المرتبطة بالمورد المحدد
                    invoiceOptions.forEach(option => {
                        if (option.value !== '' && option.dataset.supplier === selectedSupplierId) {
                            invoiceSelect.appendChild(option.cloneNode(true));
                        }
                    });
                }
            });

            // إظهار/إخفاء حقول الحساب البنكي والخزينة بناءً على طريقة الدفع
            const paymentMethodSelect = document.getElementById('payment_method');
            const bankAccountContainer = document.getElementById('bank_account_container');
            const treasuryContainer = document.getElementById('treasury_container');

            paymentMethodSelect.addEventListener('change', function() {
                const selectedMethod = this.value;
                
                // إخفاء كلا الحقلين أولاً
                bankAccountContainer.classList.add('hidden');
                treasuryContainer.classList.add('hidden');
                
                // إظهار الحقل المناسب بناءً على طريقة الدفع
                if (selectedMethod === 'bank_transfer' || selectedMethod === 'cheque') {
                    bankAccountContainer.classList.remove('hidden');
                } else if (selectedMethod === 'cash') {
                    treasuryContainer.classList.remove('hidden');
                }
            });

            // تحديث المبلغ عند اختيار فاتورة
            invoiceSelect.addEventListener('change', function() {
                const selectedOption = this.options[this.selectedIndex];
                const amountInput = document.getElementById('amount');
                
                if (this.value && selectedOption.dataset.remaining) {
                    amountInput.value = parseFloat(selectedOption.dataset.remaining).toFixed(2);
                    amountInput.dataset.remaining = selectedOption.dataset.remaining;
                } else {
                    amountInput.value = '';
                    delete amountInput.dataset.remaining;
                }
            });

            // تشغيل الأحداث عند تحميل الصفحة لتعيين الحالة الأولية
            if (paymentMethodSelect.value) {
                paymentMethodSelect.dispatchEvent(new Event('change'));
            }
            
            if (supplierSelect.value) {
                supplierSelect.dispatchEvent(new Event('change'));
                
                // إذا كانت هناك فاتورة محددة مسبقًا، نقوم بتحديدها
                const preSelectedInvoice = "{{ old('supplier_invoice_id', $selected_invoice_id ?? '') }}";
                if (preSelectedInvoice) {
                    invoiceSelect.value = preSelectedInvoice;
                    invoiceSelect.dispatchEvent(new Event('change'));
                }
            }
        });
    </script>
</x-app-layout>
