@extends('frontEnd.layouts.master')
@section('title','My Orders')

@push('css')
@include('frontEnd.layouts.customer.partials.cp-styles')
@endpush

@section('content')
<div class="cp-wrap">

    {{-- Breadcrumb --}}
    <div class="cp-nav">
        <a href="{{ route('home') }}"><i class="fa-solid fa-house"></i> Home</a>
        <span>/</span>
        <a href="{{ route('customer.account') }}">Your Account</a>
        <span>/</span>
        <strong>Your Orders</strong>
    </div>

    {{-- Tabs --}}
    <div class="cp-tabs">
        <a href="{{ route('customer.account') }}" class="cp-tab"><i class="fa-solid fa-gauge-high"></i> Dashboard</a>
        <a href="{{ route('customer.orders') }}" class="cp-tab active"><i class="fa-solid fa-box"></i> Your Orders</a>
        <a href="{{ route('customer.order_track') }}" class="cp-tab"><i class="fa-solid fa-location-dot"></i> Track Order</a>
        <a href="{{ route('customer.refunds') }}" class="cp-tab"><i class="fa-solid fa-rotate-left"></i> Refunds</a>
        <a href="{{ route('customer.profile_edit') }}" class="cp-tab"><i class="fa-solid fa-shield-halved"></i> Security</a>
    </div>

    {{-- Orders --}}
    <div class="cp-card">
        <div class="cp-card-head">
            <h3>Order History</h3>
            <span style="font-size:14px;color:#565959;font-weight:500;">{{ $orders->total() }} {{ Str::plural('order', $orders->total()) }}</span>
        </div>

        @forelse($orders as $order)
        @php
            $payment_record = \App\Models\Payment::where('order_id', $order->id)->orderBy('id','desc')->first();
            $gateway_status = $payment_record ? strtolower(trim($payment_record->payment_status)) : '';
            $payment_method = $payment_record ? strtolower(trim($payment_record->payment_method)) : '';
            $admin_status   = strtolower(trim($order->payment_status ?? ''));
            $order_status   = strtolower(trim($order->status->slug ?? $order->status->name ?? ''));
            $grand_total    = $order->amount;
            $paid_amount    = 0;
            if ($payment_record && !in_array($gateway_status, ['failed','cancel','cancelled','rejected'])) {
                $paid_amount = $payment_record->amount;
            }
            $is_cod = in_array($payment_method, ['cod','cash','cash_on_delivery']);
            $is_completed = in_array($order_status, ['completed','delivered']) || in_array($admin_status, ['completed','delivered']);
            if ($is_cod && !$is_completed && $paid_amount >= $grand_total) $paid_amount = 0;
            if ($is_completed) $paid_amount = $grand_total;
            elseif ($paid_amount == 0 && in_array($admin_status, ['paid','success','approved'])) $paid_amount = $grand_total;
            $due_amount  = max(0, $grand_total - $paid_amount);
            $is_failed   = ($paid_amount == 0 && in_array($gateway_status, ['failed','cancel','cancelled']));
            $show_dl     = ($paid_amount >= $grand_total) || ($paid_amount > 0 && !$is_failed);
            $digitalDLs  = \App\Models\DigitalDownload::where('order_id', $order->id)->get();
            $existingRefund = \App\Models\Refund::where('order_id', $order->id)->whereIn('status',['pending','approved'])->first();
            $canRefund   = ($order->order_status != 11 && $paid_amount > 0 && !$existingRefund);
            $os = (int)$order->order_status;
            $bt = $order->status->name ?? 'Processing';
            if ($os==6)                    { $bc='badge-delivered'; }
            elseif ($os==11)               { $bc='badge-cancelled'; }
            elseif (in_array($os,[3,4,5])) { $bc='badge-shipped';   }
            else                           { $bc='badge-processing'; }
        @endphp

        <div style="padding:22px; border-top:1px solid #f0f2f2;">
            {{-- Top row --}}
            <div style="display:flex; justify-content:space-between; align-items:flex-start; gap:12px; flex-wrap:wrap; margin-bottom:15px;">
                <div>
                    <div style="display:flex; align-items:center; gap:10px; margin-bottom:6px;">
                        <strong style="color:var(--amz-navy); font-size:16px;">#{{ $order->invoice_id }}</strong>
                        <span class="{{ $bc }}">{{ $bt }}</span>
                        @if($is_cod && !$is_completed)
                            <span class="badge-cod">COD</span>
                        @elseif($paid_amount >= $grand_total)
                            <span class="badge-paid">Paid</span>
                        @elseif($is_failed)
                            <span class="badge-unpaid">Failed</span>
                        @elseif($paid_amount > 0)
                            <span class="badge-partial">Partial</span>
                        @else
                            <span class="badge-unpaid">Unpaid</span>
                        @endif
                    </div>
                    <div style="font-size:13px; color:#565959;">Ordered on {{ $order->created_at->format('d M Y, h:i A') }}</div>
                </div>
                <div style="text-align:right;">
                    <div style="font-size:18px; font-weight:800; color:var(--amz-price);">৳{{ number_format($grand_total, 0) }}</div>
                    @if($due_amount > 0)
                        <div style="font-size:12px; color:#b12704; font-weight:600;">Due: ৳{{ number_format($due_amount, 0) }}</div>
                    @endif
                </div>
            </div>

            {{-- Product thumbnails --}}
            @if($order->orderdetails && $order->orderdetails->count())
            <div style="display:flex; gap:10px; margin-bottom:18px; flex-wrap:wrap;">
                @foreach($order->orderdetails->take(8) as $detail)
                @php
                    $img = $detail->product?->image?->image ?? $detail->image?->image ?? null;
                @endphp
                <img src="{{ $img ? asset($img) : asset('public/uploads/default/no-image.png') }}"
                     onerror="this.src='{{ asset('uploads/default/no-image.png') }}'"
                     style="width:54px;height:54px;border-radius:4px;object-fit:cover;border:1px solid var(--amz-border); background:#fff;"
                     title="{{ $detail->product_name }}">
                @endforeach
                @if($order->orderdetails->count() > 8)
                    <div style="width:54px;height:54px;border-radius:4px;background:var(--amz-gray-bg);display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;color:#565959;border:1px solid var(--amz-border);">
                        +{{ $order->orderdetails->count() - 8 }}
                    </div>
                @endif
            </div>
            @endif

            {{-- Actions --}}
            <div style="display:flex; gap:10px; flex-wrap:wrap;">
                <a href="{{ route('customer.invoice', ['id'=>$order->id]) }}" class="cp-btn cp-btn-blue">
                    Details
                </a>
                @if($order->admin_note)
                    <a href="{{ route('customer.order_note', ['id'=>$order->id]) }}" class="cp-btn cp-btn-blue">
                        Order Note
                    </a>
                @endif
                @if($digitalDLs->count() && $show_dl)
                    @foreach($digitalDLs as $dl)
                        <a href="{{ route('digital.download', $dl->token) }}" class="cp-btn cp-btn-primary" target="_blank">
                            <i class="fa-solid fa-download"></i> Download
                        </a>
                    @endforeach
                @endif
                @if($canRefund)
                    <a href="{{ route('customer.refunds.create', $order->id) }}" class="cp-btn cp-btn-red">
                        Request Refund
                    </a>
                @elseif($existingRefund)
                    <a href="{{ route('customer.refunds.show', $existingRefund->id) }}" class="cp-btn cp-btn-red">
                        Refund Status
                    </a>
                @endif
            </div>
        </div>

        @empty
        <div class="cp-empty">
            <i class="fa-solid fa-box-open"></i>
            <h5>You haven't placed any orders yet.</h5>
            <p>Check out our latest products and start shopping today!</p>
            <a href="{{ route('home') }}" class="cp-btn cp-btn-primary" style="margin-top:20px; padding:12px 30px; border-radius:50px;">Start Shopping</a>
        </div>
        @endforelse

        {{-- Pagination --}}
        @if($orders->hasPages())
        <div class="cp-pagination">
            <a href="{{ $orders->previousPageUrl() ?? '#' }}" class="cp-page-btn {{ $orders->onFirstPage() ? 'disabled' : '' }}">
                Previous
            </a>
            @for($p = max(1,$orders->currentPage()-2); $p <= min($orders->lastPage(),$orders->currentPage()+2); $p++)
                <a href="{{ $orders->url($p) }}" class="cp-page-btn {{ $p == $orders->currentPage() ? 'active' : '' }}">{{ $p }}</a>
            @endfor
            <a href="{{ $orders->nextPageUrl() ?? '#' }}" class="cp-page-btn {{ !$orders->hasMorePages() ? 'disabled' : '' }}">
                Next
            </a>
        </div>
        @endif
    </div>

</div>
@endsection
