@extends('layouts.modern')

@section('content')
<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h4>إنشاء فاتورة جديدة</h4>
                </div>
                <div class="card-body">
                    @include('layouts.alerts')

                    <form method="POST" action="{{ route('invoices.store') }}">
                        @csrf

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="customer_id">العميل <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="">-- اختر العميل --</option>
                                        @foreach($customers as $customer)
                                            <option value="{{ $customer->id }}" {{ old('customer_id') == $customer->id ? 'selected' : '' }}>
                                                {{ $customer->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('customer_id')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="maintenance_contract_id">عقد الصيانة</label>
                                    <select name="maintenance_contract_id" id="maintenance_contract_id" class="form-control @error('maintenance_contract_id') is-invalid @enderror">
                                        <option value="">-- اختر العقد --</option>
                                        @foreach($contracts as $contract)
                                            <option value="{{ $contract->id }}" {{ old('maintenance_contract_id') == $contract->id ? 'selected' : '' }}>
                                                {{ $contract->contract_number }} - {{ $contract->customer->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('maintenance_contract_id')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="invoice_date">تاريخ الفاتورة <span class="text-danger">*</span></label>
                                    <input type="date" name="invoice_date" id="invoice_date" class="form-control @error('invoice_date') is-invalid @enderror" value="{{ old('invoice_date', date('Y-m-d')) }}" required>
                                    @error('invoice_date')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="due_date">تاريخ الاستحقاق <span class="text-danger">*</span></label>
                                    <input type="date" name="due_date" id="due_date" class="form-control @error('due_date') is-invalid @enderror" value="{{ old('due_date', date('Y-m-d', strtotime('+30 days'))) }}" required>
                                    @error('due_date')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="template_id">قالب الفاتورة</label>
                                    <select name="template_id" id="template_id" class="form-control @error('template_id') is-invalid @enderror">
                                        <option value="">-- اختر القالب --</option>
                                        @foreach($templates as $template)
                                            <option value="{{ $template->id }}" {{ old('template_id') == $template->id ? 'selected' : '' }}>
                                                {{ $template->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('template_id')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="language">لغة الفاتورة <span class="text-danger">*</span></label>
                                    <select name="language" id="language" class="form-control @error('language') is-invalid @enderror" required>
                                        <option value="ar" {{ old('language', 'ar') == 'ar' ? 'selected' : '' }}>العربية</option>
                                        <option value="en" {{ old('language') == 'en' ? 'selected' : '' }}>الإنجليزية</option>
                                    </select>
                                    @error('language')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <h5 class="mt-4 mb-3">بنود الفاتورة</h5>
                        <div class="table-responsive">
                            <table class="table table-bordered" id="items-table">
                                <thead>
                                    <tr>
                                        <th>الوصف <span class="text-danger">*</span></th>
                                        <th>الكمية <span class="text-danger">*</span></th>
                                        <th>سعر الوحدة <span class="text-danger">*</span></th>
                                        <th>نسبة الخصم (%)</th>
                                        <th>المجموع</th>
                                        <th>الإجراءات</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr>
                                        <td>
                                            <input type="text" name="items[0][description]" class="form-control" required>
                                        </td>
                                        <td>
                                            <input type="number" name="items[0][quantity]" class="form-control item-quantity" min="0.01" step="0.01" value="1" required>
                                        </td>
                                        <td>
                                            <input type="number" name="items[0][unit_price]" class="form-control item-price" min="0" step="0.01" value="0" required>
                                        </td>
                                        <td>
                                            <input type="number" name="items[0][discount_percentage]" class="form-control item-discount" min="0" max="100" step="0.01" value="0">
                                        </td>
                                        <td>
                                            <span class="item-total">0.00</span>
                                        </td>
                                        <td>
                                            <button type="button" class="btn btn-danger btn-sm remove-item">حذف</button>
                                        </td>
                                    </tr>
                                </tbody>
                                <tfoot>
                                    <tr>
                                        <td colspan="6">
                                            <button type="button" class="btn btn-success btn-sm" id="add-item">إضافة بند</button>
                                        </td>
                                    </tr>
                                </tfoot>
                            </table>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="tax_rate">نسبة الضريبة (%) <span class="text-danger">*</span></label>
                                    <input type="number" name="tax_rate" id="tax_rate" class="form-control @error('tax_rate') is-invalid @enderror" min="0" max="100" step="0.01" value="{{ old('tax_rate', 15) }}" required>
                                    @error('tax_rate')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card">
                                    <div class="card-body">
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>المجموع الفرعي:</span>
                                            <span id="subtotal">0.00</span>
                                        </div>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>الخصم:</span>
                                            <span id="total-discount">0.00</span>
                                        </div>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>الضريبة:</span>
                                            <span id="tax-amount">0.00</span>
                                        </div>
                                        <div class="d-flex justify-content-between font-weight-bold">
                                            <span>الإجمالي:</span>
                                            <span id="total-amount">0.00</span>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row mb-3">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="notes">ملاحظات</label>
                                    <textarea name="notes" id="notes" class="form-control @error('notes') is-invalid @enderror" rows="3">{{ old('notes') }}</textarea>
                                    @error('notes')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="terms_conditions">الشروط والأحكام</label>
                                    <textarea name="terms_conditions" id="terms_conditions" class="form-control @error('terms_conditions') is-invalid @enderror" rows="3">{{ old('terms_conditions') }}</textarea>
                                    @error('terms_conditions')
                                        <span class="invalid-feedback" role="alert">
                                            <strong>{{ $message }}</strong>
                                        </span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="form-group text-center">
                            <button type="submit" class="btn btn-primary">إنشاء الفاتورة</button>
                            <a href="{{ route('invoices.index') }}" class="btn btn-secondary">إلغاء</a>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

@push('scripts')
<script>
    $(document).ready(function() {
        // إضافة بند جديد
        $('#add-item').click(function() {
            var rowCount = $('#items-table tbody tr').length;
            var newRow = `
                <tr>
                    <td>
                        <input type="text" name="items[${rowCount}][description]" class="form-control" required>
                    </td>
                    <td>
                        <input type="number" name="items[${rowCount}][quantity]" class="form-control item-quantity" min="0.01" step="0.01" value="1" required>
                    </td>
                    <td>
                        <input type="number" name="items[${rowCount}][unit_price]" class="form-control item-price" min="0" step="0.01" value="0" required>
                    </td>
                    <td>
                        <input type="number" name="items[${rowCount}][discount_percentage]" class="form-control item-discount" min="0" max="100" step="0.01" value="0">
                    </td>
                    <td>
                        <span class="item-total">0.00</span>
                    </td>
                    <td>
                        <button type="button" class="btn btn-danger btn-sm remove-item">حذف</button>
                    </td>
                </tr>
            `;
            $('#items-table tbody').append(newRow);
            calculateTotals();
        });

        // حذف بند
        $(document).on('click', '.remove-item', function() {
            if ($('#items-table tbody tr').length > 1) {
                $(this).closest('tr').remove();
                calculateTotals();
            } else {
                alert('يجب أن تحتوي الفاتورة على بند واحد على الأقل');
            }
        });

        // حساب المجموع عند تغيير الكمية أو السعر أو الخصم
        $(document).on('input', '.item-quantity, .item-price, .item-discount, #tax_rate', function() {
            calculateTotals();
        });

        // حساب المجاميع
        function calculateTotals() {
            var subtotal = 0;
            var totalDiscount = 0;

            $('#items-table tbody tr').each(function() {
                var quantity = parseFloat($(this).find('.item-quantity').val()) || 0;
                var price = parseFloat($(this).find('.item-price').val()) || 0;
                var discount = parseFloat($(this).find('.item-discount').val()) || 0;

                var rowSubtotal = quantity * price;
                var rowDiscount = rowSubtotal * (discount / 100);
                var rowTotal = rowSubtotal - rowDiscount;

                $(this).find('.item-total').text(rowTotal.toFixed(2));

                subtotal += rowSubtotal;
                totalDiscount += rowDiscount;
            });

            var taxRate = parseFloat($('#tax_rate').val()) || 0;
            var taxableAmount = subtotal - totalDiscount;
            var taxAmount = taxableAmount * (taxRate / 100);
            var totalAmount = taxableAmount + taxAmount;

            $('#subtotal').text(subtotal.toFixed(2));
            $('#total-discount').text(totalDiscount.toFixed(2));
            $('#tax-amount').text(taxAmount.toFixed(2));
            $('#total-amount').text(totalAmount.toFixed(2));
        }

        // تحديث العقود عند تغيير العميل
        $('#customer_id').change(function() {
            var customerId = $(this).val();
            if (customerId) {
                $.ajax({
                    url: '/api/customers/' + customerId + '/contracts',
                    type: 'GET',
                    dataType: 'json',
                    success: function(data) {
                        var options = '<option value="">-- اختر العقد --</option>';
                        $.each(data, function(key, contract) {
                            options += '<option value="' + contract.id + '">' + contract.contract_number + '</option>';
                        });
                        $('#maintenance_contract_id').html(options);
                    }
                });
            } else {
                $('#maintenance_contract_id').html('<option value="">-- اختر العقد --</option>');
            }
        });

        // تحديث المجاميع عند تحميل الصفحة
        calculateTotals();
    });
</script>
@endpush
@endsection