@extends('layouts.app')

@section('title', \App\Helpers\TranslationHelper::transFromDatabase('Edit Supplier Invoice', __('Edit Supplier Invoice')))

@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('Edit Supplier Invoice', __('Edit Supplier Invoice')) }} - {{ $invoice->invoice_number }}</h3>
                    <div class="card-tools">
                        <a href="{{ route('supplier-invoices.index') }}" class="btn btn-sm btn-secondary">
                            <i class="fas fa-arrow-right"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Back to List', __('Back to List')) }}
                        </a>
                    </div>
                </div>
                <div class="card-body">
                    <form id="invoiceForm" action="{{ route('supplier-invoices.update', $invoice) }}" method="POST" enctype="multipart/form-data">
                        @csrf
                        @method('PUT')

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="supplier_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Supplier', __('Supplier')) }} <span class="text-danger">*</span></label>
                                    <select name="supplier_id" id="supplier_id" class="form-control @error('supplier_id') is-invalid @enderror" required>
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Select Supplier', __('Select Supplier')) }} --</option>
                                        @foreach($suppliers as $supplier)
                                            <option value="{{ $supplier->id }}" {{ old('supplier_id', $invoice->supplier_id) == $supplier->id ? 'selected' : '' }}>
                                                {{ $supplier->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('supplier_id')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="warehouse_id">{{ \App\Helpers\TranslationHelper::transFromDatabase('Warehouse', __('Warehouse')) }} <span class="text-danger">*</span></label>
                                    <select name="warehouse_id" id="warehouse_id" class="form-control @error('warehouse_id') is-invalid @enderror" required>
                                        <option value="">-- {{ \App\Helpers\TranslationHelper::transFromDatabase('Select Warehouse', __('Select Warehouse')) }} --</option>
                                        @foreach($warehouses as $warehouse)
                                            <option value="{{ $warehouse->id }}" {{ old('warehouse_id', $invoice->warehouse_id) == $warehouse->id ? 'selected' : '' }}>
                                                {{ $warehouse->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                    @error('warehouse_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="{{ $invoice->invoice_number }}" readonly>
                                    <small class="form-text text-muted">{{ \App\Helpers\TranslationHelper::transFromDatabase('Auto-generated number', __('Auto-generated number')) }}</small>
                                    @error('invoice_number')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-3">
                                <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', $invoice->reference_number) }}" placeholder="{{ \App\Helpers\TranslationHelper::transFromDatabase('Manual invoice/reference number', __('Manual invoice/reference number')) }}">
                                    @error('reference_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', $invoice->invoice_date->format('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')) }} <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', $invoice->due_date->format('Y-m-d')) }}" required>
                                    @error('due_date')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-3">
                                <div class="form-group">
                                    <label for="status">{{ \App\Helpers\TranslationHelper::transFromDatabase('Status', __('Status')) }} <span class="text-danger">*</span></label>
                                    <select name="status" id="status" class="form-control @error('status') is-invalid @enderror" required>
                                        <option value="draft" {{ old('status', $invoice->status) == 'draft' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Draft', __('Draft')) }}</option>
                                        <option value="approved" {{ old('status', $invoice->status) == 'approved' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Approved', __('Approved')) }}</option>
                                        <option value="partially_paid" {{ old('status', $invoice->status) == 'partially_paid' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Partially Paid', __('Partially Paid')) }}</option>
                                        <option value="paid" {{ old('status', $invoice->status) == 'paid' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Paid', __('Paid')) }}</option>
                                        <option value="overdue" {{ old('status', $invoice->status) == 'overdue' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Overdue', __('Overdue')) }}</option>
                                        <option value="cancelled" {{ old('status', $invoice->status) == 'cancelled' ? 'selected' : '' }}>{{ \App\Helpers\TranslationHelper::transFromDatabase('Cancelled', __('Cancelled')) }}</option>
                                    </select>
                                    @error('status')
                                        <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('Unit', __('Unit')) }}</th>
                                            <th style="width: 130px;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Description', __('Description')) }}</th>
                                            <th style="width: 130px;">{{ \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('Total', __('Total')) }}</th>
                                            <th style="width: 100px; text-align: center;">{{ \App\Helpers\TranslationHelper::transFromDatabase('Action', __('Action')) }}</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', __('Total')) }}:</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', $invoice->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">
                                    @if($invoice->attachment)
                                        <small class="form-text text-muted mt-2">{{ \App\Helpers\TranslationHelper::transFromDatabase('Current Attachment', __('Current Attachment')) }}:
                                            <a href="{{ Storage::url($invoice->attachment) }}" target="_blank" class="text-primary">{{ basename($invoice->attachment) }}</a>
                                        </small>
                                    @endif
                                    @error('attachment')
                                        <span class="invalid-feedback">{{ $message }}</span>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <input type="hidden" id="subtotalInput" name="subtotal">
                        <input type="hidden" id="taxAmountInput" name="tax_amount">
                        <input type="hidden" id="totalAmountInput" name="total_amount">

                        <div class="row mt-4">
                            <div class="col-md-12">
                                <button type="submit" id="submitBtn" class="btn btn-success" title="{{ \App\Helpers\TranslationHelper::transFromDatabase('Update Invoice', __('Update Invoice')) }}" data-toggle="tooltip" data-placement="top">
                                    <i class="fas fa-save"></i> {{ \App\Helpers\TranslationHelper::transFromDatabase('Update', __('Update')) }}
                                </button>
                                <a href="{{ route('supplier-invoices.index') }}" class="btn btn-secondary" title="{{ \App\Helpers\TranslationHelper::transFromDatabase('Cancel', __('Cancel')) }}" data-toggle="tooltip" data-placement="top">
                                    <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;
const itemsData = @json($items);
const existingItems = @json($invoice->items);

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

function createItemRow(index, data = null) {
    const row = document.createElement('tr');      
    
    let itemsOptions = '<option value="">-- {{ __('Select Item') }} --</option>';
    itemsData.forEach(item => {
        const selected = data && data.item_id == item.id ? 'selected' : '';
        itemsOptions += `<option value="${item.id}" ${selected}>${item.name}</option>`;
    });
    
    row.innerHTML = `
        <td>
            <select name="items[${index}][item_id]" class="form-control form-control-sm item-select" data-index="${index}">
                ${itemsOptions}
            </select>
        </td>
        <td>
            <select name="items[${index}][item_unit_id]" class="form-control form-control-sm item-unit-select" data-index="${index}" ${!data || !data.item_id ? 'disabled' : ''}>
                <option value="">-- {{ __('Select Unit') }} --</option>
            </select>
        </td>
        <td>
            <textarea name="items[${index}][description]" class="form-control form-control-sm item-description" placeholder="{{ __('Description') }}" rows="2" style="resize:vertical; min-height:38px;">${data && data.description ? data.description : ''}</textarea>
        </td>
        <td>
            <input type="number" name="items[${index}][quantity]" class="form-control form-control-sm item-qty" step="0.01" min="0.01" placeholder="0.00" required value="${data ? data.quantity : ''}" style="width:100%">
        </td>
        <td>
            <input type="number" name="items[${index}][unit_price]" class="form-control form-control-sm item-price" step="0.01" min="0" placeholder="0.00" required value="${data ? data.unit_price : ''}">
        </td>
        <td>
            <input type="number" name="items[${index}][discount_amount]" class="form-control form-control-sm item-discount" step="0.01" min="0" max="100" placeholder="0" value="${data ? data.discount_percentage : '0'}">
            <input type="hidden" name="items[${index}][discount_type]" value="percentage">
        </td>
        <td>
            <input type="number" name="items[${index}][tax_rate]" class="form-control form-control-sm item-tax" step="0.01" min="0" max="100" placeholder="0" value="${data ? data.tax_rate : '0'}">
        </td>
        <td>
            <span class="item-total">${data ? (data.line_total || '0.00') : '0.00'}</span>
        </td>
        <td>
            <button type="button" class="btn btn-sm btn-danger remove-item" title="{{ __('Delete') }}" style="padding: 5px 10px; white-space: nowrap;">
                <i class="fas fa-trash"></i>
            </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 row = this.closest('tr');
            
            if (itemId) {
                const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
                const unitSelect = row.querySelector('.item-unit-select');
                
                fetch(`{{ route('inventory.items.units.api', ':itemId') }}`.replace(':itemId', itemId), {
                    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.innerHTML = '<option value="">-- {{ __('Select Unit') }} --</option>';
                        data.data.forEach(unit => {
                            const option = document.createElement('option');
                            option.value = unit.item_unit_id;
                            option.textContent = unit.unit_name;
                            if (unit.is_default) option.selected = true;
                            unitSelect.appendChild(option);
                        });
                        
                        const defaultUnit = data.data.find(u => u.is_default);
                        if (defaultUnit) {
                            updatePrice(defaultUnit.item_unit_id, row);
                        }
                    } else {
                        unitSelect.innerHTML = '<option value="">-- {{ __('No Units Available') }} --</option>';
                    }
                    unitSelect.disabled = false;
                })
                .catch(error => {
                    console.error('{{ __('Error fetching units') }}:', error);
                    unitSelect.innerHTML = '<option value="">-- {{ __('Select Unit') }} --</option>';
                    unitSelect.disabled = false;
                });
            } else {
                const unitSelect = row.querySelector('.item-unit-select');
                unitSelect.innerHTML = '<option value="">-- {{ __('Select Unit') }} --</option>';
                unitSelect.disabled = true;
            }
        });
    });
    
    document.querySelectorAll('.item-unit-select').forEach(select => {
        select.addEventListener('change', function() {
            const row = this.closest('tr');
            const itemUnitId = this.value;
            
            if (itemUnitId) {
                updatePrice(itemUnitId, row);
            } else {
                row.querySelector('.item-price').value = '0';
            }
            calculateTotals();
        });
    });

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

    document.querySelectorAll('.remove-item').forEach(btn => {
        btn.addEventListener('click', function() {
            this.closest('tr').remove();
            calculateTotals();
        });
    });
}

function updatePrice(itemUnitId, row) {
    const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
    fetch(`{{ route('inventory.items.unit.price.api', ':id') }}`.replace(':id', itemUnitId), {
        headers: {
            'X-CSRF-TOKEN': token,
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            row.querySelector('.item-price').value = parseFloat(data.price || data.purchase_price || 0).toFixed(2);
            calculateTotals();
        }
    })
    .catch(error => console.error('{{ __('Error') }}:', error));
}

function calculateTotals() {
    let subtotal = 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 discountPct = parseFloat(row.querySelector('.item-discount').value) || 0;
        const taxPct = parseFloat(row.querySelector('.item-tax').value) || 0;

        const lineSubtotal = qty * price;
        const discountAmount = (lineSubtotal * discountPct) / 100;
        const taxableAmount = lineSubtotal - discountAmount;
        const taxAmount = (taxableAmount * taxPct) / 100;
        const lineTotal = taxableAmount + taxAmount;

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

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

    const total = subtotal - totalDiscount + totalTax;

    document.getElementById('subtotalDisplay').textContent = subtotal.toFixed(2);
    document.getElementById('totalDiscountDisplay').textContent = totalDiscount.toFixed(2);
    document.getElementById('totalTaxDisplay').textContent = totalTax.toFixed(2);
    document.getElementById('totalDisplay').textContent = total.toFixed(2);

    document.getElementById('subtotalInput').value = subtotal.toFixed(2);
    document.getElementById('taxAmountInput').value = totalTax.toFixed(2);
    document.getElementById('totalAmountInput').value = total.toFixed(2);
}

document.getElementById('invoiceForm').addEventListener('submit', function(e) {
    const items = document.querySelectorAll('#itemsBody tr').length;
    if (items === 0) {
        e.preventDefault();
        alert('{{ __('Please add at least one item') }}');
        return false;
    }
});

document.addEventListener('DOMContentLoaded', function() {
    if (existingItems && existingItems.length > 0) {
        const tbody = document.getElementById('itemsBody');
        const fetchPromises = [];
        
        existingItems.forEach((item, index) => {
            itemCount = index + 1;
            const row = createItemRow(index, item);
            tbody.appendChild(row);
            
            const itemSelect = row.querySelector('.item-select');
            const unitSelect = row.querySelector('.item-unit-select');
            
            if (item.item_id) {
                itemSelect.value = item.item_id;
                
                const token = document.querySelector('meta[name="csrf-token"]')?.getAttribute('content');
                
                const fetchPromise = fetch(`{{ route('inventory.items.units.api', ':itemId') }}`.replace(':itemId', item.item_id), {
                    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.innerHTML = '<option value="">-- {{ __('Select Unit') }} --</option>';
                        data.data.forEach(unit => {
                            const option = document.createElement('option');
                            option.value = unit.item_unit_id;
                            option.textContent = unit.unit_name;
                            option.selected = (item.item_unit_id == unit.item_unit_id);
                            unitSelect.appendChild(option);
                        });
                        unitSelect.disabled = false;
                    } else {
                        unitSelect.innerHTML = '<option value="">-- {{ __('No Units Available') }} --</option>';
                    }
                })
                .catch(error => {
                    console.error('Error fetching units:', error);
                    unitSelect.innerHTML = '<option value="">-- {{ __('Select Unit') }} --</option>';
                });
                
                fetchPromises.push(fetchPromise);
            }
        });
        
        Promise.all(fetchPromises).then(() => {
            attachItemEventListeners();
            calculateTotals();
        });
    }
});

$(function() {
    $('[data-toggle="tooltip"]').tooltip();
});
</script>
@endsection
