@extends('layouts.admin')

@section('title', 'Create New Order')

@section('content')
<div class="py-12">
    <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
        <div class="bg-white dark:bg-gray-800 overflow-hidden shadow-sm sm:rounded-lg">
            <div class="p-6 text-gray-900 dark:text-gray-100">
                <!-- Header -->
                <div class="flex justify-between items-center mb-6">
                    <h2 class="text-2xl font-bold">Create New Order</h2>
                    <a href="{{ route('admin.orders.index') }}" 
                       class="bg-gray-600 hover:bg-gray-700 text-white px-4 py-2 rounded-lg font-semibold transition-colors">
                        Back to Orders
                    </a>
                </div>

                <!-- Error Messages -->
                @if($errors->any())
                    <div class="mb-4 bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
                        <ul class="list-disc list-inside">
                            @foreach($errors->all() as $error)
                                <li>{{ $error }}</li>
                            @endforeach
                        </ul>
                    </div>
                @endif

                <form action="{{ route('admin.orders.store') }}" method="POST" id="orderForm">
                    @csrf
                    
                    <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
                        <!-- Customer Information -->
                        <div class="lg:col-span-2 space-y-6">
                            <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-6">
                                <h3 class="text-lg font-semibold mb-4">Customer Information</h3>
                                
                                <div class="mb-4">
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Customer Type</label>
                                    <div class="flex space-x-4">
                                        <label class="flex items-center">
                                            <input type="radio" name="customer_type" value="existing" class="mr-2" onchange="toggleCustomerFields()">
                                            Existing Customer
                                        </label>
                                        <label class="flex items-center">
                                            <input type="radio" name="customer_type" value="new" class="mr-2" checked onchange="toggleCustomerFields()">
                                            New Customer
                                        </label>
                                    </div>
                                </div>

                                <div id="existingCustomerField" class="mb-4 hidden">
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Select Customer</label>
                                    <select name="customer_id" class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500" onchange="fillCustomerData()">
                                        <option value="">Select a customer...</option>
                                        @foreach($customers as $customer)
                                            <option value="{{ $customer->id }}" data-name="{{ $customer->name }}" data-phone="{{ $customer->phone }}">
                                                {{ $customer->name }} ({{ $customer->phone }})
                                            </option>
                                        @endforeach
                                    </select>
                                </div>

                                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Customer Name *</label>
                                        <input type="text" name="customer_name" value="{{ old('customer_name') }}" required
                                               class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500">
                                    </div>
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Phone Number *</label>
                                        <input type="text" name="customer_phone" value="{{ old('customer_phone') }}" required
                                               class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500">
                                    </div>
                                </div>

                                <div class="mt-4">
                                    <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Address *</label>
                                    <textarea name="customer_address" rows="3" required
                                              class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500">{{ old('customer_address') }}</textarea>
                                </div>
                            </div>

                            <!-- Products -->
                            <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-6">
                                <h3 class="text-lg font-semibold mb-4">Order Products</h3>
                                
                                <div id="productsList">
                                    <div class="product-item grid grid-cols-1 md:grid-cols-4 gap-4 mb-4 p-4 bg-white dark:bg-gray-800 rounded-lg">
                                        <div class="md:col-span-2">
                                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Product *</label>
                                            <select name="products[0][id]" required onchange="updateProductPrice(this, 0)"
                                                    class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500">
                                                <option value="">Select a product...</option>
                                                @foreach($products as $product)
                                                    <option value="{{ $product->id }}" data-price="{{ $product->price }}" data-unit="{{ $product->unit }}">
                                                        {{ $product->name }} - ৳{{ number_format($product->price, 2) }}/{{ $product->unit }}
                                                    </option>
                                                @endforeach
                                            </select>
                                        </div>
                                        <div>
                                            <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Quantity *</label>
                                            <input type="number" name="products[0][quantity]" min="1" value="1" required onchange="updateProductTotal(0)"
                                                   class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500">
                                        </div>
                                        <div class="flex items-end">
                                            <div class="w-full">
                                                <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Total</label>
                                                <input type="text" readonly class="product-total w-full rounded-md border-gray-300 bg-gray-100 dark:bg-gray-600 text-gray-700 dark:text-gray-300">
                                            </div>
                                            <button type="button" onclick="removeProduct(this)" class="ml-2 text-red-600 hover:text-red-800 p-2">
                                                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"></path>
                                                </svg>
                                            </button>
                                        </div>
                                    </div>
                                </div>

                                <button type="button" onclick="addProduct()" class="bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded-lg font-semibold transition-colors">
                                    Add Another Product
                                </button>
                            </div>

                            <!-- Order Notes -->
                            <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-6">
                                <h3 class="text-lg font-semibold mb-4">Order Notes</h3>
                                <textarea name="notes" rows="4" placeholder="Optional notes about this order..."
                                          class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500">{{ old('notes') }}</textarea>
                            </div>
                        </div>

                        <!-- Order Summary & Settings -->
                        <div class="space-y-6">
                            <!-- Order Settings -->
                            <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-6">
                                <h3 class="text-lg font-semibold mb-4">Order Settings</h3>
                                
                                <div class="space-y-4">
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Order Status *</label>
                                        <select name="status" required class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500">
                                            <option value="pending" {{ old('status') === 'pending' ? 'selected' : '' }}>Pending</option>
                                            <option value="confirmed" {{ old('status') === 'confirmed' ? 'selected' : '' }}>Confirmed</option>
                                            <option value="processing" {{ old('status') === 'processing' ? 'selected' : '' }}>Processing</option>
                                            <option value="shipped" {{ old('status') === 'shipped' ? 'selected' : '' }}>Shipped</option>
                                            <option value="delivered" {{ old('status') === 'delivered' ? 'selected' : '' }}>Delivered</option>
                                            <option value="cancelled" {{ old('status') === 'cancelled' ? 'selected' : '' }}>Cancelled</option>
                                        </select>
                                    </div>

                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Payment Status *</label>
                                        <select name="payment_status" required class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500">
                                            <option value="pending" {{ old('payment_status') === 'pending' ? 'selected' : '' }}>Pending</option>
                                            <option value="paid" {{ old('payment_status') === 'paid' ? 'selected' : '' }}>Paid</option>
                                            <option value="failed" {{ old('payment_status') === 'failed' ? 'selected' : '' }}>Failed</option>
                                            <option value="refunded" {{ old('payment_status') === 'refunded' ? 'selected' : '' }}>Refunded</option>
                                        </select>
                                    </div>

                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Payment Method *</label>
                                        <select name="payment_method" required class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500">
                                            <option value="cash_on_delivery" {{ old('payment_method') === 'cash_on_delivery' ? 'selected' : '' }}>Cash on Delivery</option>
                                            <option value="bkash" {{ old('payment_method') === 'bkash' ? 'selected' : '' }}>bKash</option>
                                            <option value="nagad" {{ old('payment_method') === 'nagad' ? 'selected' : '' }}>Nagad</option>
                                            <option value="rocket" {{ old('payment_method') === 'rocket' ? 'selected' : '' }}>Rocket</option>
                                            <option value="bank_transfer" {{ old('payment_method') === 'bank_transfer' ? 'selected' : '' }}>Bank Transfer</option>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <!-- Order Summary -->
                            <div class="bg-gray-50 dark:bg-gray-700 rounded-lg p-6">
                                <h3 class="text-lg font-semibold mb-4">Order Summary</h3>
                                
                                <div class="space-y-3">
                                    <div class="flex justify-between">
                                        <span>Subtotal</span>
                                        <span id="subtotalAmount">৳0.00</span>
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Shipping Amount</label>
                                        <input type="number" name="shipping_amount" step="0.01" min="0" value="{{ old('shipping_amount', 0) }}" onchange="updateOrderTotal()"
                                               class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500">
                                    </div>
                                    
                                    <div>
                                        <label class="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">Discount Amount</label>
                                        <input type="number" name="discount_amount" step="0.01" min="0" value="{{ old('discount_amount', 0) }}" onchange="updateOrderTotal()"
                                               class="w-full rounded-md border-gray-300 dark:border-gray-600 dark:bg-gray-700 focus:border-blue-500 focus:ring-blue-500">
                                    </div>
                                    
                                    <hr class="border-gray-300 dark:border-gray-600">
                                    <div class="flex justify-between font-bold text-lg">
                                        <span>Total</span>
                                        <span id="totalAmount">৳0.00</span>
                                    </div>
                                </div>

                                <button type="submit" class="w-full mt-6 bg-blue-600 hover:bg-blue-700 text-white py-3 px-4 rounded-lg font-semibold transition-colors">
                                    Create Order
                                </button>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
let productIndex = 1;

function toggleCustomerFields() {
    const customerType = document.querySelector('input[name="customer_type"]:checked').value;
    const existingField = document.getElementById('existingCustomerField');
    
    if (customerType === 'existing') {
        existingField.classList.remove('hidden');
    } else {
        existingField.classList.add('hidden');
        document.querySelector('select[name="customer_id"]').value = '';
        document.querySelector('input[name="customer_name"]').value = '';
        document.querySelector('input[name="customer_phone"]').value = '';
    }
}

function fillCustomerData() {
    const select = document.querySelector('select[name="customer_id"]');
    const option = select.selectedOptions[0];
    
    if (option && option.value) {
        document.querySelector('input[name="customer_name"]').value = option.dataset.name;
        document.querySelector('input[name="customer_phone"]').value = option.dataset.phone;
    }
}

function addProduct() {
    const productsList = document.getElementById('productsList');
    const newProduct = document.querySelector('.product-item').cloneNode(true);
    
    // Update names and IDs
    newProduct.querySelectorAll('[name]').forEach(input => {
        const name = input.name.replace(/\[\d+\]/, `[${productIndex}]`);
        input.name = name;
        input.value = input.type === 'number' ? '1' : '';
    });
    
    newProduct.querySelector('.product-total').value = '';
    newProduct.querySelector('select').setAttribute('onchange', `updateProductPrice(this, ${productIndex})`);
    newProduct.querySelector('input[type="number"]').setAttribute('onchange', `updateProductTotal(${productIndex})`);
    
    productsList.appendChild(newProduct);
    productIndex++;
}

function removeProduct(button) {
    const productsList = document.getElementById('productsList');
    if (productsList.children.length > 1) {
        button.closest('.product-item').remove();
        updateOrderTotal();
    }
}

function updateProductPrice(select, index) {
    const option = select.selectedOptions[0];
    const quantityInput = document.querySelector(`input[name="products[${index}][quantity]"]`);
    updateProductTotal(index);
}

function updateProductTotal(index) {
    const select = document.querySelector(`select[name="products[${index}][id]"]`);
    const quantityInput = document.querySelector(`input[name="products[${index}][quantity]"]`);
    const totalInput = document.querySelector(`.product-item:nth-child(${index + 1}) .product-total`);
    
    if (select && select.selectedOptions[0] && quantityInput && totalInput) {
        const price = parseFloat(select.selectedOptions[0].dataset.price || 0);
        const quantity = parseInt(quantityInput.value || 0);
        const total = price * quantity;
        
        totalInput.value = `৳${total.toFixed(2)}`;
        updateOrderTotal();
    }
}

function updateOrderTotal() {
    let subtotal = 0;
    
    document.querySelectorAll('.product-total').forEach(input => {
        const value = parseFloat(input.value.replace('৳', '') || 0);
        subtotal += value;
    });
    
    const shipping = parseFloat(document.querySelector('input[name="shipping_amount"]').value || 0);
    const discount = parseFloat(document.querySelector('input[name="discount_amount"]').value || 0);
    const total = subtotal + shipping - discount;
    
    document.getElementById('subtotalAmount').textContent = `৳${subtotal.toFixed(2)}`;
    document.getElementById('totalAmount').textContent = `৳${total.toFixed(2)}`;
}
</script>
@endsection