@extends('layouts.admin')

@section('content')
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="card">
                <div class="card-header">
                    <h4 class="card-title">Orders Management</h4>
                    <div class="d-flex gap-2 flex-wrap">
                        <div class="search-box">
                            <input type="text" id="searchInput" class="form-control" placeholder="Search orders..." value="{{ request('search') }}">
                        </div>
                        <div class="date-filters d-flex gap-2">
                            <input type="date" class="form-control" id="dateFrom" value="{{ request('date_from') }}">
                            <input type="date" class="form-control" id="dateTo" value="{{ request('date_to') }}">
                        </div>
                        <button class="btn btn-primary" id="exportOrders">Export</button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered table-hover">
                            <thead class="table-light">
                                <tr>
                                    <th>Order #</th>
                                    <th>Customer</th>
                                    <th>Total</th>
                                    <th>Status</th>
                                    <th>Payment</th>
                                    <th>Date</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($orders as $order)
                                <tr>
                                    <td>{{ $order->order_number }}</td>
                                    <td>
                                        {{ $order->shipping_name }}<br>
                                        <small>{{ $order->shipping_email }}</small>
                                    </td>
                                    <td>₦{{ $order->formatted_total }}</td>
                                    <td>{!! $order->status_badge !!}</td>
                                    <td>{!! $order->payment_status_badge !!}</td>
                                    <td>{{ $order->created_at->format('M d, Y') }}</td>
                                    <td>
                                        <div class="btn-group">
                                            <a href="{{ route('admin.orders.show', $order) }}" 
                                               class="btn btn-sm btn-info">View</a>
                                            <button type="button" 
                                                    class="btn btn-sm btn-primary update-status" 
                                                    data-order-id="{{ $order->id }}">
                                                Update Status
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                @endforeach
                            </tbody>
                        </table>
                    </div>
                    <div class="mt-4">
                        <nav aria-label="Page navigation">
                            <ul class="pagination pagination-sm justify-content-center">
                                @if ($orders->onFirstPage())
                                    <li class="page-item disabled">
                                        <span class="page-link">&laquo; Previous</span>
                                    </li>
                                @else
                                    <li class="page-item">
                                        <a class="page-link" href="{{ $orders->previousPageUrl() }}" rel="prev">&laquo; Previous</a>
                                    </li>
                                @endif

                                <li class="page-item disabled">
                                    <span class="page-link">Page {{ $orders->currentPage() }} of {{ $orders->lastPage() }}</span>
                                </li>

                                @if ($orders->hasMorePages())
                                    <li class="page-item">
                                        <a class="page-link" href="{{ $orders->nextPageUrl() }}" rel="next">Next &raquo;</a>
                                    </li>
                                @else
                                    <li class="page-item disabled">
                                        <span class="page-link">Next &raquo;</span>
                                    </li>
                                @endif
                            </ul>
                        </nav>
                    </div>
                     {{-- <div class="mt-4">
                        <div class="d-flex justify-content-center pagination-container">
                            {{ $orders->appends(request()->query())->links('pagination::bootstrap-5') }}
                        </div>
                    </div> --}}
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Status Update Modal -->
<div class="modal fade" id="updateStatusModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Update Order Status</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="updateStatusForm">
                    <div class="mb-3">
                        <label class="form-label">Order Status</label>
                        <select class="form-select" name="order_status" id="orderStatus">
                            @foreach(App\Models\Order::getStatusList() as $key => $value)
                            <option value="{{ $key }}">{{ $value }}</option>
                            @endforeach
                        </select>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">Payment Status</label>
                        <select class="form-select" name="payment_status" id="paymentStatus">
                            @foreach(App\Models\Order::getPaymentStatusList() as $key => $value)
                            <option value="{{ $key }}">{{ $value }}</option>
                            @endforeach
                        </select>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary" id="saveStatus">Save changes</button>
            </div>
        </div>
    </div>
</div>
<style>
    /* Hide any other pagination elements that might be coming from elsewhere */
    .pagination:not(.pagination-sm) {
        display: none !important;
    }
    
    /* Style our custom pagination */
    .pagination-sm .page-link {
        padding: 0.25rem 0.5rem;
        font-size: 0.875rem;
    }
</style>
@endsection
@push('styles')

@endpush
@push('scripts')
<script>
document.addEventListener('DOMContentLoaded', function() {
    let currentOrderId;
    let statusModal;

    // Initialize the modal
    statusModal = new bootstrap.Modal(document.getElementById('updateStatusModal'));

    // Update status modal handling
    document.querySelectorAll('.update-status').forEach(button => {
        button.addEventListener('click', function() {
            currentOrderId = this.dataset.orderId;
            statusModal.show();
        });
    });

    document.getElementById('saveStatus').addEventListener('click', function() {
        const saveButton = this;
        const orderStatus = document.getElementById('orderStatus').value;
        const paymentStatus = document.getElementById('paymentStatus').value;
        
        // Show loading state
        saveButton.disabled = true;
        saveButton.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Saving...';

        fetch(`/admin/orders/${currentOrderId}/status`, {
            method: 'PATCH',
            headers: {
                'Content-Type': 'application/json',
                'Accept': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                order_status: orderStatus,
                payment_status: paymentStatus
            })
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('Network response was not ok');
            }
            return response.json();
        })
        .then(data => {
            if(data.success) {
                // Show success message
                showToast('Success', 'Order status updated successfully!', 'success');
                
                // Reload page after 1 second
                setTimeout(() => {
                    window.location.reload();
                }, 1000);
            } else {
                throw new Error(data.message || 'Failed to update status');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            showToast('Error', error.message || 'An error occurred. Please try again.', 'danger');
            
            // Reset button state
            saveButton.disabled = false;
            saveButton.innerHTML = 'Save changes';
        });
    });

    // Search and filter functionality
    let searchTimeout;
    const searchInput = document.getElementById('searchInput');
    if (searchInput) {
        searchInput.addEventListener('keyup', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(filterOrders, 500);
        });
    }

    const dateFrom = document.getElementById('dateFrom');
    const dateTo = document.getElementById('dateTo');
    if (dateFrom) dateFrom.addEventListener('change', filterOrders);
    if (dateTo) dateTo.addEventListener('change', filterOrders);

    function filterOrders() {
        const search = searchInput ? searchInput.value : '';
        const fromDate = dateFrom ? dateFrom.value : '';
        const toDate = dateTo ? dateTo.value : '';

        const params = new URLSearchParams({
            search: search,
            date_from: fromDate,
            date_to: toDate
        });

        window.location.href = `{{ route('admin.orders.index') }}?${params.toString()}`;
    }

    // Export functionality
    const exportButton = document.getElementById('exportOrders');
    if (exportButton) {
        exportButton.addEventListener('click', function() {
            const search = searchInput ? searchInput.value : '';
            const fromDate = dateFrom ? dateFrom.value : '';
            const toDate = dateTo ? dateTo.value : '';

            const params = new URLSearchParams({
                search: search,
                date_from: fromDate,
                date_to: toDate,
                export: true
            });

            window.location.href = `{{ route('admin.orders.export') }}?${params.toString()}`;
        });
    }

    // Helper function to show toast notifications
    function showToast(title, message, type = 'success') {
        const toast = document.createElement('div');
        toast.className = 'position-fixed bottom-0 end-0 p-3';
        toast.style.zIndex = '5';
        toast.innerHTML = `
            <div class="toast show" role="alert" aria-live="assertive" aria-atomic="true">
                <div class="toast-header bg-${type} text-white">
                    <strong class="me-auto">${title}</strong>
                    <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
                </div>
                <div class="toast-body">
                    ${message}
                </div>
            </div>
        `;
        document.body.appendChild(toast);
        
        // Auto-remove after 5 seconds
        setTimeout(() => {
            toast.remove();
        }, 5000);
    }
});
</script>
@endpush