@include('admin.header')

<div class="container-fluid">
    <div class="row mb-3">
        <div class="col-md-8">
            <h1><i class="fas fa-edit me-2"></i>Edit Order Confirmation</h1>
            <p class="text-muted">Order #{{ $orderConfirmation->order_number }}</p>
        </div>
        <div class="col-md-4 text-right">
            <a href="{{ route('admin.order-confirmations.show', $orderConfirmation) }}" class="btn btn-outline-secondary">
                <i class="fas fa-arrow-left me-1"></i>Back to Order
            </a>
        </div>
    </div>

    @if ($errors->any())
        <div class="alert alert-danger">
            <h6><i class="fas fa-exclamation-circle me-2"></i>Please fix the following errors:</h6>
            <ul class="mb-0">
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif

    <form action="{{ route('admin.order-confirmations.update', $orderConfirmation) }}" method="POST">
        @csrf
        @method('PUT')

        <!-- Order Information (Read Only) -->
        <div class="card mb-4">
            <div class="card-header bg-info text-white">
                <h5 class="mb-0"><i class="fas fa-info-circle me-2"></i>Order Information (Read Only)</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-4">
                        <div class="info-item mb-3">
                            <label class="text-muted small">Order Number</label>
                            <div class="fw-bold">{{ $orderConfirmation->order_number }}</div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="info-item mb-3">
                            <label class="text-muted small">Customer</label>
                            <div class="fw-bold">{{ $orderConfirmation->quotation->inquiry->buyer->company_name ?? 'N/A' }}</div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="info-item mb-3">
                            <label class="text-muted small">Item Description</label>
                            <div class="fw-bold">{{ $orderConfirmation->quotation->inquiry->itemDescription->name ?? 'N/A' }}</div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="info-item mb-3">
                            <label class="text-muted small">Current Status</label>
                            <div>
                                <span class="badge bg-{{ $orderConfirmation->status_badge_color }}">
                                    {{ ucfirst(str_replace('_', ' ', $orderConfirmation->status)) }}
                                </span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="info-item mb-3">
                            <label class="text-muted small">Created Date</label>
                            <div class="fw-bold">{{ $orderConfirmation->created_at->format('M d, Y H:i') }}</div>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="info-item mb-3">
                            <label class="text-muted small">Quotation</label>
                            <div class="fw-bold">
                                <a href="{{ route('admin.quotations.show', $orderConfirmation->quotation) }}" class="text-decoration-none">
                                    {{ $orderConfirmation->quotation->quotation_number }}
                                </a>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Editable Order Details -->
        <div class="card mb-4">
            <div class="card-header bg-primary text-white">
                <h5 class="mb-0"><i class="fas fa-edit me-2"></i>Order Details</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group mb-3">
                            <label for="customer_po_number" class="form-label">Customer PO Number</label>
                            <input type="text" name="customer_po_number" id="customer_po_number" 
                                   class="form-control" value="{{ old('customer_po_number', $orderConfirmation->customer_po_number) }}"
                                   placeholder="Enter customer purchase order number">
                            <small class="form-text text-muted">Customer's purchase order reference</small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group mb-3">
                            <label for="delivery_date" class="form-label">Delivery Date</label>
                            <input type="date" name="delivery_date" id="delivery_date" 
                                   class="form-control" value="{{ old('delivery_date', $orderConfirmation->delivery_date?->format('Y-m-d')) }}">
                            <small class="form-text text-muted">Expected delivery date</small>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-6">
                        <div class="form-group mb-3">
                            <label for="confirmed_quantity" class="form-label">Confirmed Quantity <span class="text-danger">*</span></label>
                            <input type="number" name="confirmed_quantity" id="confirmed_quantity" 
                                   class="form-control" value="{{ old('confirmed_quantity', $orderConfirmation->confirmed_quantity) }}"
                                   min="1" required>
                            <small class="form-text text-muted">Final confirmed order quantity</small>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="form-group mb-3">
                            <label for="confirmed_price" class="form-label">Confirmed Price (per unit) <span class="text-danger">*</span></label>
                            <div class="input-group">
                                <span class="input-group-text">$</span>
                                <input type="number" name="confirmed_price" id="confirmed_price" 
                                       class="form-control" value="{{ old('confirmed_price', $orderConfirmation->confirmed_price) }}"
                                       min="0" step="0.01" required>
                            </div>
                            <small class="form-text text-muted">Final confirmed price per unit</small>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group mb-3">
                            <label for="payment_terms" class="form-label">Payment Terms</label>
                            <textarea name="payment_terms" id="payment_terms" class="form-control" rows="3"
                                      placeholder="Enter payment terms and conditions">{{ old('payment_terms', $orderConfirmation->payment_terms) }}</textarea>
                            <small class="form-text text-muted">Payment terms, conditions, and schedule</small>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group mb-3">
                            <label for="special_instructions" class="form-label">Special Instructions</label>
                            <textarea name="special_instructions" id="special_instructions" class="form-control" rows="3"
                                      placeholder="Enter any special instructions or requirements">{{ old('special_instructions', $orderConfirmation->special_instructions) }}</textarea>
                            <small class="form-text text-muted">Any special requirements, packaging instructions, etc.</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Updated Order Summary -->
        <div class="card mb-4">
            <div class="card-header bg-success text-white">
                <h5 class="mb-0"><i class="fas fa-calculator me-2"></i>Updated Order Summary</h5>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-3">
                        <div class="summary-item text-center p-3 border rounded">
                            <h6 class="text-muted">Quantity</h6>
                            <h4 id="summary_quantity">{{ number_format($orderConfirmation->confirmed_quantity) }}</h4>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-item text-center p-3 border rounded">
                            <h6 class="text-muted">Unit Price</h6>
                            <h4 id="summary_unit_price">${{ number_format($orderConfirmation->confirmed_price, 2) }}</h4>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-item text-center p-3 border rounded">
                            <h6 class="text-muted">Total Value</h6>
                            <h4 id="summary_total_value" class="text-success">
                                ${{ number_format($orderConfirmation->total_value, 2) }}
                            </h4>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="summary-item text-center p-3 border rounded">
                            <h6 class="text-muted">Original Quote</h6>
                            <h4 class="text-info">${{ number_format($orderConfirmation->quotation->quoted_price, 2) }}</h4>
                            <small class="text-muted">
                                @php
                                    $difference = $orderConfirmation->confirmed_price - $orderConfirmation->quotation->quoted_price;
                                    $percentChange = $orderConfirmation->quotation->quoted_price > 0 ? ($difference / $orderConfirmation->quotation->quoted_price) * 100 : 0;
                                @endphp
                                @if($difference > 0)
                                    <span class="text-success">+${{ number_format($difference, 2) }} (+{{ number_format($percentChange, 1) }}%)</span>
                                @elseif($difference < 0)
                                    <span class="text-danger">${{ number_format($difference, 2) }} ({{ number_format($percentChange, 1) }}%)</span>
                                @else
                                    <span class="text-muted">No change</span>
                                @endif
                            </small>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Change Log -->
        @if($orderConfirmation->updated_at != $orderConfirmation->created_at)
        <div class="card mb-4">
            <div class="card-header bg-warning text-dark">
                <h6 class="mb-0"><i class="fas fa-history me-2"></i>Last Updated</h6>
            </div>
            <div class="card-body">
                <p class="mb-0">
                    <strong>Last modified:</strong> {{ $orderConfirmation->updated_at->format('M d, Y H:i') }}
                    @if($orderConfirmation->updater)
                        by {{ $orderConfirmation->updater->name }}
                    @endif
                </p>
            </div>
        </div>
        @endif

        <!-- Action Buttons -->
        <div class="card">
            <div class="card-body">
                <div class="d-flex justify-content-between">
                    <a href="{{ route('admin.order-confirmations.show', $orderConfirmation) }}" class="btn btn-outline-secondary">
                        <i class="fas fa-times me-1"></i>Cancel
                    </a>
                    <div>
                        <button type="button" class="btn btn-outline-primary me-2" onclick="resetForm()">
                            <i class="fas fa-undo me-1"></i>Reset Changes
                        </button>
                        <button type="submit" class="btn btn-success btn-lg">
                            <i class="fas fa-save me-1"></i>Update Order Confirmation
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </form>
</div>

<script>
// Store original values for reset functionality
const originalValues = {
    customer_po_number: '{{ $orderConfirmation->customer_po_number }}',
    delivery_date: '{{ $orderConfirmation->delivery_date?->format('Y-m-d') }}',
    confirmed_quantity: {{ $orderConfirmation->confirmed_quantity }},
    confirmed_price: {{ $orderConfirmation->confirmed_price }},
    payment_terms: `{{ $orderConfirmation->payment_terms }}`,
    special_instructions: `{{ $orderConfirmation->special_instructions }}`
};

// Update summary when quantity or price changes
function updateSummary() {
    const quantity = parseInt(document.getElementById('confirmed_quantity').value) || 0;
    const price = parseFloat(document.getElementById('confirmed_price').value) || 0;
    const totalValue = quantity * price;
    
    document.getElementById('summary_quantity').textContent = quantity.toLocaleString();
    document.getElementById('summary_unit_price').textContent = '$' + price.toFixed(2);
    document.getElementById('summary_total_value').textContent = '$' + totalValue.toLocaleString('en-US', {minimumFractionDigits: 2});
}

// Reset form to original values
function resetForm() {
    if (confirm('Are you sure you want to reset all changes?')) {
        document.getElementById('customer_po_number').value = originalValues.customer_po_number;
        document.getElementById('delivery_date').value = originalValues.delivery_date;
        document.getElementById('confirmed_quantity').value = originalValues.confirmed_quantity;
        document.getElementById('confirmed_price').value = originalValues.confirmed_price;
        document.getElementById('payment_terms').value = originalValues.payment_terms;
        document.getElementById('special_instructions').value = originalValues.special_instructions;
        updateSummary();
    }
}

// Event listeners
document.getElementById('confirmed_quantity').addEventListener('input', updateSummary);
document.getElementById('confirmed_price').addEventListener('input', updateSummary);

// Form validation
document.querySelector('form').addEventListener('submit', function(e) {
    const quantity = parseInt(document.getElementById('confirmed_quantity').value);
    const price = parseFloat(document.getElementById('confirmed_price').value);
    
    if (quantity <= 0) {
        e.preventDefault();
        alert('Quantity must be greater than 0');
        document.getElementById('confirmed_quantity').focus();
        return;
    }
    
    if (price <= 0) {
        e.preventDefault();
        alert('Price must be greater than 0');
        document.getElementById('confirmed_price').focus();
        return;
    }
    
    // Check for significant price changes
    const originalPrice = {{ $orderConfirmation->quotation->quoted_price }};
    const priceChange = Math.abs(price - originalPrice) / originalPrice * 100;
    
    if (priceChange > 10) {
        if (!confirm(`The price has changed by ${priceChange.toFixed(1)}% from the original quote. Are you sure you want to continue?`)) {
            e.preventDefault();
            return;
        }
    }
});

// Highlight changed fields
document.addEventListener('DOMContentLoaded', function() {
    const fields = ['customer_po_number', 'delivery_date', 'confirmed_quantity', 'confirmed_price', 'payment_terms', 'special_instructions'];
    
    fields.forEach(fieldName => {
        const field = document.getElementById(fieldName);
        if (field) {
            field.addEventListener('input', function() {
                const currentValue = this.value;
                const originalValue = originalValues[fieldName];
                
                if (currentValue != originalValue) {
                    this.classList.add('border-warning');
                    this.classList.remove('border-success');
                } else {
                    this.classList.remove('border-warning');
                    this.classList.add('border-success');
                }
            });
        }
    });
});
</script>

@include('admin.footer')

