@extends('admin.layout.dashboard_master')

@section('content')
    <main id="main" class="main">

        <div class="pagetitle">
            <h1>Pending Orders</h1>
            <nav>
                <ol class="breadcrumb">
                    <li class="breadcrumb-item"><a href="{{ route('american.plastic.admin.dashboard') }}">American Plastic</a></li>
                    <li class="breadcrumb-item">Dashboard</li>
                    <li class="breadcrumb-item active">Pending Orders</li>
                </ol>
            </nav>
        </div><!-- End Page Title -->

        <section class="section">
            <div class="row">
                <div class="col-lg-12">
                    <div class="card">
                        <div class="card-body pt-3">
                            <!-- Add this filter section before your table -->
                            <div class="row mb-4 align-items-end gx-3">
                                <div class="col-md-3">
                                    <label for="startDate" class="form-label small fw-bold">From Date:</label>
                                    <div class="input-group input-group-sm">
                                        <span class="input-group-text bg-white"><i class="bi bi-calendar-event"></i></span>
                                        <input type="date" class="form-control" id="startDate">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <label for="endDate" class="form-label small fw-bold">To Date:</label>
                                    <div class="input-group input-group-sm">
                                        <span class="input-group-text bg-white"><i class="bi bi-calendar-check"></i></span>
                                        <input type="date" class="form-control" id="endDate">
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <label for="payment_method_filter" class="form-label small fw-bold">Payment Method:</label>
                                    <select class="form-select form-select-sm" id="payment_method_filter">
                                        <option value="">All Methods</option>
                                        <option value="koko">Koko</option>
                                        <option value="visa">Visa</option>
                                        <option value="cod">COD</option>
                                        <option value="mintpay">Mintpay</option>
                                    </select>
                                </div>
                                <div class="col-md-3">
                                    <label for="status_filter" class="form-label small fw-bold">Status:</label>
                                    <select class="form-select form-select-sm" id="status_filter">
                                        <option value="">All Statuses</option>
                                        <option value="pending">Pending</option>
                                        <option value="completed">Completed</option>
                                        <option value="failed">Failed</option>
                                    </select>
                                </div>
                            </div>
                            <div class="row mb-4">
                                <div class="col-md-3">
                                    <button class="btn btn-light btn-sm w-100 border text-muted" id="reset_filters">
                                        <i class="bi bi-arrow-repeat me-1"></i> Reset Filters
                                    </button>
                                </div>
                            </div>

                            <div class="table-responsive text-nowrap">
                                <table class="table" id="pending_order_table" style="width:100%;">
                                    <thead>
                                        <tr>
                                            <th>ID</th>
                                            <th>Order Number</th>
                                            <th>Customer Name</th>
                                            <th>Customer Email</th>
                                            <th>Total</th>
                                            <th>Payment Method</th>
                                            <th>Status</th>
                                            <th>Created At</th>
                                            <th>Actions</th>
                                        </tr>
                                    </thead>
                                    <tbody></tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Details Modal -->
            <div class="modal fade" id="pending_order_details_modal" tabindex="-1" aria-labelledby="modalLabel" aria-hidden="true">
                <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                        <div class="modal-header">
                            <h5 class="modal-title" id="modalLabel">Pending Order Details - <span id="modal_order_id"></span></h5>
                            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                        </div>
                        <div class="modal-body">
                            <div class="row">
                                <!-- Order Summary -->
                                <div class="col-md-6 mb-3">
                                    <div class="card border shadow-none h-100">
                                        <div class="card-header bg-light">
                                            <h6 class="mb-0 fw-bold text-secondary">Order Summary</h6>
                                        </div>
                                        <div class="card-body pt-3">
                                            <p class="mb-2"><strong>Order ID:</strong> <span id="summary_order_id"></span></p>
                                            <p class="mb-2"><strong>Payment Method:</strong> <span id="summary_payment_method" class="text-uppercase"></span></p>
                                            <p class="mb-2"><strong>Status:</strong> <span id="summary_status"></span></p>
                                            <p class="mb-2"><strong>Created At:</strong> <span id="summary_created_at"></span></p>
                                            <p class="mb-0"><strong>Total Amount:</strong> <span id="summary_total" class="text-primary fw-bold"></span></p>
                                        </div>
                                    </div>
                                </div>

                                <!-- Customer Details -->
                                <div class="col-md-6 mb-3">
                                    <div class="card border shadow-none h-100">
                                        <div class="card-header bg-light">
                                            <h6 class="mb-0 fw-bold text-secondary">Customer Information</h6>
                                        </div>
                                        <div class="card-body pt-3">
                                            <p class="mb-2"><strong>Name:</strong> <span id="customer_name"></span></p>
                                            <p class="mb-2"><strong>Email:</strong> <span id="customer_email"></span></p>
                                            <p class="mb-2"><strong>Phone:</strong> <span id="customer_phone"></span></p>
                                            <p class="mb-2"><strong>Address:</strong> <span id="customer_address"></span></p>
                                            <p class="mb-0"><strong>City/Zip:</strong> <span id="customer_city_zip"></span></p>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <!-- Products -->
                            <div class="card border shadow-none mb-3">
                                <div class="card-header bg-light">
                                    <h6 class="mb-0 fw-bold text-secondary">Items in Cart</h6>
                                </div>
                                <div class="card-body pt-3">
                                    <div class="table-responsive">
                                        <table class="table table-bordered mb-0" id="products_table">
                                            <thead>
                                                <tr>
                                                    <th>Product Name</th>
                                                    <th>SKU</th>
                                                    <th>Color</th>
                                                    <th>Quantity</th>
                                                </tr>
                                            </thead>
                                            <tbody></tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>

                            <!-- Raw Payload accordion -->
                            <div class="accordion" id="payloadAccordion">
                                <div class="accordion-item border">
                                    <h2 class="accordion-header" id="headingPayload">
                                        <button class="accordion-button collapsed py-2 bg-light text-secondary" type="button" data-bs-toggle="collapse" data-bs-target="#collapsePayload" aria-expanded="false" aria-controls="collapsePayload">
                                            <strong>View Raw JSON Payload</strong>
                                        </button>
                                    </h2>
                                    <div id="collapsePayload" class="accordion-collapse collapse" aria-labelledby="headingPayload" data-bs-parent="#payloadAccordion">
                                        <div class="accordion-body p-0">
                                            <pre class="bg-dark text-white p-3 mb-0" style="max-height: 250px; overflow-y: auto; font-size: 0.85rem;"><code id="raw_payload_json"></code></pre>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                        </div>
                    </div>
                </div>
            </div>
        </section>

        <script>
        $(document).ready(function() {
            var table = $('#pending_order_table').DataTable({
                processing: true,
                serverSide: true,
                ajax: {
                    url: "{{ route('american.plastic.admin.pending.orders.get') }}",
                    data: function(d) {
                        d.payment_method = $('#payment_method_filter').val();
                        d.status = $('#status_filter').val();
                        d.startDate = $('#startDate').val();
                        d.endDate = $('#endDate').val();
                    }
                },
                columns: [
                    { data: 'id', name: 'id' },
                    { data: 'order_id', name: 'order_id' },
                    { data: 'customer_name', name: 'customer_name', orderable: false, searchable: false },
                    { data: 'customer_email', name: 'customer_email', orderable: false, searchable: false },
                    { data: 'total_amount', name: 'total_amount', orderable: false, searchable: false },
                    { data: 'payment_method', name: 'payment_method' },
                    { data: 'status', name: 'status' },
                    { data: 'created_at', name: 'created_at' },
                    { data: 'action', name: 'action', orderable: false, searchable: false }
                ],
                order: [[0, 'desc']]
            });

            // Filters trigger reload
            $('#payment_method_filter, #status_filter, #startDate, #endDate').on('change', function() {
                table.ajax.reload();
            });

            // Reset filters
            $('#reset_filters').on('click', function() {
                $('#payment_method_filter').val('');
                $('#status_filter').val('');
                $('#startDate').val('');
                $('#endDate').val('');
                table.ajax.reload();
            });

            // View Details click handler
            $(document).on('click', '.view-pending-details', function() {
                var id = $(this).data('id');
                $.ajax({
                    url: "{{ route('admin.order.pending.details') }}",
                    type: 'GET',
                    data: { id: id },
                    success: function(response) {
                        var pendingOrder = response.pending_order;
                        var payload = pendingOrder.payload || {};

                        // Modal headers
                        $('#modal_order_id').text(pendingOrder.order_id);
                        $('#summary_order_id').text(pendingOrder.order_id);
                        $('#summary_payment_method').text(pendingOrder.payment_method);
                        
                        // Status badge logic
                        var statusHtml = '';
                        if (pendingOrder.status === 'completed') {
                            statusHtml = '<span class="badge bg-success">Completed</span>';
                        } else if (pendingOrder.status === 'failed') {
                            statusHtml = '<span class="badge bg-danger">Failed</span>';
                        } else {
                            statusHtml = '<span class="badge bg-warning text-dark">Pending</span>';
                        }
                        $('#summary_status').html(statusHtml);

                        // Format created_at date
                        var dateStr = new Date(pendingOrder.created_at).toLocaleString();
                        $('#summary_created_at').text(dateStr);

                        // Total amount
                        var amount = payload.amount || payload.total || 0;
                        $('#summary_total').text('LKR ' + parseFloat(amount).toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2}));

                        // Customer info
                        var firstName = payload.cus_first_name || payload.first_name || '';
                        var lastName = payload.cus_last_name || payload.last_name || '';
                        $('#customer_name').text($.trim(firstName + ' ' + lastName) || 'N/A');
                        $('#customer_email').text(payload.cus_email || payload.email || 'N/A');
                        $('#customer_phone').text(payload.cus_phone || payload.telephone || 'N/A');
                        
                        var address1 = payload.cus_address_1 || payload.address_1 || '';
                        var address2 = payload.cus_address_2 || payload.address_2 || '';
                        $('#customer_address').text($.trim(address1 + ' ' + address2) || 'N/A');
                        
                        var city = payload.cus_city || payload.city || '';
                        var postcode = payload.cus_postcode || payload.postcode || '';
                        $('#customer_city_zip').text((city ? city + ', ' : '') + (postcode || ''));

                        // Products table
                        var productsTableBody = $('#products_table tbody');
                        productsTableBody.empty();
                        
                        if (response.products && response.products.length > 0) {
                            response.products.forEach(function(item) {
                                productsTableBody.append(
                                    '<tr>' +
                                        '<td>' + item.name + '</td>' +
                                        '<td>' + item.sku + '</td>' +
                                        '<td>' + item.color + '</td>' +
                                        '<td>' + item.quantity + '</td>' +
                                    '</tr>'
                                );
                            });
                        } else {
                            productsTableBody.append('<tr><td colspan="4" class="text-center text-muted">No products found in payload</td></tr>');
                        }

                        // Raw payload code
                        $('#raw_payload_json').text(JSON.stringify(payload, null, 4));

                        // Open modal
                        $('#pending_order_details_modal').modal('show');
                    },
                    error: function() {
                        alert('Error loading pending order details.');
                    }
                });
            });
        });
        </script>
    </main>
@endsection
