@extends('layouts.app')

@section('content')
<div class="card">
    <div class="card-header">
        <h3 class="card-title"><i class="fas fa-receipt"></i> New Sale Bill</h3>
        <a href="{{ route('sales.index') }}" class="btn btn-outline">
            <i class="fas fa-arrow-left"></i> Back
        </a>
    </div>
    <div class="card-body">
        @if ($errors->any())
            <div class="alert alert-danger">
                <strong><i class="fas fa-exclamation-circle"></i> Please fix the following errors:</strong>
                <ul style="margin: 0.5rem 0 0 1rem;">
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif

        <form action="{{ route('sales.store') }}" method="POST" id="saleForm">
            @csrf
            
            <!-- Bill Header -->
            <div class="form-row">
                <div class="form-group" style="flex: 0 0 150px;">
                    <label class="form-label" for="bill_no">Bill No. <span class="text-danger">*</span></label>
                    <input type="text" class="form-control @error('bill_no') is-invalid @enderror" id="bill_no" name="bill_no" 
                           value="{{ old('bill_no', $nextBillNo) }}" readonly style="background: var(--light-bg);">
                </div>

                <div class="form-group" style="flex: 0 0 150px;">
                    <label class="form-label" for="date">Date <span class="text-danger">*</span></label>
                    <input type="date" class="form-control @error('date') is-invalid @enderror" id="date" name="date" 
                           value="{{ old('date', date('Y-m-d')) }}" required>
                </div>

                <div class="form-group" style="flex: 1;">
                    <label class="form-label" for="party_id">Customer <span class="text-danger">*</span></label>
                    <select class="form-control @error('party_id') is-invalid @enderror" id="party_id" name="party_id" required>
                        <option value="">Select Customer</option>
                        @foreach($parties as $party)
                            <option value="{{ $party->id }}" {{ old('party_id') == $party->id ? 'selected' : '' }}>
                                {{ $party->name }} ({{ $party->code }})
                            </option>
                        @endforeach
                    </select>
                </div>

                <div class="form-group" style="flex: 0 0 150px;">
                    <label class="form-label" for="ref_no">Reference No.</label>
                    <input type="text" class="form-control" id="ref_no" name="ref_no" 
                           value="{{ old('ref_no') }}" placeholder="Customer PO #">
                </div>
            </div>

            <!-- Items Table -->
            <div class="card mt-3" style="border: 1px solid var(--border-color);">
                <div class="card-header" style="background: var(--light-bg); padding: 0.75rem 1rem;">
                    <h4 style="font-size: 0.9375rem; font-weight: 600; margin: 0;">
                        <i class="fas fa-list"></i> Sale Items (FINISH Products)
                    </h4>
                </div>
                <div class="card-body" style="padding: 0; overflow-x: auto;">
                    <table id="itemsTable">
                        <thead>
                            <tr>
                                <th style="width: 50px;">#</th>
                                <th style="min-width: 250px;">Item</th>
                                <th style="width: 100px;">Available</th>
                                <th style="width: 100px;">Qty</th>
                                <th style="width: 80px;">Unit</th>
                                <th style="width: 120px;">Rate</th>
                                <th style="width: 120px;">Amount</th>
                                <th style="width: 50px;"></th>
                            </tr>
                        </thead>
                        <tbody id="itemsBody">
                            <tr class="item-row" data-row="0">
                                <td class="text-center">1</td>
                                <td>
                                    <select class="form-control item-select" name="items[0][item_id]" style="width: 100%;" required>
                                        <option value="">Select Item</option>
                                        @foreach($items as $item)
                                            <option value="{{ $item->id }}" 
                                                    data-price="{{ $item->sale_price }}" 
                                                    data-unit="{{ $item->unit }}"
                                                    data-stock="{{ $item->current_stock }}">
                                                {{ $item->code }} - {{ $item->name }}
                                            </option>
                                        @endforeach
                                    </select>
                                </td>
                                <td>
                                    <input type="text" class="form-control stock-display text-center" readonly 
                                           value="-" style="background: var(--light-bg);">
                                </td>
                                <td>
                                    <input type="number" class="form-control qty-input" name="items[0][quantity]" 
                                           step="0.01" min="0.01" value="1" required>
                                </td>
                                <td>
                                    <input type="text" class="form-control unit-display text-center" readonly 
                                           value="" style="background: var(--light-bg);">
                                </td>
                                <td>
                                    <input type="number" class="form-control rate-input" name="items[0][rate]" 
                                           step="0.01" min="0" value="0" required>
                                </td>
                                <td>
                                    <input type="number" class="form-control amount-display" readonly value="0"
                                           style="background: var(--light-bg); font-weight: 600;">
                                </td>
                                <td class="text-center">
                                    <button type="button" class="btn btn-outline remove-row" style="padding: 0.25rem 0.5rem; color: var(--danger-color);">
                                        <i class="fas fa-times"></i>
                                    </button>
                                </td>
                            </tr>
                        </tbody>
                        <tfoot>
                            <tr>
                                <td colspan="8">
                                    <button type="button" class="btn btn-outline" id="addRow" style="width: 100%;">
                                        <i class="fas fa-plus"></i> Add New Row
                                    </button>
                                </td>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>

            <!-- Bill Footer -->
            <div class="form-row mt-4">
                <div class="form-group" style="flex: 1;">
                    <label class="form-label" for="remarks">Remarks / Notes</label>
                    <textarea class="form-control" id="remarks" name="remarks" rows="3" 
                              placeholder="Optional notes about this sale...">{{ old('remarks') }}</textarea>
                </div>

                <div style="flex: 0 0 300px;">
                    <table style="width: 100%; border: none;">
                        <tr>
                            <td style="padding: 0.5rem; border: none; text-align: right;">Gross Amount:</td>
                            <td style="padding: 0.5rem; border: none; text-align: right; width: 150px;">
                                <strong id="grossAmount">Rs. 0.00</strong>
                                <input type="hidden" name="gross_amount" id="grossAmountInput" value="0">
                            </td>
                        </tr>
                        <tr>
                            <td style="padding: 0.5rem; border: none; text-align: right;">Discount (-):</td>
                            <td style="padding: 0.5rem; border: none; text-align: right;">
                                <input type="number" class="form-control" id="discount" name="discount" 
                                       step="0.01" min="0" value="{{ old('discount', 0) }}" style="width: 100%; text-align: right;">
                            </td>
                        </tr>
                        <tr style="background: var(--light-bg);">
                            <td style="padding: 0.75rem; border: none; text-align: right; font-size: 1.125rem;">
                                <strong>Net Amount:</strong>
                            </td>
                            <td style="padding: 0.75rem; border: none; text-align: right; font-size: 1.25rem;">
                                <strong id="netAmount" class="text-success">Rs. 0.00</strong>
                                <input type="hidden" name="net_amount" id="netAmountInput" value="0">
                            </td>
                        </tr>
                    </table>
                </div>
            </div>

            <div style="display: flex; gap: 0.5rem; margin-top: 1.5rem; padding-top: 1rem; border-top: 1px solid var(--border-color);">
                <button type="submit" class="btn btn-success">
                    <i class="fas fa-save"></i> Save Sale
                </button>
                <button type="submit" name="save_and_new" value="1" class="btn btn-outline">
                    <i class="fas fa-plus"></i> Save & New
                </button>
                <a href="{{ route('sales.index') }}" class="btn btn-outline">
                    Cancel
                </a>
            </div>
        </form>
    </div>
</div>

<script>
    let rowCount = 1;
    const itemsData = @json($items);

    // Add new row
    document.getElementById('addRow').addEventListener('click', function() {
        const tbody = document.getElementById('itemsBody');
        const newRow = document.createElement('tr');
        newRow.className = 'item-row';
        newRow.dataset.row = rowCount;
        
        let itemOptions = '<option value="">Select Item</option>';
        itemsData.forEach(item => {
            itemOptions += `<option value="${item.id}" data-price="${item.sale_price}" data-unit="${item.unit}" data-stock="${item.current_stock}">${item.code} - ${item.name}</option>`;
        });
        
        newRow.innerHTML = `
            <td class="text-center">${rowCount + 1}</td>
            <td>
                <select class="form-control item-select" name="items[${rowCount}][item_id]" style="width: 100%;" required>
                    ${itemOptions}
                </select>
            </td>
            <td>
                <input type="text" class="form-control stock-display text-center" readonly value="-" style="background: var(--light-bg);">
            </td>
            <td>
                <input type="number" class="form-control qty-input" name="items[${rowCount}][quantity]" step="0.01" min="0.01" value="1" required>
            </td>
            <td>
                <input type="text" class="form-control unit-display text-center" readonly value="" style="background: var(--light-bg);">
            </td>
            <td>
                <input type="number" class="form-control rate-input" name="items[${rowCount}][rate]" step="0.01" min="0" value="0" required>
            </td>
            <td>
                <input type="number" class="form-control amount-display" readonly value="0" style="background: var(--light-bg); font-weight: 600;">
            </td>
            <td class="text-center">
                <button type="button" class="btn btn-outline remove-row" style="padding: 0.25rem 0.5rem; color: var(--danger-color);">
                    <i class="fas fa-times"></i>
                </button>
            </td>
        `;
        
        tbody.appendChild(newRow);
        rowCount++;
        attachRowEvents(newRow);
    });

    // Remove row
    document.addEventListener('click', function(e) {
        if (e.target.closest('.remove-row')) {
            const rows = document.querySelectorAll('.item-row');
            if (rows.length > 1) {
                e.target.closest('.item-row').remove();
                updateRowNumbers();
                calculateTotals();
            } else {
                alert('At least one item row is required.');
            }
        }
    });

    function attachRowEvents(row) {
        const itemSelect = row.querySelector('.item-select');
        const qtyInput = row.querySelector('.qty-input');
        const rateInput = row.querySelector('.rate-input');

        itemSelect.addEventListener('change', function() {
            const option = this.options[this.selectedIndex];
            if (option.value) {
                rateInput.value = parseFloat(option.dataset.price || 0).toFixed(2);
                row.querySelector('.unit-display').value = option.dataset.unit || '';
                row.querySelector('.stock-display').value = parseFloat(option.dataset.stock || 0).toFixed(2);
            } else {
                rateInput.value = '0';
                row.querySelector('.unit-display').value = '';
                row.querySelector('.stock-display').value = '-';
            }
            calculateRow(row);
        });

        [qtyInput, rateInput].forEach(input => {
            input.addEventListener('input', () => calculateRow(row));
        });
    }

    function calculateRow(row) {
        const qty = parseFloat(row.querySelector('.qty-input').value) || 0;
        const rate = parseFloat(row.querySelector('.rate-input').value) || 0;
        const amount = qty * rate;
        
        row.querySelector('.amount-display').value = amount.toFixed(2);
        
        // Check stock warning
        const stock = parseFloat(row.querySelector('.stock-display').value) || 0;
        if (qty > stock && stock > 0) {
            row.querySelector('.qty-input').style.borderColor = 'var(--warning-color)';
        } else {
            row.querySelector('.qty-input').style.borderColor = '';
        }
        
        calculateTotals();
    }

    function calculateTotals() {
        let grossAmount = 0;
        document.querySelectorAll('.amount-display').forEach(input => {
            grossAmount += parseFloat(input.value) || 0;
        });

        const discount = parseFloat(document.getElementById('discount').value) || 0;
        const netAmount = grossAmount - discount;

        document.getElementById('grossAmount').textContent = 'Rs. ' + grossAmount.toLocaleString('en-PK', {minimumFractionDigits: 2, maximumFractionDigits: 2});
        document.getElementById('grossAmountInput').value = grossAmount.toFixed(2);
        
        document.getElementById('netAmount').textContent = 'Rs. ' + netAmount.toLocaleString('en-PK', {minimumFractionDigits: 2, maximumFractionDigits: 2});
        document.getElementById('netAmountInput').value = netAmount.toFixed(2);
    }

    function updateRowNumbers() {
        document.querySelectorAll('.item-row').forEach((row, index) => {
            row.querySelector('td:first-child').textContent = index + 1;
        });
    }

    // Initialize first row events
    document.querySelectorAll('.item-row').forEach(row => attachRowEvents(row));
    
    // Recalculate when discount changes
    document.getElementById('discount').addEventListener('input', calculateTotals);
    
    // Form validation
    document.getElementById('saleForm').addEventListener('submit', function(e) {
        const items = document.querySelectorAll('.item-select');
        let hasValidItem = false;
        items.forEach(select => {
            if (select.value) hasValidItem = true;
        });
        
        if (!hasValidItem) {
            e.preventDefault();
            alert('Please add at least one item to the sale.');
            return false;
        }
    });
</script>
@endsection
