@extends('admin.layout.template')
@section('title', 'Order Details')

@section('content')
<div class="page-content">
    <div class="container-xxl">

        <div class="row">
            <!-- LEFT SIDE -->
            <div class="col-xl-9 col-lg-8">

                {{-- ORDER HEADER --}}
                <div class="card">
                    <div class="card-body">
                        <div class="d-flex flex-wrap align-items-center justify-content-between gap-2">
                            <div>
                                <h4 class="fw-medium text-dark d-flex align-items-center gap-2">
                                    #{{ $order->order_number }}

                                    <span class="badge bg-success-subtle text-success px-2 py-1 fs-13">
                                        {{ ucfirst($order->payment_status) }}
                                    </span>

                                    <span class="border border-warning text-warning fs-13 px-2 py-1 rounded">
                                        {{ ucfirst($order->order_status) }}
                                    </span>
                                </h4>

                                <p class="mb-0">
                                    Order / Order Details /
                                    {{ $order->created_at->format('M d, Y h:i a') }}
                                </p>
                            </div>

                            <div>
<a href="{{ route('download-invoice', ['orderid' => $order->id]) }}"
   class="btn btn-outline-secondary">
   Download Invoice
</a>

                                <button type="button" class="btn btn-primary editStatusBtn" data-bs-toggle="modal" data-bs-target="#statusModal">Edit Order</button>
                            </div>
                        </div>
                    </div>
                </div>

                {{-- PRODUCTS --}}
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Products</h4>
                    </div>

                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table align-middle table-hover">
                                <thead class="bg-light-subtle">
                                    <tr>
                                        <th>Product</th>
                                        <th>Status</th>
                                        <th>Qty</th>
                                        <th>Price</th>
                                        <th>Tax</th>
                                        <th>Total</th>
                                    </tr>
                                </thead>

                                <tbody>
                                    @foreach($order->items as $item)
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center gap-2">
                                                <div class="rounded bg-light avatar-md d-flex align-items-center justify-content-center">
                                                    @php
                                                    $image = $item->product?->images->first()?->image;
                                                    @endphp

                                                    <img
                                                        src="{{ $image ? asset('uploads/products/'.$image) : asset('no-image.png') }}"
                                                        class="avatar-md rounded"
                                                        alt="{{ $item->product->name }}">
                                                </div>

                                                <div>
                                                    <p class="mb-0 fw-medium">{{ $item->product->name }}</p>
                                                </div>
                                            </div>
                                        </td>


                                        <td>
                                            <span class="badge bg-success-subtle text-success">
                                                {{ ucfirst($item->status) }}
                                            </span>
                                        </td>

                                        <td>{{ $item->qty }}</td>
                                        <td>₹{{ number_format($item->price,2) }}</td>
                                        <td>₹{{ number_format($item->tax,2) }}</td>
                                        <td>₹{{ number_format($item->total,2) }}</td>
                                    </tr>
                                    @endforeach
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>

                {{-- ORDER TIMELINE --}}
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Order Timeline</h4>
                    </div>

                    <div class="card-body">
                       
                        <div class="position-relative ms-2">
                            <span class="position-absolute start-0 top-0 border border-dashed h-100"></span>

                            @php
                            $lastStatusId = optional($order->statusHistory->last())->id;
                            @endphp

                            @foreach($order->statusHistory as $history)

                            <div class="position-relative ps-4">
                                <div class="mb-4">

                                    {{-- ICON --}}
                                    <span
                                        class="position-absolute start-0 avatar-sm translate-middle-x
d-inline-flex align-items-center justify-content-center rounded-circle
{{ $history->id == $lastStatusId ? 'bg-light' : 'bg-light text-success' }}">

                                        @if($history->id == $lastStatusId)
                                        {{-- CURRENT STATUS (SPINNER) --}}
                                        <div class="spinner-border spinner-border-sm text-warning" role="status">
                                            <span class="visually-hidden">Loading...</span>
                                        </div>
                                        @else
                                        {{-- COMPLETED STATUS --}}
                                        <i class='bx bx-check-circle fs-20'></i>
                                        @endif

                                    </span>

                                    {{-- CONTENT --}}
                                    <div class="ms-2 d-flex flex-wrap gap-2 align-items-center justify-content-between">
                                        <div>
                                            <h5 class="mb-1 text-dark fw-medium fs-15">
                                                {{ ucfirst($history->status) }}
                                            </h5>

                                            @if($history->description)
                                            <p class="mb-0">{{ $history->description }}</p>
                                            @endif
                                        </div>

                                        <p class="mb-0">
                                            {{ \Carbon\Carbon::parse($history->status_date)->format('M d, Y, h:i a') }}
                                        </p>
                                    </div>

                                </div>
                            </div>

                            @endforeach
                        </div>

                      
                    </div>
                </div>

            </div>

            <!-- RIGHT SIDE -->
            <div class="col-xl-3 col-lg-4">

                {{-- ORDER SUMMARY --}}
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Order Summary</h4>
                    </div>

                    <div class="card-body">
                        <table class="table mb-0">
                            <tr>
                                <td>Subtotal</td>
                                <td class="text-end">₹{{ number_format($order->subtotal,2) }}</td>
                            </tr>
                            <tr>
                                <td>Discount</td>
                                <td class="text-end text-danger">
                                    -₹{{ number_format($order->discount,2) }}
                                </td>
                            </tr>
                            <tr>
                                <td>Tax</td>
                                <td class="text-end">₹{{ number_format($order->tax,2) }}</td>
                            </tr>
                            <tr>
                                <td>Delivery</td>
                                <td class="text-end">₹{{ number_format($order->delivery_charge,2) }}</td>
                            </tr>
                        </table>
                    </div>

                    <div class="card-footer d-flex justify-content-between bg-light-subtle">
                        <strong>Total</strong>
                        <strong>₹{{ number_format($order->total,2) }}</strong>
                    </div>
                </div>

                {{-- PAYMENT INFO (FROM ORDERS TABLE) --}}
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Payment Information</h4>
                    </div>

                    <div class="card-body">
                        <p class="mb-1 fw-medium">
                            Payment Method :
                            <span class="text-muted">{{ ucfirst($order->payment_method ?? 'N/A') }}</span>
                        </p>

                        <p class="mb-1 fw-medium">
                            Transaction ID :
                            <span class="text-muted">{{ $order->transaction_id ?? 'N/A' }}</span>
                        </p>

                        <p class="mb-0 fw-medium">
                            Payment Status :
                            <span class="badge bg-success-subtle text-success">
                                {{ ucfirst($order->payment_status) }}
                            </span>
                        </p>
                    </div>
                </div>

                {{-- CUSTOMER DETAILS --}}
                <div class="card">
                    <div class="card-header">
                        <h4 class="card-title">Customer</h4>
                    </div>

                    <div class="card-body">
                        <p class="mb-1 fw-medium">{{ $order->user->name }}</p>
                        <p class="mb-1">{{ $order->user->email }}</p>
                        <p class="mb-1">{{ $order->user->phone }}</p>

                        <hr>

                        <p class="fw-medium mb-1">Shipping Address</p>
                        <p class="mb-0">{{ $order->shipping_address }}</p>
                    </div>
                </div>

            </div>
        </div>

    </div>
</div>

 <div class="modal fade" id="statusModal" 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">
                    <input type="hidden" id="order_id" value="{{ $order->id}}">

                    <div class="mb-3">
                        <label class="form-label">Order Status</label>
                       <select name="order_status" id="order_status" class="form-select" required>
    <option value="processing" {{ $order->order_status == 'processing' ? 'selected' : '' }}>
        Processing
    </option>

    <option value="shipped" {{ $order->order_status == 'shipped' ? 'selected' : '' }}>
        Shipped
    </option>

    <option value="in_transit" {{ $order->order_status == 'in_transit' ? 'selected' : '' }}>
        In Transit
    </option>

    <option value="delivered" {{ $order->order_status == 'delivered' ? 'selected' : '' }}>
        Delivered
    </option>

    <option value="cancelled" {{ $order->order_status == 'cancelled' ? 'selected' : '' }}>
        Cancelled
    </option>

    <option value="refund" {{ $order->order_status == 'refund' ? 'selected' : '' }}>
        Refund
    </option>
</select>

                    </div>

                    <div class="mb-3">
                        <label class="form-label">Status Description</label>
                        <textarea id="status_description" class="form-control" required rows="3"
                            placeholder="Optional message shown to customer">
                    </textarea>
                    </div>
                </div>

                <div class="modal-footer">
                    <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                    <button class="btn btn-primary" id="saveStatus">Save</button>
                </div>

            </div>
        </div>
    </div>
<script>
    
// $(document).on('click', '.editStatusBtn', function () {

//     let orderId = $(this).data('id');
//     let status  = $(this).data('status');

//     $('#order_id').val(orderId);
//     $('#order_status').val(status);
//     $('#status_description').val('');

//     let modal = new bootstrap.Modal(document.getElementById('statusModal'));
//     modal.show();
// });


$('#saveStatus').on('click', function () {

    Swal.fire({
        title: 'Confirm Update',
        text: 'Do you want to update order status?',
        icon: 'warning',
        showCancelButton: true,
        confirmButtonText: 'Yes, Update',
        cancelButtonText: 'Cancel'
    }).then((result) => {

        if (!result.isConfirmed) return;

        let orderId     = $('#order_id').val();
        let status      = $('#order_status').val();
        let description = $('#status_description').val();

        fetch("{{ route('updateStatus') }}", {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': '{{ csrf_token() }}'
            },
            body: JSON.stringify({
                id: orderId,
                order_status: status,
                description: description
            })
        })
        .then(res => res.json())
        .then(data => {
            Swal.fire({
                icon: data.success ? 'success' : 'error',
                title: data.success ? 'Updated!' : 'Failed',
                text: data.message ?? 'Operation completed'
            }).then(() => {
                if (data.success) location.reload();
            });
        })
        .catch(() => {
            Swal.fire('Error', 'Server error occurred', 'error');
        });

    });
});

</script>
@endsection