@extends('layouts.app')

@section('content')
    <div class="row mb-4">
        <div class="col-12">
            <h2 class="fw-light">{{ __('Edit Invoice #') }}{{ $invoice->code }}</h2>
            <nav aria-label="breadcrumb">
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('dashboard') }}">{{ __('Dashboard') }}</a></li>
                    <li class="breadcrumb-item"><a href="{{ route('accounting.invoices.index') }}">{{ __('Invoices') }}</a></li>
                    <li class="breadcrumb-item active" aria-current="page">{{ __('Edit') }}</li>
                </ol>
            </nav>
        </div>
    </div>

    @if($invoice->paid_amount > 0)
        <div class="alert alert-warning border-start border-4 border-warning">
            <i class="fas fa-exclamation-triangle me-2"></i>
            {{ __('This invoice has recorded payments. Some fields (like items and totals) are locked to maintain financial integrity.') }}
        </div>
    @endif

    <form action="{{ route('accounting.invoices.update', $invoice) }}" method="POST" id="invoiceForm">
        @csrf
        @method('PUT')
        <div class="row">
            <!-- Main Details -->
            <div class="col-12 col-lg-8">
                <div class="card mb-4">
                    <div class="card-header bg-dark border-secondary">
                        <h5 class="mb-0">{{ __('Invoice Items') }}</h5>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-bordered border-secondary mb-0" id="itemsTable">
                                <thead class="table-dark">
                                    <tr>
                                        <th style="width: 20%">{{ __('Product/Service') }}</th>
                                        <th style="width: 25%">{{ __('Description') }}</th>
                                        <th style="width: 10%">{{ __('Unit') }}</th>
                                        <th style="width: 15%">{{ __('Serial Key') }}</th>
                                        <th style="width: 8%">{{ __('Qty') }}</th>
                                        <th style="width: 12%">{{ __('Unit Price') }}</th>
                                        <th style="width: 10%">{{ __('Total') }}</th>
                                        <th style="width: 50px"></th>
                                    </tr>
                                </thead>
                                <tbody id="itemsBody">
                                    @foreach($invoice->items as $index => $item)
                                    <tr class="item-row">
                                        <td>
                                            <textarea name="items[{{ $index }}][description]" class="form-control mb-1" rows="2"
                                                {{ $invoice->paid_amount > 0 ? 'readonly' : '' }} required>{{ $item->description }}</textarea>
                                            
                                            <div class="row g-1 date-range {{ $item->unit && $item->unit->type == 'time' ? '' : 'd-none' }}">
                                                <div class="col-6">
                                                    <input type="date" name="items[{{ $index }}][start_date]" 
                                                        class="form-control form-control-sm" 
                                                        value="{{ $item->start_date ? $item->start_date->format('Y-m-d') : '' }}"
                                                        {{ $invoice->paid_amount > 0 ? 'readonly' : '' }}>
                                                </div>
                                                <div class="col-6">
                                                    <input type="date" name="items[{{ $index }}][end_date]" 
                                                        class="form-control form-control-sm" 
                                                        value="{{ $item->end_date ? $item->end_date->format('Y-m-d') : '' }}"
                                                        {{ $invoice->paid_amount > 0 ? 'readonly' : '' }}>
                                                </div>
                                            </div>
                                        </td>
                                        <td>
                                            <select name="items[{{ $index }}][unit_id]" 
                                                class="form-select unit-select" 
                                                onchange="checkUnitType(this)"
                                                {{ $invoice->paid_amount > 0 ? 'disabled' : '' }}>
                                                <option value="">{{ __('None') }}</option>
                                                @foreach($units as $u)
                                                    <option value="{{ $u->id }}" data-type="{{ $u->type }}" {{ $item->unit_id == $u->id ? 'selected' : '' }}>
                                                        {{ $u->name }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </td>
                                        <td>
                                            <input type="text" name="items[{{ $index }}][serial_key]" class="form-control"
                                                value="{{ $item->serial_key }}" {{ $invoice->paid_amount > 0 ? 'readonly' : '' }}>
                                        </td>
                                        <td>
                                            <input type="number" name="items[{{ $index }}][quantity]" class="form-control qty-input"
                                                value="{{ $item->quantity + 0 }}" step="0.01" min="0.01" {{ $invoice->paid_amount > 0 ? 'readonly' : '' }} required>
                                        </td>
                                        <td>
                                            <input type="number" name="items[{{ $index }}][unit_price]"
                                                class="form-control price-input" value="{{ $item->unit_price }}" step="0.01" min="0" {{ $invoice->paid_amount > 0 ? 'readonly' : '' }} required>
                                        </td>
                                        <td>
                                            <input type="text" class="form-control-plaintext text-end total-display"
                                                value="{{ number_format($item->total, 2) }}" readonly>
                                        </td>
                                        <td class="text-center">
                                            @if($invoice->paid_amount == 0)
                                            <button type="button" class="btn btn-outline-danger btn-sm remove-row">
                                                <i class="fas fa-times"></i>
                                            </button>
                                            @endif
                                        </td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                        @if($invoice->paid_amount == 0)
                        <div class="mt-3">
                            <button type="button" class="btn btn-outline-success btn-sm" id="addItemBtn">
                                <i class="fas fa-plus me-1"></i> {{ __('Add Line Item') }}
                            </button>
                        </div>
                        @endif
                    </div>
                </div>

                <div class="card mb-4">
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">{{ __('Notes / Terms') }}</label>
                            <textarea name="notes" class="form-control" rows="3">{{ $invoice->notes }}</textarea>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Sidebar Details -->
            <div class="col-12 col-lg-4">
                <div class="card mb-4">
                    <div class="card-header bg-dark border-secondary">
                        <h5 class="mb-0">{{ __('Invoice Details') }}</h5>
                    </div>
                    <div class="card-body">
                        <div class="mb-3">
                            <label class="form-label">{{ __('Client') }} <span class="text-danger">*</span></label>
                            <select name="customer_id" class="form-select" {{ $invoice->paid_amount > 0 ? 'disabled' : '' }} required>
                                @foreach($customers as $customer)
                                    <option value="{{ $customer->id }}" {{ $invoice->customer_id == $customer->id ? 'selected' : '' }}>
                                        {{ $customer->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">{{ __('Invoice Number') }}</label>
                            <input type="text" name="code" class="form-control" value="{{ $invoice->code }}" readonly>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">{{ __('Invoice Date') }} <span class="text-danger">*</span></label>
                            <input type="date" name="date" class="form-control" value="{{ $invoice->date->format('Y-m-d') }}" required>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">{{ __('Due Date') }}</label>
                            <input type="date" name="due_date" class="form-control" value="{{ $invoice->due_date ? $invoice->due_date->format('Y-m-d') : '' }}">
                        </div>

                        <hr class="border-secondary">

                        <div class="mb-3">
                            <label class="form-label">{{ __('Sales Person') }}</label>
                            <select name="sales_person_id" class="form-select">
                                <option value="">{{ __('None') }}</option>
                                @foreach($salesPeople as $sp)
                                    <option value="{{ $sp->id }}" {{ $invoice->sales_person_id == $sp->id ? 'selected' : '' }}>
                                        {{ $sp->name }}
                                    </option>
                                @endforeach
                            </select>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">{{ __('Commission Amount (EGP)') }}</label>
                            <input type="number" name="commission_amount" class="form-control" step="0.01" value="{{ $invoice->commission_amount }}">
                        </div>

                        <hr class="border-secondary">

                        <!-- Summary -->
                        <div class="d-flex justify-content-between mb-2">
                            <span>{{ __('Subtotal:') }}</span>
                            <span id="subtotalDisplay">{{ number_format($invoice->subtotal, 2) }}</span>
                        </div>
                        <div class="row g-2 mb-2 align-items-center">
                            <div class="col-6">{{ __('VAT (%):') }}</div>
                            <div class="col-6">
                                <input type="number" name="tax_percent" id="taxInput" class="form-control form-control-sm text-end" 
                                    value="{{ $invoice->tax_percent }}" {{ $invoice->paid_amount > 0 ? 'readonly' : '' }}>
                            </div>
                        </div>
                        <div class="d-flex justify-content-between mb-2">
                            <span>{{ __('Tax Amount:') }}</span>
                            <span id="taxDisplay">{{ number_format($invoice->tax_amount, 2) }}</span>
                        </div>
                        <hr class="border-secondary">
                        <div class="d-flex justify-content-between mb-2 align-items-center">
                            <span>{{ __('Discount:') }}</span>
                            <div class="input-group input-group-sm w-50">
                                <select name="discount_type" id="discountType" class="form-select" {{ $invoice->paid_amount > 0 ? 'disabled' : '' }}>
                                    <option value="fixed" {{ $invoice->discount_type == 'fixed' ? 'selected' : '' }}>{{ __('Fixed') }}</option>
                                    <option value="percent" {{ $invoice->discount_type == 'percent' ? 'selected' : '' }}>{{ __('%') }}</option>
                                </select>
                                <input type="number" name="discount_value" id="discountInput" class="form-control" 
                                    value="{{ $invoice->discount_value + 0 }}" min="0" step="0.01" {{ $invoice->paid_amount > 0 ? 'readonly' : '' }}>
                            </div>
                        </div>
                        <div class="d-flex justify-content-between mb-2 align-items-center">
                            <span>{{ __('Shipping:') }}</span>
                            <input type="number" name="shipping_amount" id="shippingInput" class="form-control form-control-sm w-50 text-end" 
                                value="{{ $invoice->shipping_amount + 0 }}" min="0" step="0.01" {{ $invoice->paid_amount > 0 ? 'readonly' : '' }}>
                        </div>
                        <div class="d-flex justify-content-between mb-2 align-items-center">
                            <span>{{ __('Extra Exp:') }}</span>
                            <div class="input-group input-group-sm w-50">
                                <input type="text" name="extra_expenses_note" class="form-control" placeholder="Note" 
                                    value="{{ $invoice->extra_expenses_note }}" {{ $invoice->paid_amount > 0 ? 'readonly' : '' }}>
                                <input type="number" name="extra_expenses_amount" id="extraExpensesInput" class="form-control text-end" 
                                    value="{{ $invoice->extra_expenses_amount + 0 }}" min="0" step="0.01" {{ $invoice->paid_amount > 0 ? 'readonly' : '' }}>
                            </div>
                        </div>
                        <hr class="border-secondary">
                        <div class="d-flex justify-content-between fs-5 fw-bold border-top border-secondary pt-2">
                            <span>{{ __('Total:') }}</span>
                            <span id="totalDisplay">{{ number_format($invoice->total, 2) }}</span>
                        </div>

                        <div class="mt-4">
                            <button type="submit" class="btn btn-primary w-100">{{ __('Update Invoice') }}</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </form>

    <!-- Product Selection Logic differs in Edit vs Create significantly because usually in edit we don't have the product list handy for adding NEW rows unless we inject it differently. But wait, we DO have $products passed to the view. -->
    
    <!-- Template for new row -->
    <template id="newRowTemplate">
        <tr class="item-row">
            <!-- Product Select -->
            <td>
                 <select class="form-select product-select" onchange="fillProductData(this)">
                    <option value="">{{ __('Select Product') }}</option>
                    @foreach($products as $product)
                        <option value="{{ $product->id }}" data-name="{{ $product->name }}"
                            data-price="{{ $product->price }}"
                            data-description="{{ $product->description }}"
                            data-unit-id="{{ $product->unit_id }}">
                            {{ $product->name }}
                        </option>
                    @endforeach
                </select>
            </td>
            <td>
                <textarea name="items[INDEX][description]" class="form-control description-input mb-1" placeholder="{{ __('Item description') }}" rows="2" required></textarea>
                <div class="row g-1 date-range d-none">
                    <div class="col-6"><input type="date" name="items[INDEX][start_date]" class="form-control form-control-sm" placeholder="{{ __('From') }}"></div>
                    <div class="col-6"><input type="date" name="items[INDEX][end_date]" class="form-control form-control-sm" placeholder="{{ __('To') }}"></div>
                </div>
            </td>
            <td>
                <select name="items[INDEX][unit_id]" class="form-select unit-select" onchange="checkUnitType(this)">
                    <option value="">{{ __('None') }}</option>
                    @foreach($units as $u)
                        <option value="{{ $u->id }}" data-type="{{ $u->type }}">{{ $u->name }}</option>
                    @endforeach
                </select>
            </td>
            <td><input type="text" name="items[INDEX][serial_key]" class="form-control"></td>
            <td><input type="number" name="items[INDEX][quantity]" class="form-control qty-input" value="1" step="0.01" min="0.01" required></td>
            <td><input type="number" name="items[INDEX][unit_price]" class="form-control price-input" value="0.00" step="0.01" min="0" required></td>
            <td><input type="text" class="form-control-plaintext text-end total-display" value="0.00" readonly></td>
            <td class="text-center">
                <button type="button" class="btn btn-outline-danger btn-sm remove-row"><i class="fas fa-times"></i></button>
            </td>
        </tr>
    </template>

    <datalist id="productsList">
        @foreach($products as $product)
            <option value="{{ $product->name }}" data-price="{{ $product->price }}">
        @endforeach
    </datalist>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const itemsBody = document.getElementById('itemsBody');
            const addItemBtn = document.getElementById('addItemBtn');
            const taxInput = document.getElementById('taxInput');

            // Expose function globally
            window.checkUnitType = function(selectElement) {
                const selectedOption = selectElement.options[selectElement.selectedIndex];
                const type = selectedOption.getAttribute('data-type');
                const row = selectElement.closest('.item-row');
                const dateRange = row.querySelector('.date-range');

                if (type === 'time') {
                    dateRange.classList.remove('d-none');
                } else {
                    dateRange.classList.add('d-none');
                    // Only clear if not readonly (paid) - although JS shouldn't touch values if we want to preserve them? 
                    // Better clear if user explicitly changes unit type to non-time.
                     if (!selectElement.hasAttribute('disabled')) {
                        row.querySelectorAll('.date-range input').forEach(input => input.value = '');
                     }
                }
            };
            
            window.fillProductData = function(selectElement) {
                const selectedOption = selectElement.options[selectElement.selectedIndex];
                const row = selectElement.closest('.item-row');
                
                if (selectedOption.value) {
                    const productName = selectedOption.getAttribute('data-name');
                    const productPrice = selectedOption.getAttribute('data-price');
                    const productDescription = selectedOption.getAttribute('data-description');
                    const productUnitId = selectedOption.getAttribute('data-unit-id');
                    
                    row.querySelector('.description-input').value = productDescription || productName;
                    row.querySelector('.price-input').value = parseFloat(productPrice).toFixed(2);
                    
                    const unitSelect = row.querySelector('.unit-select');
                    if (productUnitId) {
                        unitSelect.value = productUnitId;
                    } else {
                        unitSelect.selectedIndex = 0;
                    }
                    checkUnitType(unitSelect);
                    
                    calculateTotals();
                }
            };

            function calculateTotals() {
                let subtotal = 0;
                document.querySelectorAll('.item-row').forEach(row => {
                    const qty = parseFloat(row.querySelector('.qty-input').value) || 0;
                    const price = parseFloat(row.querySelector('.price-input').value) || 0;
                    const total = qty * price;
                    row.querySelector('.total-display').value = total.toFixed(2);
                    subtotal += total;
                });

                const taxPercent = parseFloat(taxInput.value) || 0;
                const taxAmount = (subtotal * taxPercent) / 100;

                // Discount
                const discountType = document.getElementById('discountType').value;
                let discountValue = parseFloat(document.getElementById('discountInput').value) || 0;
                let discountAmount = 0;

                if (discountType === 'percent') {
                    discountAmount = (subtotal * discountValue) / 100;
                } else {
                    discountAmount = discountValue;
                }

                // Expenses
                const shippingAmount = parseFloat(document.getElementById('shippingInput').value) || 0;
                const extraExpensesAmount = parseFloat(document.getElementById('extraExpensesInput').value) || 0;

                const total = subtotal + taxAmount - discountAmount + shippingAmount + extraExpensesAmount;

                document.getElementById('subtotalDisplay').textContent = subtotal.toLocaleString(undefined, {
                    minimumFractionDigits: 2
                });
                document.getElementById('taxDisplay').textContent = taxAmount.toLocaleString(undefined, {
                    minimumFractionDigits: 2
                });
                document.getElementById('totalDisplay').textContent = total.toLocaleString(undefined, {
                    minimumFractionDigits: 2
                });
            }

            // Calculation Triggers
            if (addItemBtn) {
                addItemBtn.addEventListener('click', function() {
                    const itemsBody = document.getElementById('itemsBody');
                    const template = document.getElementById('newRowTemplate');
                    const rowIndex = itemsBody.querySelectorAll('tr').length; // simple count
                    
                    // Basic clone setup since we used a template
                    const clone = template.content.cloneNode(true);
                    
                    // Update names
                    clone.querySelectorAll('[name*="INDEX"]').forEach(input => {
                        input.setAttribute('name', input.getAttribute('name').replace('INDEX', rowIndex));
                    });
                    
                    itemsBody.appendChild(clone);
                });
            }

            document.getElementById('discountInput').addEventListener('input', calculateTotals);
            document.getElementById('discountType').addEventListener('change', calculateTotals);
            document.getElementById('shippingInput').addEventListener('input', calculateTotals);
            document.getElementById('extraExpensesInput').addEventListener('input', calculateTotals);

            itemsBody.addEventListener('click', function(e) {
                if (e.target.closest('.remove-row')) {
                    if (itemsBody.children.length > 1) {
                        e.target.closest('.item-row').remove();
                        calculateTotals();
                    }
                }
            });

            itemsBody.addEventListener('input', function(e) {
                if (e.target.classList.contains('qty-input') || e.target.classList.contains('price-input')) {
                    calculateTotals();
                }
                
                // Product autocomplete
                if (e.target.getAttribute('list') === 'productsList') {
                    const option = document.querySelector(`#productsList option[value="${e.target.value}"]`);
                    if (option) {
                        const row = e.target.closest('.item-row');
                        row.querySelector('.price-input').value = option.dataset.price;
                        calculateTotals();
                    }
                }
            });

            taxInput.addEventListener('input', calculateTotals);
        });
    </script>
@endsection
