@extends('layouts.app')

@section('title', \App\Helpers\TranslationHelper::transFromDatabase('Add New Payment', __('Add New Payment')))

@push('styles')
<!-- Select2 CSS -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2-bootstrap-5-theme/1.3.0/select2-bootstrap-5.min.css" rel="stylesheet" />
@endpush

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">{{ \App\Helpers\TranslationHelper::transFromDatabase('Add New Payment', __('Add New Payment')) }}</h3>
                    <div class="card-tools">
                        <a href="{{ route('customer-payments.index') }}" class="btn btn-sm btn-secondary">
                            <i class="fas fa-arrow-right"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Return to Payments', __('Return to Payments')) }}
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form action="{{ route('customer-payments.store') }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customer_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Customer Name', __('Customer Name')) }} <span class="text-danger">*</span></label>
                                    <select name="customer_id" id="customer_id" class="form-control @error('customer_id') is-invalid @enderror" required>
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Customer', __('Choose Customer')) }} --</option>
                                        @foreach($customers as $customer)
                                            <option value="{{ $customer->id }}" {{ old('customer_id', request('customer_id')) == $customer->id ? 'selected' : '' }}>
                                                {{ $customer->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('customer_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customer_invoice_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Number', __('Invoice Number')) }} <span class="text-danger">*</span></label>
                                    <select name="customer_invoice_id" id="customer_invoice_id" class="form-control select2 @error('customer_invoice_id') is-invalid @enderror" required>
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Invoice', __('Choose Invoice')) }} --</option>
                                        @if(isset($invoices))
                                            @foreach($invoices as $invoice)
                                                <option value="{{ $invoice->id }}" {{ old('customer_invoice_id', request('invoice_id')) == $invoice->id ? 'selected' : '' }}
                                                    data-customer="{{ $invoice->customer_id }}"
                                                    data-remaining="{{ $invoice->remaining_amount }}">
                                                    {{ $invoice->invoice_number }} - {{ number_format($invoice->remaining_amount, 2) }} ({{ \App\Helpers\TranslationHelper::transFromDatabase('Remaining', __('Remaining')) }})
                                                </option>
                                            @endforeach
                                        @endif
                                    </select>
                                    @error('customer_invoice_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="payment_number">{{ \App\Helpers\TranslationHelper::transFromDatabase('Payment Number', __('Payment Number')) }} <span class="text-danger">*</span></label>
                                    <input type="text" name="payment_number" id="payment_number" class="form-control @error('payment_number') is-invalid @enderror" value="{{ old('payment_number') }}" required>
                                    @error('payment_number')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="payment_date">{{ \App\Helpers\TranslationHelper::transFromDatabase('Payment Date', __('Payment Date')) }} <span class="text-danger">*</span></label>
                                    <input type="date" name="payment_date" id="payment_date" class="form-control @error('payment_date') is-invalid @enderror" value="{{ old('payment_date', date('Y-m-d')) }}" required>
                                    @error('payment_date')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="amount">{{ \App\Helpers\TranslationHelper::transFromDatabase('Payment Amount', __('Payment Amount')) }} <span class="text-danger">*</span></label>
                                    <input type="number" step="0.01" name="amount" id="amount" class="form-control @error('amount') is-invalid @enderror" value="{{ old('amount') }}" required>
                                    @error('amount')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="payment_method">{{ \App\Helpers\TranslationHelper::transFromDatabase('Payment Method', __('Payment Method')) }} <span class="text-danger">*</span></label>
                                    <select name="payment_method" id="payment_method" class="form-control select2 @error('payment_method') is-invalid @enderror" required>
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Method', __('Choose Method')) }} --</option>
                                        <option value="cash" {{ old('payment_method') == 'cash' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Cash', __('Cash')) }}</option>
                                        <option value="bank_transfer" {{ old('payment_method') == 'bank_transfer' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Bank Transfer', __('Bank Transfer')) }}</option>
                                        <option value="check" {{ old('payment_method') == 'check' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Check', __('Check')) }}</option>
                                        <option value="credit_card" {{ old('payment_method') == 'credit_card' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Credit Card', __('Credit Card')) }}</option>
                                        <option value="other" {{ old('payment_method') == 'other' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Other', __('Other')) }}</option>
                                    </select>
                                    @error('payment_method')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="reference_number">{{ \App\Helpers\TranslationHelper::transFromDatabase('Reference Number', __('Reference Number')) }}</label>
                                    <input type="text" name="reference_number" id="reference_number" class="form-control @error('reference_number') is-invalid @enderror" value="{{ old('reference_number') }}">
                                    @error('reference_number')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6" id="treasury_container" style="{{ old('payment_method') == 'cash' || $errors->has('treasury_id') ? '' : 'display: none;' }}">
                                <div class="form-group">
                                    <label for="treasury_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Treasury', __('Treasury')) }} <span class="text-danger">*</span></label>
                                    <select name="treasury_id" id="treasury_id" class="form-control select2 @error('treasury_id') is-invalid @enderror">
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Treasury', __('Choose Treasury')) }} --</option>
                                        @foreach($treasuries as $treasury)
                                        <option value="{{ $treasury->id }}" {{ old('treasury_id') == $treasury->id ? 'selected' : '' }}>
                                            {{ $treasury->name }}
                                        </option>
                                        @endforeach
                                    </select>
                                    @error('treasury_id')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6" id="bank_container" style="{{ in_array(old('payment_method'), ['bank_transfer', 'check', 'credit_card']) || $errors->has('bank_account_id') ? '' : 'display: none;' }}">
                                <div class="form-group">
                                    <label for="bank_account_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Bank Account', __('Bank Account')) }} <span class="text-danger">*</span></label>
                                    <select name="bank_account_id" id="bank_account_id" class="form-control select2 @error('bank_account_id') is-invalid @enderror">
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Bank Account', __('Choose Bank Account')) }} --</option>
                                        @foreach($bankAccounts as $bankAccount)
                                        <option value="{{ $bankAccount->id }}" {{ old('bank_account_id') == $bankAccount->id ? 'selected' : '' }}>
                                            {{ $bankAccount->bank->name ?? '' }} - {{ $bankAccount->account_number }}
                                        </option>
                                        @endforeach
                                    </select>
                                    @error('bank_account_id')
                                    <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="attachment">{{ \App\Helpers\TranslationHelper::transFromDatabase('Attachment', __('Attachment')) }}</label>
                                    <input type="file" name="attachment" id="attachment" class="form-control-file @error('attachment') is-invalid @enderror">
                                    @error('attachment')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group">
                            <label for="notes">{{ \App\Helpers\TranslationHelper::transFromDatabase('Notes', __('Notes')) }}</label>
                            <textarea name="notes" id="notes" rows="3" class="form-control @error('notes') is-invalid @enderror">{{ old('notes') }}</textarea>
                            @error('notes')
                                <span class="invalid-feedback">{{ $message }}</span>
                            @enderror
                        </div>
                        
                        <div class="form-group">
                            <button type="submit" class="btn btn-primary">
                                <i class="fas fa-save"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Save', __('Save')) }}
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<!-- jQuery (required for Select2) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Select2 JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>

<script>
    $(document).ready(function() {
        // تهيئة Select2
        $('.select2').select2({
            dir: "rtl",
            language: "ar",
            width: '100%',
            theme: 'bootstrap-5'
        });

        // عند تغيير العميل
        $('#customer_id').on('change', function() {
            const customerId = $(this).val();
            const invoiceSelect = $('#customer_invoice_id');
            
            if (customerId) {
                $.ajax({
                    url: `{{ url('/api/customers') }}/${customerId}/invoices`,
                    type: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        let options = '<option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Invoice', __('Choose Invoice')) }} --</option>';
                        
                        $.each(data, function(key, invoice) {
                            options += `<option value="${invoice.id}" data-remaining="${invoice.remaining_amount}">${invoice.invoice_number} - ${invoice.remaining_amount.toFixed(2)} ({{ \App\Helpers\TranslationHelper::transFromDatabase('Remaining', __('Remaining')) }})</option>`;
                        });
                        
                        invoiceSelect.html(options).trigger('change');
                    }
                });
            } else {
                invoiceSelect.html('<option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Invoice', __('Choose Invoice')) }} --</option>').trigger('change');
            }
        });
        
        // عند تغيير الفاتورة
        $('#customer_invoice_id').on('change', function() {
            const selectedOption = $(this).find('option:selected');
            if (selectedOption.val() !== '') {
                const remainingAmount = parseFloat(selectedOption.data('remaining'));
                if (!isNaN(remainingAmount)) {
                    $('#amount').val(remainingAmount.toFixed(2));
                }
            }
        });

        // وظيفة تبديل عرض الخزينة والبنك
        function toggleFinancialSources() {
            var method = $('#payment_method').val();
            console.log('Current payment method:', method);
            
            if (method === 'cash') {
                $('#treasury_container').show();
                $('#bank_container').hide();
                $('#treasury_id').prop('required', true);
                $('#bank_account_id').prop('required', false);
            } else if (['bank_transfer', 'check', 'credit_card'].includes(method)) {
                $('#treasury_container').hide();
                $('#bank_container').show();
                $('#treasury_id').prop('required', false);
                $('#bank_account_id').prop('required', true);
            } else {
                $('#treasury_container').hide();
                $('#bank_container').hide();
                $('#treasury_id').prop('required', false);
                $('#bank_account_id').prop('required', false);
            }
        }

        // عند تغيير طريقة الدفع
        $('#payment_method').on('change', function() {
            toggleFinancialSources();
        });

        // تنفيذ التبديل عند التحميل (في حال وجود قيم سابقة)
        toggleFinancialSources();
    });
</script>
@endpush
@endsection
