@extends('layouts.admin-simple')

@section('title', 'Create Direct Delivery')

@push('styles')
<style>
/* Adjust Select2 dropdown widths for better proportions */
.select2-container {
    width: 100% !important;
}

/* Make dropdowns auto-width based on content */
.select2-dropdown {
    min-width: 200px;
    max-width: 400px;
    width: auto !important;
}

/* Ensure the selection box doesn't get too wide */
.select2-container .select2-selection--single {
    min-width: 200px;
    max-width: 100%;
}

/* Allow dropdown to expand based on content */
.select2-container--open .select2-dropdown--below {
    width: auto !important;
    min-width: 200px;
}
</style>
@endpush

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title mb-0">
                        <i class="material-icons mr-2">add</i>
                        Create Direct Delivery
                    </h4>
                </div>

                <form action="{{ route('warehouse.direct-deliveries.store') }}" method="POST">
                    @csrf
                    <div class="card-body">
                        <div class="row">
                            <!-- Basic Information -->
                            <div class="col-md-6">
                                <x-warehouse.select2-dropdown
                                    name="supplier_id"
                                    id="supplier_id"
                                    label="Supplier"
                                    placeholder="Select Supplier"
                                    :options="$suppliers->map(function($supplier) {
                                        return ['value' => $supplier->id, 'text' => $supplier->name];
                                    })"
                                    :selected="old('supplier_id')"
                                    required="true"
                                    errorField="supplier_id"
                                />
                            </div>

                            <div class="col-md-6">
                                <x-warehouse.select2-dropdown
                                    name="project_id"
                                    id="project_id"
                                    label="Destination Project"
                                    placeholder="Select Project"
                                    :options="$projects->map(function($project) {
                                        return ['value' => $project->id, 'text' => $project->project_name];
                                    })"
                                    :selected="old('project_id')"
                                    required="true"
                                    errorField="project_id"
                                />
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="delivery_date">Delivery Date <span class="text-danger">*</span></label>
                                    <input type="date" name="delivery_date" id="delivery_date"
                                           class="form-control @error('delivery_date') is-invalid @enderror"
                                           value="{{ old('delivery_date', date('Y-m-d')) }}" required>
                                    @error('delivery_date')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <x-warehouse.select2-dropdown
                                    name="delivery_type"
                                    id="delivery_type"
                                    label="Delivery Type"
                                    placeholder="Select Type"
                                    :options="[
                                        ['value' => 'purchase_order', 'text' => 'Purchase Order'],
                                        ['value' => 'direct_purchase', 'text' => 'Direct Purchase'],
                                        ['value' => 'emergency', 'text' => 'Emergency']
                                    ]"
                                    :selected="old('delivery_type', 'purchase_order')"
                                    required="true"
                                    errorField="delivery_type"
                                    allowClear="false"
                                />
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="lpo_number">LPO Number</label>
                                    <input type="text" name="lpo_number" id="lpo_number"
                                           class="form-control @error('lpo_number') is-invalid @enderror"
                                           value="{{ old('lpo_number') }}"
                                           placeholder="e.g., LPO-2024-001">
                                    @error('lpo_number')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="delivery_note_number">Delivery Note Number <span class="text-danger">*</span></label>
                                    <input type="text" name="delivery_note_number" id="delivery_note_number"
                                           class="form-control @error('delivery_note_number') is-invalid @enderror"
                                           value="{{ old('delivery_note_number') }}"
                                           placeholder="e.g., DN-2024-001"
                                           required>
                                    @error('delivery_note_number')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="supplier_delivery_note">Supplier Delivery Note</label>
                                    <input type="text" name="supplier_delivery_note" id="supplier_delivery_note"
                                           class="form-control @error('supplier_delivery_note') is-invalid @enderror"
                                           value="{{ old('supplier_delivery_note') }}"
                                           placeholder="Supplier's delivery note reference">
                                    @error('supplier_delivery_note')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="delivered_by">Delivered By</label>
                                    <input type="text" name="delivered_by" id="delivered_by"
                                           class="form-control @error('delivered_by') is-invalid @enderror"
                                           value="{{ old('delivered_by') }}"
                                           placeholder="Driver/person name">
                                    @error('delivered_by')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="vehicle_number">Vehicle Number</label>
                                    <input type="text" name="vehicle_number" id="vehicle_number"
                                           class="form-control @error('vehicle_number') is-invalid @enderror"
                                           value="{{ old('vehicle_number') }}"
                                           placeholder="Vehicle registration number">
                                    @error('vehicle_number')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="order_date">Order Date</label>
                                    <input type="date" name="order_date" id="order_date"
                                           class="form-control @error('order_date') is-invalid @enderror"
                                           value="{{ old('order_date') }}">
                                    @error('order_date')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="requires_approval">
                                        <input type="checkbox" name="requires_approval" id="requires_approval"
                                               value="1" {{ old('requires_approval') ? 'checked' : '' }}>
                                        Requires Approval
                                    </label>
                                    <small class="form-text text-muted">Check if this delivery requires managerial approval</small>
                                </div>
                            </div>

                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="can_be_returned">
                                        <input type="checkbox" name="can_be_returned" id="can_be_returned"
                                               value="1" {{ old('can_be_returned', true) ? 'checked' : '' }}>
                                        Allow Site Returns
                                    </label>
                                    <small class="form-text text-muted">Check if delivered items can be returned from site</small>
                                </div>
                            </div>

                            <div class="col-12">
                                <div class="form-group">
                                    <label for="delivery_notes">Delivery Notes</label>
                                    <textarea name="delivery_notes" id="delivery_notes"
                                              class="form-control @error('delivery_notes') is-invalid @enderror"
                                              rows="3" placeholder="Any additional notes about this delivery">{{ old('delivery_notes') }}</textarea>
                                    @error('delivery_notes')
                                    <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>

                        <!-- Items Section -->
                        <div class="row mt-4">
                            <div class="col-12">
                                <h5 class="border-bottom pb-2 mb-3">
                                    <i class="material-icons mr-2">list</i>
                                    Delivery Items
                                </h5>

                                <div class="table-responsive">
                                    <table class="table table-bordered" id="items-table">
                                        <thead class="thead-light">
                                            <tr>
                                                <th width="20%">Item</th>
                                                <th width="8%">Ordered Qty</th>
                                                <th width="8%">Delivered Qty</th>
                                                <th width="6%">Unit</th>
                                                <th width="10%">Unit Price ({{ config('app.currency', 'AED') }})</th>
                                                <th width="8%">Batch #</th>
                                                <th width="10%">Production Date</th>
                                                <th width="10%">Expiry Date</th>
                                                <th width="15%" class="text-right">Total</th>
                                                <th width="5%">Action</th>
                                            </tr>
                                        </thead>
                                        <tbody id="items-tbody">
                                            <!-- Items will be added here dynamically -->
                                        </tbody>
                                        <tfoot class="bg-light">
                                            <tr>
                                                <td class="text-right font-weight-bold" style="text-align:right;" colspan="10">Total Amount (AED): <span id="total-amount" class="text-primary">0.00</span>
                                                    <input type="hidden" name="total_amount" id="total_amount_input" value="0">
                                                </td>
                                            </tr>
                                        </tfoot>
                                    </table>
                                </div>

                                <button type="button" class="btn btn-outline-primary mt-2" onclick="addItemRow()">
                                    <i class="material-icons mr-1">add</i>
                                    Add Item
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="card-footer">
                        <div class="row">
                            <div class="col-md-6">
                                <a href="{{ route('warehouse.direct-deliveries.index') }}" class="btn btn-secondary">
                                    <i class="material-icons mr-1">arrow_back</i>
                                    Back to List
                                </a>
                            </div>
                            <div class="col-md-6 text-right">
                                <button type="submit" class="btn btn-primary">
                                    <i class="material-icons mr-1">save</i>
                                    Create Direct Delivery
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>
@endsection

@push('scripts')
<script>
let itemRowIndex = 0;
let itemsList = @json($items);

function addItemRow() {
    const tbody = document.getElementById('items-tbody');
    const row = document.createElement('tr');
    row.innerHTML = `
        <td>
            <select name="items[${itemRowIndex}][item_id]" class="form-control" onchange="updateItemRow(this, ${itemRowIndex})" required>
                <option value="">Select Item</option>
                ${itemsList.map(item => `<option value="${item.id}">${item.item_description} ${item.item_code ? '(' + item.item_code + ')' : ''}</option>`).join('')}
            </select>
        </td>
        <td>
            <input type="number" name="items[${itemRowIndex}][ordered_quantity]"
                   class="form-control" step="0.01" min="0.01" onchange="calculateTotal(${itemRowIndex})" required>
        </td>
        <td>
            <input type="number" name="items[${itemRowIndex}][delivered_quantity]"
                   class="form-control" step="0.01" min="0.01" onchange="calculateTotal(${itemRowIndex})" required>
        </td>
        <td>
            <input type="text" name="items[${itemRowIndex}][unit_of_measure]"
                   class="form-control" placeholder="e.g., pcs, kg">
        </td>
        <td>
            <input type="number" name="items[${itemRowIndex}][unit_price]"
                   class="form-control" step="0.01" min="0" onchange="calculateTotal(${itemRowIndex})" required>
        </td>
        <td>
            <input type="text" name="items[${itemRowIndex}][batch_number]" class="form-control">
        </td>
        <td>
            <input type="date" name="items[${itemRowIndex}][production_date]" class="form-control">
        </td>
        <td>
            <input type="date" name="items[${itemRowIndex}][expiry_date]" class="form-control">
        </td>
        <td>
            <input type="text" class="form-control text-right" id="total_${itemRowIndex}" readonly>
        </td>
        <td>
            <button type="button" class="btn btn-sm btn-outline-danger" onclick="removeItemRow(this)">
                <i class="material-icons">delete</i>
            </button>
        </td>
    `;

    tbody.appendChild(row);
    itemRowIndex++;
}

function updateItemRow(select, rowIndex) {
    // Populate item details based on selection
    const selectedOption = select.options[select.selectedIndex];
    // You can extend this to populate additional item details if needed
}

function calculateTotal(rowIndex) {
    const deliveredQty = parseFloat(document.querySelector(`input[name="items[${rowIndex}][delivered_quantity]"]`).value) || 0;
    const unitPrice = parseFloat(document.querySelector(`input[name="items[${rowIndex}][unit_price]"]`).value) || 0;
    const total = deliveredQty * unitPrice;

    document.getElementById(`total_${rowIndex}`).value = total.toFixed(2);

    // Calculate overall total
    updateTotalAmount();
}

function updateTotalAmount() {
    let grandTotal = 0;

    // Sum all individual totals
    document.querySelectorAll('[id^="total_"]').forEach(function(totalInput) {
        const value = parseFloat(totalInput.value) || 0;
        grandTotal += value;
    });

    // Update the display
    document.getElementById('total-amount').textContent = grandTotal.toFixed(2);
    document.getElementById('total_amount_input').value = grandTotal.toFixed(2);
}

function removeItemRow(button) {
    button.closest('tr').remove();
    // Recalculate total amount after removing row
    updateTotalAmount();
}

// Add initial row
document.addEventListener('DOMContentLoaded', function() {
    addItemRow();
});
</script>
@endpush