@extends('layouts.admin', ['title' => __('app.admin.orders')])

@section('admin-content')
    <form class="row g-2 align-items-end mb-4">
        <div class="col-md-4">
            <label class="form-label heading-label">{{ __('app.orders.search') }}</label>
            <input type="text" name="search" class="form-control rounded-4" value="{{ request('search') }}" placeholder="{{ __('app.orders.search') }}">
        </div>
        <div class="col-md-3">
            <label class="form-label heading-label">{{ __('app.orders.status') }}</label>
            <select name="status" class="form-select rounded-4">
                <option value="">{{ __('app.orders.all') }}</option>
                @foreach (['processing','ready','collected'] as $status)
                    <option value="{{ $status }}" @selected(request('status') === $status)>{{ __('app.orders.show.statuses.' . $status) }}</option>
                @endforeach
            </select>
        </div>
        <div class="col-md-2">
            <button class="btn btn-primary btn-rounded w-100" type="submit">
                <i class="bi bi-search me-2"></i>{{ __('app.orders.filter') }}
            </button>
        </div>
        <div class="col-md-3">
            <label class="form-label heading-label">{{ __('app.orders.barcode') }}</label>
            <div class="input-group barcode-input-group rounded-pill">
                <input type="text" id="barcodeSearch" class="form-control" placeholder="{{ __('app.orders.barcode') }}" autocomplete="off">
                <button class="btn btn-outline-primary barcode-scan-btn" type="button" id="barcodeLookupBtn">
                    <i class="bi bi-upc-scan"></i>
                </button>
            </div>
        </div>
        <div class="col-md-12 col-lg-3 text-lg-end">
            <a href="{{ route('service-orders.index') }}" class="btn btn-outline-primary btn-rounded w-100">
                <i class="bi bi-plus-circle me-2"></i>{{ __('app.orders.new_service') }}
            </a>
        </div>
    </form>

    <div class="table-responsive">
        <table class="table align-middle">
            <thead>
                <tr>
                    <th>{{ __('app.orders.table.order') }}</th>
                    <th>{{ __('app.orders.table.customer') }}</th>
                    <th>{{ __('app.orders.table.service') }}</th>
                    <th>{{ __('app.orders.table.total') }}</th>
                    <th>{{ __('app.orders.table.status') }}</th>
                    <th>{{ __('app.orders.table.payment') }}</th>
                    <th>{{ __('app.orders.table.actions') }}</th>
                </tr>
            </thead>
            <tbody>
                @forelse ($orders as $order)
                    <tr>
                        <td>
                            <div class="fw-semibold">{{ $order->order_number }}</div>
                            <small class="text-muted">{{ $order->created_at->translatedFormat('d M, H:i') }}</small>
                        </td>
                        <td>
                            @if(empty(trim($order->customer_name ?? '')))
                                {{ __('app.front.walk_in') }}
                            @else
                                {{ $order->customer_name }}
                            @endif
                        </td>
                        <td>{{ __('app.front.' . $order->service_type) }}</td>
                        <td>{{ number_format($order->total, 2) }}</td>
                        <td>
                            <select class="form-select form-select-sm status-select" data-order-id="{{ $order->id }}" style="min-width: 120px;">
                                @foreach (['processing','ready','collected'] as $status)
                                    <option value="{{ $status }}" @selected($order->status === $status) data-color-class="{{ [
                                        'processing' => 'text-info',
                                        'ready' => 'text-success',
                                        'collected' => 'text-secondary',
                                    ][$status] ?? 'text-secondary' }}">
                                        {{ __('app.orders.show.statuses.' . $status) }}
                                    </option>
                                @endforeach
                            </select>
                        </td>
                        <td>
                            <div class="form-check form-switch d-inline-block">
                                <input class="form-check-input payment-switch {{ $order->payment_status === 'paid' ? 'bg-success' : 'bg-danger' }}" 
                                       type="checkbox" 
                                       role="switch" 
                                       data-order-id="{{ $order->id }}"
                                       {{ $order->payment_status === 'paid' ? 'checked' : '' }}
                                       style="width: 3rem; height: 1.5rem;">
                            </div>
                        </td>
                        <td class="text-end">
                            <a href="{{ route('admin.orders.show', $order) }}" class="btn btn-sm btn-outline-primary">{{ __('app.orders.manage') }}</a>
                        </td>
                    </tr>
                @empty
                    <tr>
                        <td colspan="7" class="text-center text-muted py-5">{{ __('app.orders.none') }}</td>
                    </tr>
                @endforelse
            </tbody>
        </table>
    </div>

{{ $orders->links() }}
@endsection

@push('styles')
    <style>
        .barcode-input-group {
            border: 1px solid #ced4da;
            border-radius: 999px;
            overflow: hidden;
            background-color: #fff;
        }

        .barcode-input-group .form-control,
        .barcode-input-group .btn {
            border: none;
            box-shadow: none;
        }

        .barcode-input-group .form-control:focus,
        .barcode-input-group .btn:focus {
            box-shadow: none;
        }

        .barcode-input-group .barcode-scan-btn {
            border-left: 1px solid #e2e6ea;
        }
    </style>
@endpush

@push('styles')
    <style>
        .status-select {
            border: 1px solid #ced4da;
            font-size: 0.875rem;
        }
        .status-select:focus {
            border-color: var(--bs-primary);
            box-shadow: 0 0 0 0.2rem rgba(var(--bs-primary-rgb), 0.25);
        }
        .status-select option[value="processing"] {
            color: var(--bs-info);
        }
        .status-select option[value="ready"] {
            color: var(--bs-success);
        }
        .status-select option[value="collected"] {
            color: var(--bs-secondary);
        }
        
        /* Payment switch styling */
        .payment-switch {
            cursor: pointer;
            transition: background-color 0.3s ease;
        }
        .payment-switch:checked {
            background-color: var(--bs-success) !important;
            border-color: var(--bs-success) !important;
        }
        .payment-switch:not(:checked) {
            background-color: var(--bs-danger) !important;
            border-color: var(--bs-danger) !important;
        }
        .payment-switch:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
    </style>
@endpush

@push('scripts')
    <script>
        const barcodeInput = document.getElementById('barcodeSearch');
        document.getElementById('barcodeLookupBtn').addEventListener('click', async () => {
            if (!barcodeInput.value.trim()) {
                return;
            }

            try {
                const response = await fetch("{{ route('service-orders.lookup') }}", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'X-CSRF-TOKEN': '{{ csrf_token() }}',
                    },
                    body: JSON.stringify({ barcode: barcodeInput.value.trim() }),
                });

                if (!response.ok) {
                    throw new Error('Order not found');
                }

                const data = await response.json();
                window.location.href = "{{ url('admin/orders') }}/" + data.order.id;
            } catch (error) {
                alert(error.message);
            } finally {
                barcodeInput.value = '';
            }
        });

        // Handle status change
        document.querySelectorAll('.status-select').forEach(select => {
            // Store original value on load
            if (!select.getAttribute('data-original-value')) {
                select.setAttribute('data-original-value', select.value);
            }

            select.addEventListener('change', async function() {
                const orderId = this.dataset.orderId;
                const newStatus = this.value;
                const originalValue = this.getAttribute('data-original-value');

                // Disable select during request
                this.disabled = true;
                const originalBg = this.style.backgroundColor;
                this.style.backgroundColor = '#f8f9fa';

                try {
                    const response = await fetch(`/admin/orders/${orderId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                            'Accept': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest',
                        },
                        body: JSON.stringify({ status: newStatus }),
                    });

                    const data = await response.json();

                    if (!response.ok) {
                        throw new Error(data.message || 'Failed to update status');
                    }

                    // Update original value
                    this.setAttribute('data-original-value', newStatus);
                    
                    // Show success feedback
                    const row = this.closest('tr');
                    row.style.transition = 'background-color 0.3s';
                    row.style.backgroundColor = '#d4edda';
                    setTimeout(() => {
                        row.style.backgroundColor = '';
                    }, 1000);

                } catch (error) {
                    // Revert to original value
                    this.value = originalValue;
                    alert(error.message || 'حدث خطأ أثناء تحديث الحالة');
                } finally {
                    this.disabled = false;
                    this.style.backgroundColor = originalBg;
                }
            });
        });

        // Handle payment status change
        document.querySelectorAll('.payment-switch').forEach(switchEl => {
            switchEl.addEventListener('change', async function() {
                const orderId = this.dataset.orderId;
                const isPaid = this.checked;
                const originalState = !isPaid; // Store original state before change

                // Disable switch during request
                this.disabled = true;

                try {
                    const response = await fetch(`/admin/orders/${orderId}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json',
                            'X-CSRF-TOKEN': '{{ csrf_token() }}',
                            'Accept': 'application/json',
                            'X-Requested-With': 'XMLHttpRequest',
                        },
                        body: JSON.stringify({ 
                            payment_status: isPaid ? 'paid' : 'unpaid',
                            mark_paid: isPaid 
                        }),
                    });

                    const data = await response.json();

                    if (!response.ok) {
                        throw new Error(data.message || 'Failed to update payment status');
                    }

                    // Update switch color class
                    this.classList.remove('bg-success', 'bg-danger');
                    this.classList.add(isPaid ? 'bg-success' : 'bg-danger');
                    
                    // Show success feedback
                    const row = this.closest('tr');
                    row.style.transition = 'background-color 0.3s';
                    row.style.backgroundColor = isPaid ? '#d1e7dd' : '#f8d7da';
                    setTimeout(() => {
                        row.style.backgroundColor = '';
                    }, 1000);

                } catch (error) {
                    // Revert to original state
                    this.checked = originalState;
                    this.classList.remove('bg-success', 'bg-danger');
                    this.classList.add(originalState ? 'bg-success' : 'bg-danger');
                    alert(error.message || 'حدث خطأ أثناء تحديث حالة الدفع');
                } finally {
                    this.disabled = false;
                }
            });
        });
    </script>
@endpush

