@extends('layouts.main') {{-- Asumsi layout user --}}

@section('title', 'Detail Order #' . $order->id)

@section('content')
<div class="min-h-screen py-6 sm:py-8">
    <div class="w-full max-w-[1200px] mx-auto px-3 sm:px-4">
        <!-- Header -->
        <div class="mb-6 sm:mb-8">
            <div class="flex flex-col md:flex-row md:justify-between md:items-center gap-4">
                <div>
                    <h1 class="text-2xl sm:text-3xl font-bold text-gray-900">Detail Pesanan</h1>
                    <p class="mt-1 text-sm sm:text-base text-gray-600">Order ID: #{{ $order->id }}</p>
                    <p class="text-xs sm:text-sm text-gray-500 mt-1">{{ $order->created_at->format('d M Y, H:i') }}</p>
                </div>
                <div class="flex gap-2 sm:gap-3">
                    <a href="{{ route('my.orders.index') }}"
                        class="inline-flex items-center px-3 sm:px-4 py-2 text-sm text-blue-600 hover:text-blue-800 font-medium">
                        <svg class="h-4 w-4 mr-2" fill="currentColor" viewBox="0 0 20 20">
                            <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
                        </svg>
                        Kembali
                    </a>
                </div>
            </div>
        </div>

        <!-- Production Tracking Timeline -->
        @if($order->production)
            @php $production = $order->production; @endphp
            <div class="mb-6">
                @include('shared.partials.production-timeline', ['production' => $production, 'showEstimate' => true])

                <!-- Info Tambahan (Pending Approval Alert) -->
                @php
                    $hasPendingApproval = $order->production->planning_status === 'pending_approval' || $order->production->completion_status === 'pending_approval';
                    $planningPendingTooLong = false;
                    $completionPendingTooLong = false;
                    
                    if ($order->production->planning_status === 'pending_approval' && $order->production->submitted_at) {
                        $daysPending = now()->diffInDays($order->production->submitted_at);
                        $planningPendingTooLong = $daysPending > 3;
                    }
                    
                    if ($order->production->completion_status === 'pending_approval' && $order->production->completed_at) {
                        $daysPending = now()->diffInDays($order->production->completed_at);
                        $completionPendingTooLong = $daysPending > 2;
                    }
                @endphp
                
                @if($hasPendingApproval)
                <div class="mt-4 sm:mt-6 p-4 sm:p-5 {{ $planningPendingTooLong || $completionPendingTooLong ? 'bg-orange-50 border-l-4 border-orange-500' : 'bg-yellow-50 border-l-4 border-yellow-500' }} rounded-lg border border-gray-200">
                    <div class="flex items-start">
                        <div class="flex-shrink-0">
                            <svg class="w-5 h-5 sm:w-6 sm:h-6 {{ $planningPendingTooLong || $completionPendingTooLong ? 'text-orange-600' : 'text-yellow-600' }}" fill="currentColor" viewBox="0 0 20 20">
                                @if($planningPendingTooLong || $completionPendingTooLong)
                                    <path fill-rule="evenodd" d="M8.257 3.099c.765-1.36 2.722-1.36 3.486 0l5.58 9.92c.75 1.334-.213 2.98-1.742 2.98H4.42c-1.53 0-2.493-1.646-1.743-2.98l5.58-9.92zM11 13a1 1 0 11-2 0 1 1 0 012 0zm-1-8a1 1 0 00-1 1v3a1 1 0 002 0V6a1 1 0 00-1-1z" clip-rule="evenodd" />
                                @else
                                    <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
                                @endif
                            </svg>
                        </div>
                        <div class="ml-3 flex-1">
                            <h3 class="text-xs sm:text-sm font-semibold {{ $planningPendingTooLong || $completionPendingTooLong ? 'text-orange-900' : 'text-yellow-900' }}">
                                @if($planningPendingTooLong || $completionPendingTooLong)
                                    Menunggu Persetujuan (Lebih Lama dari Biasa)
                                @else
                                    Menunggu Persetujuan
                                @endif
                            </h3>
                            <p class="text-xs sm:text-sm {{ $planningPendingTooLong || $completionPendingTooLong ? 'text-orange-800' : 'text-yellow-800' }} mt-1.5 leading-relaxed">
                                @if($order->production->planning_status === 'pending_approval')
                                    @if($planningPendingTooLong)
                                        Planning produksi sudah menunggu persetujuan supervisor selama <strong>{{ now()->diffInDays($order->production->submitted_at) }} hari</strong>. 
                                        @if($order->production->submitted_at)
                                            (Disubmit: {{ $order->production->submitted_at->format('d M Y') }})
                                        @endif
                                        <br><strong class="mt-2 block text-orange-900">Jika sudah lebih dari 3 hari, silakan hubungi customer service untuk follow-up.</strong>
                                    @else
                                        Planning produksi sedang menunggu persetujuan supervisor. 
                                        @if($order->production->submitted_at)
                                            (Disubmit: {{ $order->production->submitted_at->format('d M Y') }})
                                        @endif
                                        Kami akan memproses segera setelah disetujui.
                                    @endif
                                @elseif($order->production->completion_status === 'pending_approval')
                                    @if($completionPendingTooLong)
                                        Produksi telah selesai dan menunggu persetujuan final selama <strong>{{ now()->diffInDays($order->production->completed_at) }} hari</strong>.
                                        @if($order->production->completed_at)
                                            (Selesai: {{ $order->production->completed_at->format('d M Y') }})
                                        @endif
                                        <br><strong class="mt-2 block text-orange-900">Jika sudah lebih dari 2 hari, silakan hubungi customer service untuk follow-up.</strong>
                                    @else
                                        Produksi telah selesai dan sedang menunggu persetujuan final dari supervisor.
                                        @if($order->production->completed_at)
                                            (Selesai: {{ $order->production->completed_at->format('d M Y') }})
                                        @endif
                                        Produk akan segera siap setelah disetujui.
                                    @endif
                                @endif
                            </p>
                            @if($planningPendingTooLong || $completionPendingTooLong)
                            <div class="mt-3 sm:mt-4">
                                <a href="{{ route('guest.contact') }}" class="inline-flex items-center px-3 sm:px-4 py-2 bg-orange-600 hover:bg-orange-700 text-white text-xs sm:text-sm font-medium rounded-lg transition-colors">
                                    <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 5.636l-3.536 3.536m0 5.656l3.536 3.536M9.172 9.172L5.636 5.636m3.536 9.192l-3.536 3.536M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-5 0a4 4 0 11-8 0 4 4 0 018 0z"></path>
                                    </svg>
                                    Hubungi Customer Service
                                </a>
                            </div>
                            @endif
                        </div>
                    </div>
                </div>
                @endif
            </div>
        @elseif($order->order_status === 'diterima' && $order->status === 'selesai')
            <!-- Info jika belum ada production tapi order sudah diterima dan pembayaran selesai -->
            <div class="mb-6 bg-white rounded-lg border border-gray-200 overflow-hidden">
                <div class="p-4 sm:p-5 bg-blue-50 border-l-4 border-blue-500">
                    <div class="flex items-start">
                        <div class="flex-shrink-0">
                            <svg class="w-5 h-5 sm:w-6 sm:h-6 text-blue-600" fill="currentColor" viewBox="0 0 20 20">
                                <path fill-rule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clip-rule="evenodd" />
                            </svg>
                        </div>
                        <div class="ml-3 sm:ml-4">
                            <h3 class="text-sm sm:text-base font-semibold text-blue-900">Pembayaran Selesai</h3>
                            <p class="text-xs sm:text-sm text-blue-800 mt-1.5 leading-relaxed">
                                Pembayaran Anda sudah selesai. Pesanan sedang dipersiapkan untuk masuk tahap produksi. 
                                <br><strong>Kami akan segera menghubungi Anda ketika produksi dimulai.</strong>
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        @endif

        <!-- Main Content Grid -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-4 sm:gap-6">
            <!-- Left Column: Order Info & Statuses -->
            <div class="lg:col-span-2 space-y-4 sm:space-y-6">
                <!-- Order Information -->
                <div class="bg-white rounded-lg border border-gray-200 p-4 sm:p-6">
                    <div class="px-4 sm:px-6 py-3 sm:py-4 -mx-4 sm:-mx-6 -mt-4 sm:-mt-6 mb-4 sm:mb-6 border-b border-gray-200 bg-blue-50">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center mr-3">
                                <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path>
                                </svg>
                            </div>
                            <div>
                                <h2 class="text-lg sm:text-xl font-semibold text-gray-900">Informasi Pesanan</h2>
                                <p class="text-xs sm:text-sm text-gray-600">Detail pesanan Anda</p>
                            </div>
                        </div>
                    </div>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="space-y-3">
                            <div class="bg-gray-50 p-3 rounded-lg">
                                <p class="text-xs text-gray-500 mb-1">Produk</p>
                                <p class="text-sm font-medium text-gray-900">{{ $order->product->product_title ?? 'N/A' }}</p>
                            </div>
                            <div class="bg-gray-50 p-3 rounded-lg">
                                <p class="text-xs text-gray-500 mb-1">Quantity</p>
                                <p class="text-sm font-medium text-gray-900 flex items-center">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                                        {{ $order->quantity }} unit
                                    </span>
                                </p>
                            </div>
                        </div>
                        <div class="space-y-3">
                            <div class="bg-gray-50 p-3 rounded-lg">
                                <p class="text-xs text-gray-500 mb-1">Total Harga</p>
                                <p class="text-lg font-bold text-blue-600">{{ $order->formatted_total_price }}</p>
                            </div>
                            <div class="bg-gray-50 p-3 rounded-lg">
                                <p class="text-xs text-gray-500 mb-1">Metode Pembayaran</p>
                                <p class="text-sm font-medium text-gray-900">
                                    <span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium 
                                        {{ $order->payment_method === 'transfer' ? 'bg-blue-100 text-blue-800' : 
                                           ($order->payment_method === 'dp' ? 'bg-orange-100 text-orange-800' : 'bg-gray-100 text-gray-800') }}">
                                        {{ ucfirst($order->payment_method) }}
                                    </span>
                                </p>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Statuses -->
                <div class="bg-white rounded-lg border border-gray-200 p-4 sm:p-6">
                    <div class="px-4 sm:px-6 py-3 sm:py-4 -mx-4 sm:-mx-6 -mt-4 sm:-mt-6 mb-4 sm:mb-6 border-b border-gray-200 bg-blue-50">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center mr-3">
                                <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 16h-1v-4h-1m1-4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                                </svg>
                            </div>
                            <div>
                                <h2 class="text-lg sm:text-xl font-semibold text-gray-900">Status Pesanan</h2>
                                <p class="text-xs sm:text-sm text-gray-600">Informasi status terbaru</p>
                            </div>
                        </div>
                    </div>
                    <div class="space-y-3 sm:space-y-4">
                        <!-- Status Pesanan -->
                        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-3 p-3 sm:p-4 bg-gray-50 rounded-lg border border-gray-200">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 w-8 h-8 sm:w-10 sm:h-10 bg-gray-200 rounded-lg flex items-center justify-center mr-2 sm:mr-3">
                                    <svg class="w-4 h-4 sm:w-5 sm:h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2"></path>
                                    </svg>
                                </div>
                                <div>
                                    <p class="text-xs sm:text-sm font-medium text-gray-900">Status Pesanan</p>
                                    <p class="text-xs text-gray-500">Status persetujuan pesanan</p>
                                </div>
                            </div>
                            <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium
                                {{ $order->order_status === 'diterima'
                                    ? 'bg-green-100 text-green-800'
                                    : ($order->order_status === 'ditolak'
                                        ? 'bg-red-100 text-red-800'
                                        : 'bg-yellow-100 text-yellow-800') }}">
                                {{ $order->order_status_label }}
                            </span>
                        </div>

                        <!-- Status Pembayaran -->
                        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-3 p-3 sm:p-4 bg-gray-50 rounded-lg border border-gray-200">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 w-8 h-8 sm:w-10 sm:h-10 bg-gray-200 rounded-lg flex items-center justify-center mr-2 sm:mr-3">
                                    <svg class="w-4 h-4 sm:w-5 sm:h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z"></path>
                                    </svg>
                                </div>
                                <div>
                                    <p class="text-xs sm:text-sm font-medium text-gray-900">Status Pembayaran</p>
                                    <p class="text-xs text-gray-500">Status pembayaran pesanan</p>
                                </div>
                            </div>
                            <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium
                                {{ $order->status === 'selesai'
                                    ? 'bg-green-100 text-green-800'
                                    : ($order->status === 'gagal'
                                        ? 'bg-red-100 text-red-800'
                                        : ($order->status === 'dibatalkan'
                                            ? 'bg-gray-100 text-gray-800'
                                            : 'bg-yellow-100 text-yellow-800')) }}">
                                {{ $order->status_label }}
                            </span>
                        </div>

                        <!-- Status Produksi -->
                        <div class="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-2 sm:gap-3 p-3 sm:p-4 bg-gray-50 rounded-lg border border-gray-200">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 w-8 h-8 sm:w-10 sm:h-10 bg-gray-200 rounded-lg flex items-center justify-center mr-2 sm:mr-3">
                                    <svg class="w-4 h-4 sm:w-5 sm:h-5 text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"></path>
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                    </svg>
                                </div>
                                <div>
                                    <p class="text-xs sm:text-sm font-medium text-gray-900">Status Produksi</p>
                                    <p class="text-xs text-gray-500">Status pembuatan produk</p>
                                </div>
                            </div>
                            <span class="inline-flex items-center px-2.5 py-1 rounded-full text-xs font-medium
                                {{ $order->production_status === 'selesai'
                                    ? 'bg-green-100 text-green-800'
                                    : ($order->production_status === 'dalam_proses'
                                        ? 'bg-blue-100 text-blue-800'
                                        : ($order->production_status === 'dibatalkan'
                                            ? 'bg-gray-100 text-gray-800'
                                            : 'bg-yellow-100 text-yellow-800')) }}">
                                {{ $order->production_status_label }}
                            </span>
                        </div>
                    </div>
                </div>


            </div>

            <!-- Right Column: Product Info & Actions -->
            <div class="space-y-4 sm:space-y-6">
                <!-- Product Detail Card -->
                @if ($order->product)
                    <div class="bg-white rounded-lg border border-gray-200 p-4 sm:p-6">
                        <div class="px-4 sm:px-6 py-3 sm:py-4 -mx-4 sm:-mx-6 -mt-4 sm:-mt-6 mb-4 sm:mb-6 border-b border-gray-200 bg-blue-50">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center mr-3">
                                    <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"></path>
                                    </svg>
                                </div>
                                <div>
                                    <h2 class="text-lg sm:text-xl font-semibold text-gray-900">Detail Produk</h2>
                                    <p class="text-xs sm:text-sm text-gray-600">Produk yang dipesan</p>
                                </div>
                            </div>
                        </div>
                        @if ($order->product->product_image)
                            <div class="w-full mb-4">
                                <div class="w-full border border-gray-200 rounded-lg overflow-hidden bg-gray-50 p-2 sm:p-3">
                                    <img src="{{ asset('uploads/products/' . $order->product->product_image) }}"
                                        alt="{{ $order->product->product_title }}"
                                        class="w-full h-auto max-h-48 sm:max-h-56 md:max-h-64 object-contain">
                                </div>
                            </div>
                        @endif
                        <div class="space-y-3">
                            <div class="bg-gray-50 p-3 rounded-lg">
                                <p class="text-xs text-gray-500 mb-1">Nama Produk</p>
                                <p class="text-sm font-medium text-gray-900">{{ $order->product->product_title }}</p>
                            </div>
                            <div class="bg-gray-50 p-3 rounded-lg">
                                <p class="text-xs text-gray-500 mb-1">Harga Satuan</p>
                                <p class="text-sm font-bold text-blue-600">{{ $order->product->formatted_price ?? 'N/A' }}</p>
                            </div>
                            @if($order->product->product_description)
                                <div class="bg-gray-50 p-3 rounded-lg">
                                    <p class="text-xs text-gray-500 mb-1">Deskripsi</p>
                                    <p class="text-sm text-gray-700 line-clamp-3">{{ $order->product->product_description }}</p>
                                </div>
                            @endif
                        </div>
                    </div>
                @endif

                <!-- Actions Card -->
                <div class="bg-white rounded-lg border border-gray-200 p-4 sm:p-6">
                    <div class="px-4 sm:px-6 py-3 sm:py-4 -mx-4 sm:-mx-6 -mt-4 sm:-mt-6 mb-4 sm:mb-6 border-b border-gray-200 bg-blue-50">
                        <div class="flex items-center">
                            <div class="flex-shrink-0 w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center mr-3">
                                <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path>
                                </svg>
                            </div>
                            <div>
                                <h2 class="text-lg sm:text-xl font-semibold text-gray-900">Aksi</h2>
                                <p class="text-xs sm:text-sm text-gray-600">Tindakan cepat</p>
                            </div>
                        </div>
                    </div>
                    <div class="space-y-2 sm:space-y-3">
                        <!-- Retry Payment / Change Payment Method untuk Midtrans yang gagal -->
                        @if ($order->payment_method === 'midtrans' && $order->status !== 'selesai' && $order->midtrans_status !== 'settlement')
                            <button onclick="showPaymentOptions({{ $order->id }})"
                                class="w-full inline-flex items-center justify-center px-4 py-3 bg-purple-600 hover:bg-purple-700 text-white rounded-lg font-medium transition-colors">
                                <i class="fas fa-redo mr-2"></i>
                                Ulangi Pembayaran / Ganti Metode
                            </button>
                        @endif

                        <!-- Upload / Lihat Bukti Pembayaran untuk Transfer Bank -->
                        @if ($order->payment_method === 'transfer')
                            @php
                                // Cek apakah proof_file ada dan tidak kosong
                                $hasProofFile = !empty($order->proof_file);
                                
                                // Jika ada proof_file, cek apakah file benar-benar ada di storage
                                $proofExists = false;
                                if ($hasProofFile) {
                                    try {
                                        $proofExists = \Illuminate\Support\Facades\Storage::disk('uploads')->exists($order->proof_file);
                                    } catch (\Exception $e) {
                                        $proofExists = false;
                                    }
                                }
                            @endphp
                            @if (!$proofExists)
                                <a href="{{ route('orders.confirm.form', $order) }}"
                                    class="w-full inline-flex items-center justify-center px-4 py-3 bg-orange-600 hover:bg-orange-700 text-white rounded-lg font-medium transition-colors">
                                    <i class="fas fa-upload mr-2"></i>
                                    Upload Bukti Pembayaran
                                </a>
                            @else
                                @php
                                    // Selalu gunakan route orders.proof untuk keamanan dan konsistensi
                                    // Route ini akan serve file melalui Laravel dengan authorization check
                                    try {
                                        $proofUrl = route('orders.proof', $order->id);
                                    } catch (\Exception $e) {
                                        // Fallback jika route tidak ditemukan (misalnya cache belum di-clear)
                                        // Gunakan direct URL ke uploads dengan path yang benar (file disimpan di disk 'uploads')
                                        $proofUrl = asset('uploads/' . $order->proof_file);
                                    }
                                @endphp
                                <a href="{{ $proofUrl }}" target="_blank"
                                    class="w-full inline-flex items-center justify-center px-4 py-3 bg-green-600 hover:bg-green-700 text-white rounded-lg font-medium transition-colors">
                                    <i class="fas fa-file-invoice mr-2"></i>
                                    Lihat Bukti Pembayaran
                                </a>
                            @endif
                        @endif

                        <!-- Upload / Lihat Bukti Pembayaran DP -->
                        @if ($order->payment_method === 'dp')
                            @php
                                // Cek apakah proof_file ada dan tidak kosong
                                $hasProofFile = !empty($order->proof_file);
                                
                                // Jika ada proof_file, cek apakah file benar-benar ada di storage
                                $proofExists = false;
                                if ($hasProofFile) {
                                    try {
                                        $proofExists = \Illuminate\Support\Facades\Storage::disk('uploads')->exists($order->proof_file);
                                    } catch (\Exception $e) {
                                        $proofExists = false;
                                    }
                                }
                            @endphp
                            @if (!$proofExists)
                                <a href="{{ route('orders.confirm.form', $order) }}"
                                    class="w-full inline-flex items-center justify-center px-4 py-3 bg-orange-600 hover:bg-orange-700 text-white rounded-lg font-medium transition-colors">
                                    <i class="fas fa-upload mr-2"></i>
                                    Upload Bukti Pembayaran DP
                                </a>
                            @else
                                @php
                                    // Selalu gunakan route orders.proof untuk keamanan dan konsistensi
                                    try {
                                        $proofUrl = route('orders.proof', $order->id);
                                    } catch (\Exception $e) {
                                        $proofUrl = asset('uploads/' . $order->proof_file);
                                    }
                                @endphp
                                <a href="{{ $proofUrl }}" target="_blank"
                                    class="w-full inline-flex items-center justify-center px-4 py-3 bg-green-600 hover:bg-green-700 text-white rounded-lg font-medium transition-colors">
                                    <i class="fas fa-file-invoice mr-2"></i>
                                    Lihat Bukti Pembayaran DP
                                </a>
                            @endif
                        @endif

                        <a href="{{ route('all') }}"
                            class="w-full inline-flex items-center justify-center px-4 py-3 text-sm text-blue-600 hover:text-blue-800 font-medium border border-blue-200 hover:border-blue-300 rounded-lg transition-colors">
                            <svg class="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"></path>
                            </svg>
                            Belanja Lagi
                        </a>
                    </div>
                </div>

                <!-- Shipping Info (if exists) -->
                @if (isset($order->shipping_address))
                    <div class="bg-white rounded-lg border border-gray-200 p-4 sm:p-6">
                        <div class="px-4 sm:px-6 py-3 sm:py-4 -mx-4 sm:-mx-6 -mt-4 sm:-mt-6 mb-4 sm:mb-6 border-b border-gray-200 bg-blue-50">
                            <div class="flex items-center">
                                <div class="flex-shrink-0 w-10 h-10 bg-blue-600 rounded-lg flex items-center justify-center mr-3">
                                    <svg class="w-5 h-5 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"></path>
                                    </svg>
                                </div>
                                <div>
                                    <h3 class="text-base sm:text-lg font-semibold text-gray-900">Alamat Pengiriman</h3>
                                    <p class="text-xs sm:text-sm text-gray-600">Informasi pengiriman produk</p>
                                </div>
                            </div>
                        </div>
                        <p class="text-sm text-gray-700">{{ $order->shipping_address }}</p>
                    </div>
                @endif
            </div>
        </div>
    </div>
</div>

<!-- SweetAlert2 CDN -->
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<!-- Midtrans Snap JS -->
@if(config('midtrans.client_key'))
<script src="{{ config('midtrans.is_production') ? 'https://app.midtrans.com/snap/snap.js' : 'https://app.sandbox.midtrans.com/snap/snap.js' }}" 
        data-client-key="{{ config('midtrans.client_key') }}"
        onerror="console.error('Gagal memuat Midtrans Snap JS')">
</script>
@else
<script>
    console.warn('Midtrans Client Key belum dikonfigurasi');
</script>
@endif

@if (session('success'))
    <script>
        Swal.fire({
            title: 'Berhasil!',
            text: '{{ session('success') }}',
            icon: 'success',
            timer: 3000,
            timerProgressBar: true,
            showConfirmButton: false,
            position: 'center',
            allowOutsideClick: false
        });
    </script>
@endif

@if (session('error'))
    <script>
        Swal.fire({
            title: 'Error!',
            text: '{{ session('error') }}',
            icon: 'error',
            timer: 3000,
            timerProgressBar: true,
            showConfirmButton: false,
            position: 'center',
            allowOutsideClick: false
        });
    </script>
@endif

<script>
    // Function untuk menampilkan opsi pembayaran
    function showPaymentOptions(orderId) {
        Swal.fire({
            title: 'Opsi Pembayaran',
            text: 'Pilih aksi yang ingin dilakukan',
            icon: 'question',
            showCancelButton: true,
            showDenyButton: true,
            confirmButtonText: '<i class="fas fa-redo mr-2"></i>Ulangi Midtrans',
            denyButtonText: '<i class="fas fa-exchange-alt mr-2"></i>Ganti Metode',
            cancelButtonText: 'Batal',
            confirmButtonColor: '#7c3aed',
            denyButtonColor: '#f59e0b',
            cancelButtonColor: '#6b7280',
        }).then((result) => {
            if (result.isConfirmed) {
                // Retry Midtrans payment
                retryMidtransPayment(orderId);
            } else if (result.isDenied) {
                // Change payment method
                showChangePaymentMethod(orderId);
            }
        });
    }

    // Function untuk retry Midtrans payment
    function retryMidtransPayment(orderId) {
        Swal.fire({
            title: 'Memproses...',
            text: 'Sedang membuat token pembayaran',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        fetch(`/my-orders/${orderId}/retry-midtrans`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => response.json())
        .then(data => {
            if (data.success && data.snap_token) {
                Swal.close();
                // Buka Midtrans popup
                if (typeof snap !== 'undefined') {
                    snap.pay(data.snap_token, {
                        onSuccess: function(result) {
                            const orderId = data.order_id || result.order_id;
                            const successUrl = '{{ route("orders.success", ":id") }}'.replace(':id', orderId);
                            window.location.href = successUrl;
                        },
                        onPending: function(result) {
                            const orderId = data.order_id || result.order_id;
                            Swal.fire({
                                title: 'Pembayaran Pending',
                                text: 'Pembayaran sedang diproses. Silakan tunggu konfirmasi.',
                                icon: 'info',
                                confirmButtonText: 'OK'
                            }).then(() => {
                                const successUrl = '{{ route("orders.success", ":id") }}'.replace(':id', orderId);
                                window.location.href = successUrl;
                            });
                        },
                        onError: function(result) {
                            Swal.fire('Error', 'Terjadi kesalahan dalam pembayaran. Silakan coba lagi.', 'error');
                            console.error('Midtrans error:', result);
                        },
                        onClose: function() {
                            Swal.fire({
                                title: 'Ditutup',
                                text: 'Anda menutup pembayaran sebelum selesai.',
                                icon: 'warning',
                                confirmButtonText: 'OK'
                            });
                        }
                    });
                } else {
                    Swal.fire('Error', 'Midtrans Snap belum dimuat. Silakan refresh halaman.', 'error');
                }
            } else {
                Swal.fire('Error', data.message || 'Gagal membuat token pembayaran', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire('Error', 'Terjadi kesalahan server', 'error');
        });
    }

    // Function untuk menampilkan form ganti metode pembayaran
    function showChangePaymentMethod(orderId) {
        Swal.fire({
            title: 'Ganti Metode Pembayaran',
            html: `
                <div class="text-left">
                    <p class="mb-4 text-sm text-gray-600">Pilih metode pembayaran baru:</p>
                    <div class="space-y-3">
                        <label class="flex items-center p-3 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50 transition-all">
                            <input type="radio" name="payment_method" value="transfer" class="mr-3" checked>
                            <div>
                                <span class="font-medium text-gray-800 block">Transfer Bank</span>
                                <p class="text-xs text-gray-500">BCA, BNI, Mandiri, BRI</p>
                            </div>
                        </label>
                        <label class="flex items-center p-3 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-blue-500 hover:bg-blue-50 transition-all">
                            <input type="radio" name="payment_method" value="midtrans" class="mr-3">
                            <div>
                                <span class="font-medium text-gray-800 block">E-Wallet / QRIS</span>
                                <p class="text-xs text-gray-500">GoPay, OVO, Dana, QRIS</p>
                            </div>
                        </label>
                        <label class="flex items-center p-3 border-2 border-gray-300 rounded-lg cursor-pointer hover:border-orange-500 hover:bg-orange-50 transition-all">
                            <input type="radio" name="payment_method" value="dp" class="mr-3">
                            <div>
                                <span class="font-medium text-gray-800 block">Pembayaran DP</span>
                                <p class="text-xs text-gray-500">Bayar sebagian sekarang</p>
                            </div>
                        </label>
                    </div>
                </div>
            `,
            showCancelButton: true,
            confirmButtonText: 'Ganti',
            cancelButtonText: 'Batal',
            confirmButtonColor: '#f59e0b',
            cancelButtonColor: '#6b7280',
            preConfirm: () => {
                const selectedMethod = document.querySelector('input[name="payment_method"]:checked');
                if (!selectedMethod) {
                    Swal.showValidationMessage('Pilih metode pembayaran');
                    return false;
                }
                return selectedMethod.value;
            }
        }).then((result) => {
            if (result.isConfirmed && result.value) {
                changePaymentMethod(orderId, result.value);
            }
        });
    }

    // Function untuk change payment method
    function changePaymentMethod(orderId, newMethod) {
        Swal.fire({
            title: 'Memproses...',
            text: 'Sedang mengubah metode pembayaran',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });

        const formData = new FormData();
        formData.append('new_payment_method', newMethod);

        fetch(`/my-orders/${orderId}/change-payment-method`, {
            method: 'POST',
            body: formData,
            headers: {
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                'X-Requested-With': 'XMLHttpRequest',
                'Accept': 'application/json'
            }
        })
        .then(response => {
            const contentType = response.headers.get('content-type');
            if (contentType && contentType.includes('application/json')) {
                return response.json();
            } else {
                // Redirect response
                return response.text().then(() => ({ redirect: true, url: response.url }));
            }
        })
        .then(data => {
            if (data.redirect) {
                window.location.href = data.url || '/my-orders';
            } else if (data.success) {
                if (data.snap_token && newMethod === 'midtrans') {
                    // Buka Midtrans popup
                    Swal.close();
                    if (typeof snap !== 'undefined') {
                        snap.pay(data.snap_token, {
                            onSuccess: function(result) {
                                const orderId = data.order_id || result.order_id;
                                const successUrl = '{{ route("orders.success", ":id") }}'.replace(':id', orderId);
                                window.location.href = successUrl;
                            },
                            onPending: function(result) {
                                const orderId = data.order_id || result.order_id;
                                Swal.fire({
                                    title: 'Pembayaran Pending',
                                    text: 'Pembayaran sedang diproses. Silakan tunggu konfirmasi.',
                                    icon: 'info',
                                    confirmButtonText: 'OK'
                                }).then(() => {
                                    const successUrl = '{{ route("orders.success", ":id") }}'.replace(':id', orderId);
                                    window.location.href = successUrl;
                                });
                            },
                            onError: function(result) {
                                Swal.fire('Error', 'Terjadi kesalahan dalam pembayaran. Silakan coba lagi.', 'error');
                                console.error('Midtrans error:', result);
                            },
                            onClose: function() {
                                Swal.fire({
                                    title: 'Ditutup',
                                    text: 'Anda menutup pembayaran sebelum selesai.',
                                    icon: 'warning',
                                    confirmButtonText: 'OK'
                                });
                            }
                        });
                    } else {
                        Swal.fire('Error', 'Midtrans Snap belum dimuat. Silakan refresh halaman.', 'error');
                    }
                } else {
                    Swal.fire('Sukses', data.message || 'Metode pembayaran berhasil diubah', 'success').then(() => {
                        window.location.reload();
                    });
                }
            } else {
                Swal.fire('Error', data.message || 'Gagal mengubah metode pembayaran', 'error');
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire('Error', 'Terjadi kesalahan server', 'error');
        });
    }
</script>
@endsection
