@extends('layouts.app')
@section('title', \App\Helpers\TranslationHelper::transFromDatabase('Add New Invoice', __('Add New Invoice')))

@php
    $company = \App\Models\Company::find(auth()->user()->company_id);
    $activeSubscription = \App\Models\Subscription::where('company_id', auth()->user()->company_id)
        ->where('status', 'active')
        ->where('subscription_end_date', '>=', now())
        ->first();
    
    $trialSubscription = \App\Models\Subscription::where('company_id', auth()->user()->company_id)
        ->where('status', 'trial')
        ->where('trial_end_date', '>=', now())
        ->first();
    
    $invoicesCount = \App\Models\CustomerInvoice::where('company_id', auth()->user()->company_id)->count();
    $hasActiveSubscription = $activeSubscription || $trialSubscription;
    $invoicesRemaining = max(0, 30 - $invoicesCount);
@endphp

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-md-12">
            @if(!$hasActiveSubscription && $invoicesRemaining <= 1)
                <div class="alert alert-warning alert-dismissible fade show" role="alert" style="margin-bottom: 20px;">
                    <h4 class="alert-heading" style="margin-bottom: 10px;">
                        <i class="fas fa-exclamation-triangle"></i> تنبيه مهم!
                    </h4>
                    <p style="margin-bottom: 0;">
                        ⚠️ <strong>لا يوجد اشتراك نشط حالياً</strong><br>
                        📋 عدد الفواتير المتبقية: <strong style="color: #d9534f;">{{ $invoicesRemaining }}</strong> من 30<br>
                        💡 بعد انتهاء الفواتير المسموح بها، لن تتمكن من إنشاء فواتير جديدة إلا بتفعيل الاشتراك.<br>
                        📞 يرجى التواصل مع مدير الحساب لتفعيل الاشتراك أو تجديد النسخة التجريبية.
                    </p>
                    <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
            @endif

            <div class="card">
                <div class="card-header">
                    <h3 class="card-title">{{ \App\Helpers\TranslationHelper::transFromDatabase('Add New Invoice', __('Add New Invoice')) }}</h3>
                    <div class="card-tools">
                        <a href="{{ route('customer-invoices.index') }}" class="btn btn-sm btn-secondary">
                            <i class="fas fa-arrow-right"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Return to Invoices', __('Return to Invoices')) }}
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form id="invoiceForm" action="{{ route('customer-invoices.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') == $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="contract_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Contract Title', __('Contract Title')) }}</label>
                                    <select name="customer_contract_id" id="contract_id" class="form-control @error('contract_id') is-invalid @enderror">
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Choose Contract', __('Choose Contract')) }} --</option>
                                        @foreach($contracts as $contract)
                                            <option value="{{ $contract->id }}" {{ old('contract_id') == $contract->id ? 'selected' : '' }}>
                                                {{ $contract->contract_number }} - {{ $contract->title }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('contract_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="invoice_number">{{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Number', __('Invoice Number')) }} <span class="text-danger">*</span></label>
                                    <input type="text" name="invoice_number" id="invoice_number" class="form-control bg-light @error('invoice_number') is-invalid @enderror" value="{{ $nextInvoiceNumber }}" readonly>
                                    <small class="form-text text-muted">{{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Number is Auto Generated', __('Invoice Number is Auto Generated')) }}</small>
                                    @error('invoice_number')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="invoice_date">{{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Date', __('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">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="due_date">{{ \App\Helpers\TranslationHelper::transFromDatabase('Due Date', __('Due Date')) }}</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'))) }}">
                                    @error('due_date')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="form-group mt-4">
                            <h5>{{ \App\Helpers\TranslationHelper::transFromDatabase('Invoice Items', __('Invoice Items')) }} <span class="text-danger">*</span></h5>
                            <div class="table-responsive">
                                <table class="table table-bordered table-sm" id="itemsTable">
                                    <thead class="bg-light">
                                        <tr>
                                            <th>{{ \App\Helpers\TranslationHelper::transFromDatabase('Item Name', __('Item Name')) }}</th>
                                            <th style="width: 100px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Item Unit', __('Item Unit')) }}</th>
                                            <th>{{ \App\Helpers\TranslationHelper::transFromDatabase('Description', __('Description')) }}</th>
                                            <th style="width: 80px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Quantity', __('Quantity')) }}</th>
                                            <th style="width: 100px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Unit Price', __('Unit Price')) }}</th>
                                            <th style="width: 80px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Discount %', __('Discount %')) }}</th>
                                            <th style="width: 80px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Tax %', __('Tax %')) }}</th>
                                            <th style="width: 100px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Line Total', __('Line Total')) }}</th>
                                            <th style="width: 100px; text-align: center;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Actions', __('Actions')) }}</th>
                                        </tr>
                                    </thead>
                                    <tbody id="itemsBody">
                                    </tbody>
                                </table>
                            </div>
                            <button type="button" class="btn btn-sm btn-primary" id="addItemBtn">
                                <i class="fas fa-plus"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Add Item', __('Add Item')) }}
                            </button>
                        </div>

                        <div class="row mt-4">
                            <div class="col-md-8"></div>
                            <div class="col-md-4">
                                <div class="card bg-light">
                                    <div class="card-body p-3">
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Subtotal', __('Subtotal')) }}:</span>
                                            <strong><span id="subtotalDisplay">0.00</span></strong>
                                        </div>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Total Discount', __('Total Discount')) }}:</span>
                                            <strong><span id="totalDiscountDisplay">0.00</span></strong>
                                        </div>
                                        <div class="d-flex justify-content-between mb-2">
                                            <span>{{ \App\Helpers\TranslationHelper::transFromDatabase('Total Tax', __('Total Tax')) }}:</span>
                                            <strong><span id="totalTaxDisplay">0.00</span></strong>
                                        </div>
                                        <hr>
                                        <div class="d-flex justify-content-between">
                                            <span class="font-weight-bold">{{ \App\Helpers\TranslationHelper::transFromDatabase('Total Amount', __('Total Amount')) }}:</span>
                                            <strong class="text-primary"><span id="totalDisplay">0.00</span></strong>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="notes">{{ \App\Helpers\TranslationHelper::transFromDatabase('Notes', __('Notes')) }}</label>
                                    <textarea name="notes" id="notes" class="form-control @error('notes') is-invalid @enderror" rows="4">{{ old('notes') }}</textarea>
                                    @error('notes')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <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="row mt-4">
                            <div class="col-md-12">
                                <button type="submit" id="submitBtn" class="btn btn-success">
                                    <i class="fas fa-save"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Save Invoice', __('Save Invoice')) }}
                                </button>
                                <a href="{{ route('customer-invoices.index') }}" class="btn btn-secondary">
                                    <i class="fas fa-times"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Cancel', __('Cancel')) }}
                                </a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<input type="hidden" id="itemsData" name="itemsData">

<script>
let itemCount = 0;

document.getElementById('addItemBtn').addEventListener('click', function() {
    const tbody = document.getElementById('itemsBody');
    const row = createItemRow(itemCount++);
    tbody.appendChild(row);
    attachItemEventListeners();
});

function createItemRow(inde) {
    const row = document.createElement('tr');
    const itemsOptions = document.getElementById('itemsData').value ? JSON.parse(document.getElementById('itemsData').value) : {!! json_encode($items->map(fn($item) => ['id' => $item->id, 'name' => $item->name])->toArray()) !!};

    let itemSelect = '<select name="items[' + inde + '][item_id]" class="form-control form-control-sm item-select" data-index="' + inde + '">';
    itemSelect += '<option value="">-- اختر الصنف --</option>';
    itemsOptions.forEach(item => {
        itemSelect += '<option value="' + item.id + '">' + item.name + '</option>';
    });
    itemSelect += '</select>';

    row.innerHTML = `
        <td>
            ${itemSelect}

        </td>
        <td>
            <select name="items[${inde}][item_unit_id]" class="form-control form-control-sm item-unit-select" data-index="${inde}">
                <option value="">-- اختر الوحدة --</option>
            </select>
        </td>
        <td>
            <input type="text" name="items[${inde}][description]" class="form-control form-control-sm item-description" placeholder="وصف البند">
        </td>
        <td>
            <input type="number" name="items[${inde}][quantity]" class="form-control form-control-sm item-qty" step="0.01" min="0.01" placeholder="0.00" required>
        </td>
        <td>
            <input type="number" name="items[${inde}][unit_price]" class="form-control form-control-sm item-price" step="0.01" min="0" placeholder="0.00" required>
        </td>
        <td>
            <input type="number" name="items[${inde}][discount_amount]" class="form-control form-control-sm item-discount" step="0.01" min="0" max="100" placeholder="0" value="0">
            <input type="hidden" name="items[${inde}][discount_type]" value="percentage">
        </td>
        <td>
            <input type="number" name="items[${inde}][tax_rate]" class="form-control form-control-sm item-tax" data-index="${inde}" step="0.01" min="0" max="100" placeholder="15" value="15">
        </td>
        <td>
            <span class="item-total">0.00</span>
        </td>
        <td class="text-center">
            <button type="button" class="btn btn-sm btn-danger remove-item" title="حذف هذا البند" data-toggle="tooltip" data-placement="top" style="padding: 8px 12px; white-space: nowrap; min-width: 100px;">
                <i class="fas fa-trash-alt mr-2"></i>
                <span>حذف</span>
            </button>
        </td>
    `;
    return row;
}

function attachItemEventListeners() {
    document.querySelectorAll('.item-select').forEach(select => {
        select.addEventListener('change', function() {
            const index = this.dataset.index;
            const itemId = this.value;

            const unitSelect = document.querySelector(`.item-unit-select[data-index="${index}"]`);
            unitSelect.innerHTML = '<option value="">-- اختر الوحدة --</option>';

            if (itemId) {
                // جلب الوحدات ونسبة الضريبة من الصنف
                fetch(`{{ route("inventory.items.units.api", ":itemId") }}`.replace(':itemId', itemId), { credentials: 'same-origin' })
                    .then(response => response.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(error => console.error('Error:', error));
                
                // جلب نسبة الضريبة من الصنف وتحديثها في الحقل
                fetch(`{{ route("inventory.items.data", ":itemId") }}`.replace(':itemId', itemId), { 
                    credentials: 'same-origin',
                    headers: {
                        'Accept': 'application/json'
                    }
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data && data.tax_rate) {
                            const taxInput = document.querySelector(`.item-tax[data-index="${index}"]`);
                            if (taxInput && !taxInput.value) {
                                taxInput.value = data.tax_rate;
                                taxInput.dispatchEvent(new Event('change'));
                            }
                        }
                    })
                    .catch(error => console.error('Error loading tax rate:', error));
            }
        });
    });

    document.querySelectorAll('.item-qty, .item-price, .item-discount, .item-tax').forEach(input => {
        input.addEventListener('change', updateTotals);
        input.addEventListener('keyup', updateTotals);
    });
}

function updateTotals() {
    let grandTotal = 0;
    let totalDiscount = 0;
    let totalTax = 0;

    document.querySelectorAll('#itemsBody tr').forEach(row => {
        const qty = parseFloat(row.querySelector('.item-qty').value) || 0;
        const price = parseFloat(row.querySelector('.item-price').value) || 0;
        const discount = parseFloat(row.querySelector('.item-discount').value) || 0;
        const tax = parseFloat(row.querySelector('.item-tax').value) || 0;

        const subtotal = qty * price;
        const discountAmount = (subtotal * discount) / 100;
        const afterDiscount = subtotal - discountAmount;
        const taxAmount = (afterDiscount * tax) / 100;
        const itemTotal = afterDiscount + taxAmount;

        row.querySelector('.item-total').textContent = itemTotal.toFixed(2);

        grandTotal += subtotal;
        totalDiscount += discountAmount;
        totalTax += taxAmount;
    });

    document.getElementById('subtotalDisplay').textContent = grandTotal.toFixed(2);
    document.getElementById('totalDiscountDisplay').textContent = totalDiscount.toFixed(2);
    document.getElementById('totalTaxDisplay').textContent = totalTax.toFixed(2);
    document.getElementById('totalDisplay').textContent = (grandTotal - totalDiscount + totalTax).toFixed(2);
}

attachItemEventListeners();

// ✅ استعادة البيانات القديمة عند حدوث خطأ تحقق
document.addEventListener('DOMContentLoaded', function() {
    const oldItems = {!! json_encode(old('items', [])) !!};
    
    if (Array.isArray(oldItems) && oldItems.length > 0) {
        const tbody = document.getElementById('itemsBody');
        
        oldItems.forEach((oldItem) => {
            const row = createItemRow(itemCount++);
            tbody.appendChild(row);
            
            setTimeout(() => {
                const itemSelect = row.querySelector('.item-select');
                const unitSelect = row.querySelector('.item-unit-select');
                const descriptionInput = row.querySelector('.item-description');
                const qtyInput = row.querySelector('.item-qty');
                const priceInput = row.querySelector('.item-price');
                const discountInput = row.querySelector('.item-discount');
                const taxInput = row.querySelector('.item-tax');
                
                if (oldItem.item_id) {
                    itemSelect.value = oldItem.item_id;
                    itemSelect.dispatchEvent(new Event('change'));
                    setTimeout(() => {
                        if (oldItem.item_unit_id) {
                            unitSelect.value = oldItem.item_unit_id;
                        }
                    }, 300);
                }
                
                if (oldItem.description) descriptionInput.value = oldItem.description;
                if (oldItem.quantity) qtyInput.value = oldItem.quantity;
                if (oldItem.unit_price) priceInput.value = oldItem.unit_price;
                if (oldItem.discount_amount) discountInput.value = oldItem.discount_amount;
                if (oldItem.tax_rate) taxInput.value = oldItem.tax_rate;
                
                updateTotals();
            }, 100);
        });
        
        attachItemEventListeners();
    }
});

// التعامل مع حذف الصفوف
document.addEventListener('click', function(e) {
    if (e.target.closest('.remove-item')) {
        const row = e.target.closest('tr');
        const itemCount = document.querySelectorAll('#itemsBody tr').length;
        
        if (itemCount <= 1) {
            alert('يجب أن تحتوي الفاتورة على بند واحد على الأقل!');
            return;
        }
        
        if (confirm('هل تريد بالفعل حذف هذا البند؟')) {
            row.remove();
            updateTotals();
        }
    }
});

// تفعيل Tooltips
if (typeof $ !== 'undefined') {
    $(document).ready(function() {
        $(function () {
            $('[data-toggle="tooltip"]').tooltip()
        })
    });
}
</script>

@endsection
