@extends('layouts.member')

@section('title', 'Commande #' . ($order->order_number ?? $order->id))
@section('page-title', 'Détails de la commande')

@push('styles')
<style>
    .order-status-timeline {
        display: flex;
        justify-content: space-between;
        position: relative;
        margin: 2rem 0;
    }
    .order-status-timeline::before {
        content: '';
        position: absolute;
        top: 20px;
        left: 0;
        right: 0;
        height: 4px;
        background: #e9ecef;
        z-index: 0;
    }
    .timeline-step {
        text-align: center;
        position: relative;
        z-index: 1;
        flex: 1;
    }
    .timeline-step .step-icon {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        background: #e9ecef;
        display: flex;
        align-items: center;
        justify-content: center;
        margin: 0 auto 0.5rem;
        color: #6c757d;
        transition: all 0.3s ease;
    }
    .timeline-step.completed .step-icon {
        background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
        color: white;
    }
    .timeline-step.active .step-icon {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        transform: scale(1.2);
        box-shadow: 0 5px 20px rgba(102, 126, 234, 0.4);
    }
    .product-image-wrapper {
        width: 100px;
        height: 100px;
        border-radius: 12px;
        overflow: hidden;
        flex-shrink: 0;
    }
    .summary-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 20px;
        padding: 1.5rem;
    }
    .glass-card {
        background: rgba(255, 255, 255, 0.95);
        backdrop-filter: blur(10px);
        border: 1px solid rgba(255,255,255,0.2);
    }
</style>
@endpush

@section('content')
@php
    $status = $order->status;
    $statusMap = [
        'pending' => ['warning', 'En attente', 'bi-hourglass-split', 1],
        'processing' => ['info', 'En cours', 'bi-gear', 2],
        'shipped' => ['primary', 'Expédiée', 'bi-truck', 3],
        'delivered' => ['success', 'Livrée', 'bi-check-circle', 4],
        'cancelled' => ['danger', 'Annulée', 'bi-x-circle', 0]
    ];
    $badge = $statusMap[$status] ?? ['secondary', ucfirst($status), 'bi-question-circle', 0];
    $currentStep = $badge[3];
@endphp

<!-- Header Section -->
<div class="d-flex flex-column flex-lg-row align-items-lg-center justify-content-between gap-3 mb-4">
    <div>
        <div class="d-flex align-items-center gap-3">
            <div class="rounded-circle bg-primary-subtle p-3">
                <i class="bi bi-receipt fs-3 text-primary"></i>
            </div>
            <div>
                <h4 class="mb-1 fw-bold">Commande #{{ $order->order_number ?? $order->id }}</h4>
                <div class="d-flex align-items-center gap-2 flex-wrap">
                    <span class="badge bg-{{ $badge[0] }} bg-opacity-75 px-3 py-2">
                        <i class="bi {{ $badge[2] }} me-1"></i> {{ $badge[1] }}
                    </span>
                    @if($order->order_type === 'investment')
                        <span class="badge bg-primary px-3 py-2">
                            <i class="bi bi-gem me-1"></i> Produit d'investissement
                        </span>
                    @endif
                    <small class="text-muted">• {{ $order->created_at->format('d/m/Y à H:i') }}</small>
                </div>
            </div>
        </div>
    </div>
    <a href="{{ route('member.orders.index') }}" class="btn btn-outline-secondary rounded-pill px-4">
        <i class="bi bi-arrow-left me-2"></i> Retour aux commandes
    </a>
</div>

<!-- Status Timeline -->
@if($status !== 'cancelled')
<div class="card border-0 rounded-4 shadow-sm mb-4">
    <div class="card-body p-4">
        <div class="order-status-timeline">
            <div class="timeline-step {{ $currentStep >= 1 ? ($currentStep == 1 ? 'active' : 'completed') : '' }}">
                <div class="step-icon">
                    <i class="bi bi-hourglass-split"></i>
                </div>
                <small class="text-muted">En attente</small>
            </div>
            <div class="timeline-step {{ $currentStep >= 2 ? ($currentStep == 2 ? 'active' : 'completed') : '' }}">
                <div class="step-icon">
                    <i class="bi bi-gear"></i>
                </div>
                <small class="text-muted">En cours</small>
            </div>
            <div class="timeline-step {{ $currentStep >= 3 ? ($currentStep == 3 ? 'active' : 'completed') : '' }}">
                <div class="step-icon">
                    <i class="bi bi-truck"></i>
                </div>
                <small class="text-muted">Expédiée</small>
            </div>
            <div class="timeline-step {{ $currentStep >= 4 ? 'completed' : '' }}">
                <div class="step-icon">
                    <i class="bi bi-check-circle"></i>
                </div>
                <small class="text-muted">Livrée</small>
            </div>
        </div>
    </div>
</div>
@endif

<div class="row g-4">
    <!-- Main Content -->
    <div class="col-lg-8">
        <!-- Products Section -->
        <div class="card border-0 rounded-4 shadow-sm mb-4">
            <div class="card-header bg-white rounded-top-4 border-0 py-3">
                <div class="d-flex align-items-center justify-content-between">
                    <h5 class="mb-0 fw-bold"><i class="bi bi-box-seam me-2 text-primary"></i>Article(s) commandé(s)</h5>
                    <span class="badge bg-light text-dark">
                        {{ $order->order_type === 'investment' ? '1 article' : $order->items->count() . ' article(s)' }}
                    </span>
                </div>
            </div>
            <div class="card-body p-0">
                <div class="list-group list-group-flush">
                    @if($order->order_type === 'investment' && $order->investmentProduct)
                        {{-- Affichage du produit d'investissement --}}
                        <div class="list-group-item p-4">
                            <div class="d-flex align-items-center gap-4">
                                <div class="product-image-wrapper">
                                    @if($order->investmentProduct->image)
                                        <img src="{{ $order->investmentProduct->image_url }}" class="w-100 h-100" style="object-fit: cover;" alt="{{ $order->investmentProduct->name }}">
                                    @else
                                        <div class="w-100 h-100 d-flex align-items-center justify-content-center" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                            <i class="bi bi-gem text-white fs-3"></i>
                                        </div>
                                    @endif
                                </div>
                                <div class="flex-grow-1">
                                    <div class="d-flex align-items-start justify-content-between">
                                        <div>
                                            <h6 class="fw-bold mb-1">{{ $order->investmentProduct->name }}</h6>
                                            <span class="badge bg-primary-subtle text-primary mb-2">Produit d'investissement</span>
                                            @if($order->investmentProduct->description)
                                                <p class="text-muted small mb-0">{{ Str::limit($order->investmentProduct->description, 100) }}</p>
                                            @endif
                                            @if($order->investmentProduct->features && is_string($order->investmentProduct->features))
                                                <div class="mt-2">
                                                    @foreach(array_slice(explode("\n", $order->investmentProduct->features), 0, 2) as $feature)
                                                        @if(trim($feature))
                                                            <span class="badge bg-success-subtle text-success me-1 mb-1">
                                                                <i class="bi bi-check2 me-1"></i>{{ Str::limit(trim($feature), 30) }}
                                                            </span>
                                                        @endif
                                                    @endforeach
                                                </div>
                                            @endif
                                        </div>
                                        <div class="text-end">
                                            <div class="fs-5 fw-bold text-primary">{{ number_format($order->subtotal ?? $order->investmentProduct->price, 0, ',', ' ') }} XOF</div>
                                            <small class="text-muted">Quantité: 1</small>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    @else
                        {{-- Affichage des articles normaux --}}
                        @php
                            // Récupérer les produits déjà notés par l'utilisateur
                            $reviewedProductIds = \App\Models\Review::where('user_id', auth()->id())->pluck('product_id')->toArray();
                        @endphp
                        @forelse($order->items as $item)
                            <div class="list-group-item p-4">
                                <div class="d-flex align-items-center gap-4">
                                    <div class="product-image-wrapper">
                                        @if($item->product && $item->product->image)
                                            <img src="{{ asset('storage/' . $item->product->image) }}" class="w-100 h-100" style="object-fit: cover;" alt="{{ $item->product->name ?? 'Produit' }}">
                                        @else
                                            <div class="w-100 h-100 bg-light d-flex align-items-center justify-content-center">
                                                <i class="bi bi-box text-muted fs-3"></i>
                                            </div>
                                        @endif
                                    </div>
                                    <div class="flex-grow-1">
                                        <div class="d-flex align-items-start justify-content-between">
                                            <div>
                                                <h6 class="fw-bold mb-1">{{ $item->product->name ?? 'Produit supprimé' }}</h6>
                                                @if($item->product && $item->product->category)
                                                    <span class="badge bg-light text-dark mb-2">{{ $item->product->category->name }}</span>
                                                @endif
                                                {{-- Bouton de notation si commande livrée --}}
                                                @if($order->status === 'delivered' && $item->product)
                                                    @if(in_array($item->product_id, $reviewedProductIds))
                                                        <span class="badge bg-success-subtle text-success">
                                                            <i class="bi bi-check-circle me-1"></i> Noté
                                                        </span>
                                                    @else
                                                        <a href="{{ route('member.reviews.create', $item->product_id) }}" 
                                                           class="btn btn-sm btn-outline-warning">
                                                            <i class="bi bi-star me-1"></i> Noter ce produit
                                                        </a>
                                                    @endif
                                                @endif
                                            </div>
                                            <div class="text-end">
                                                <div class="fs-5 fw-bold text-primary">{{ number_format(($item->price ?? 0) * $item->quantity, 0, ',', ' ') }} XOF</div>
                                                <small class="text-muted">{{ number_format($item->price ?? 0, 0, ',', ' ') }} XOF × {{ $item->quantity }}</small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        @empty
                            <div class="list-group-item p-4 text-center text-muted">
                                <i class="bi bi-inbox fs-1 mb-2 d-block"></i>
                                Aucun article dans cette commande
                            </div>
                        @endforelse
                    @endif
                </div>
            </div>
        </div>

        <!-- Shipping Info -->
        @if($order->shipping_address || $order->shipping_city)
        <div class="card border-0 rounded-4 shadow-sm mb-4">
            <div class="card-header bg-white rounded-top-4 border-0 py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-geo-alt me-2 text-primary"></i>Adresse de livraison</h5>
            </div>
            <div class="card-body">
                <div class="d-flex align-items-start gap-3">
                    <div class="rounded-circle bg-primary-subtle p-3">
                        <i class="bi bi-house-door text-primary"></i>
                    </div>
                    <div>
                        <h6 class="fw-bold mb-1">{{ $order->customer_name ?? auth()->user()->name }}</h6>
                        <p class="mb-1 text-muted">{{ $order->shipping_address }}</p>
                        <p class="mb-0 text-muted">
                            {{ $order->shipping_city }}
                            @if($order->shipping_country)
                                , {{ $order->shipping_country }}
                            @endif
                        </p>
                        @if($order->customer_phone)
                            <p class="mb-0 mt-2"><i class="bi bi-telephone me-2 text-primary"></i>{{ $order->customer_phone }}</p>
                        @endif
                    </div>
                </div>
            </div>
        </div>
        @endif

        <!-- Order Notes -->
        @if($order->notes)
        <div class="card border-0 rounded-4 shadow-sm mb-4">
            <div class="card-header bg-white rounded-top-4 border-0 py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-chat-left-text me-2 text-primary"></i>Notes</h5>
            </div>
            <div class="card-body">
                <p class="mb-0 text-muted">{{ $order->notes }}</p>
            </div>
        </div>
        @endif

        <!-- Preuve de livraison -->
        @if($order->delivery_proof_transmitted_at && $order->delivery_proof)
        <div class="card border-0 rounded-4 shadow-sm mb-4 overflow-hidden">
            <div class="card-header py-3" style="background: linear-gradient(135deg, #10b981 0%, #34d399 100%);">
                <h5 class="mb-0 fw-bold text-white"><i class="bi bi-camera-fill me-2"></i>Preuve de livraison</h5>
            </div>
            <div class="card-body p-4">
                <div class="text-center mb-3">
                    <a href="{{ asset('storage/' . $order->delivery_proof) }}" target="_blank" class="d-inline-block position-relative">
                        <img src="{{ asset('storage/' . $order->delivery_proof) }}" 
                             alt="Preuve de livraison" 
                             class="img-fluid rounded-4 shadow-sm" 
                             style="max-height: 350px; cursor: zoom-in; border: 3px solid #e5e7eb; transition: all 0.3s ease;"
                             onmouseover="this.style.borderColor='#10b981'; this.style.transform='scale(1.02)'"
                             onmouseout="this.style.borderColor='#e5e7eb'; this.style.transform='scale(1)'">
                        <div class="position-absolute top-0 end-0 m-2">
                            <span class="badge bg-success px-3 py-2 rounded-pill">
                                <i class="bi bi-check-circle me-1"></i> Confirmée
                            </span>
                        </div>
                    </a>
                </div>
                
                {{-- Bouton de téléchargement --}}
                <div class="d-flex justify-content-center gap-3 mb-3">
                    <a href="{{ asset('storage/' . $order->delivery_proof) }}" 
                       download="preuve-livraison-{{ $order->order_number }}.jpg"
                       class="btn btn-success rounded-pill px-4">
                        <i class="bi bi-download me-2"></i> Télécharger la preuve
                    </a>
                    <a href="{{ asset('storage/' . $order->delivery_proof) }}" 
                       target="_blank"
                       class="btn btn-outline-success rounded-pill px-4">
                        <i class="bi bi-eye me-2"></i> Voir en grand
                    </a>
                </div>
                
                <div class="alert alert-success border-0 rounded-3 mb-0" style="background: rgba(16, 185, 129, 0.1);">
                    <div class="d-flex align-items-center gap-2">
                        <i class="bi bi-shield-check fs-4 text-success"></i>
                        <div>
                            <strong>Livraison confirmée</strong>
                            <p class="mb-0 small text-muted">
                                Preuve reçue le {{ \Carbon\Carbon::parse($order->delivery_proof_transmitted_at)->format('d/m/Y à H:i') }}
                            </p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        @elseif($order->seller_id && ($order->status === 'delivered' || $order->status === 'shipped'))
        {{-- Afficher "Preuve en attente" UNIQUEMENT pour les commandes vendeur (pas pour les commandes admin) --}}
        <div class="card border-0 rounded-4 shadow-sm mb-4">
            <div class="card-header bg-white rounded-top-4 border-0 py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-camera me-2 text-primary"></i>Preuve de livraison</h5>
            </div>
            <div class="card-body text-center py-4">
                <div class="rounded-circle bg-light d-inline-flex align-items-center justify-content-center mb-3" style="width: 80px; height: 80px;">
                    <i class="bi bi-hourglass-split fs-2 text-warning"></i>
                </div>
                <h6 class="text-muted">Preuve en attente</h6>
                <p class="small text-muted mb-0">
                    La preuve de livraison vous sera transmise une fois que le vendeur l'aura soumise et qu'elle aura été validée.
                </p>
            </div>
        </div>
        @endif
    </div>

    <!-- Sidebar -->
    <div class="col-lg-4">
        <!-- Order Summary -->
        <div class="summary-card mb-4">
            <h5 class="fw-bold mb-4"><i class="bi bi-receipt me-2"></i>Récapitulatif</h5>
            
            <div class="d-flex justify-content-between mb-2">
                <span class="opacity-75">Sous-total</span>
                <span class="fw-bold">{{ number_format($order->subtotal ?? $order->total_amount, 0, ',', ' ') }} XOF</span>
            </div>
            
            @if($order->discount_amount > 0)
            <div class="d-flex justify-content-between mb-2">
                <span class="opacity-75">Réduction</span>
                <span class="fw-bold">-{{ number_format($order->discount_amount, 0, ',', ' ') }} XOF</span>
            </div>
            @endif
            
            <div class="d-flex justify-content-between mb-3">
                <span class="opacity-75">Frais de livraison</span>
                <span class="fw-bold">{{ number_format($order->shipping_fee ?? 0, 0, ',', ' ') }} XOF</span>
            </div>
            
            <hr class="border-white opacity-25">
            
            <div class="d-flex justify-content-between align-items-center">
                <span class="fs-5">Total payé</span>
                <span class="fs-4 fw-bold">{{ number_format($order->total_amount ?? $order->total, 0, ',', ' ') }} XOF</span>
            </div>
        </div>

        <!-- Payment Info -->
        <div class="card border-0 rounded-4 shadow-sm mb-4">
            <div class="card-header bg-white rounded-top-4 border-0 py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-credit-card me-2 text-primary"></i>Paiement</h5>
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between mb-3">
                    <span class="text-muted">Méthode</span>
                    <span class="fw-bold">
                        @switch($order->payment_method)
                            @case('mobile_money')
                                <i class="bi bi-phone text-warning me-1"></i> Mobile Money
                                @break
                            @case('card')
                                <i class="bi bi-credit-card text-primary me-1"></i> Carte bancaire
                                @break
                            @case('wallet')
                                <i class="bi bi-wallet2 text-success me-1"></i> Wallet
                                @break
                            @default
                                {{ ucfirst($order->payment_method ?? 'Non spécifié') }}
                        @endswitch
                    </span>
                </div>
                <div class="d-flex justify-content-between mb-3">
                    <span class="text-muted">Statut</span>
                    @php
                        $paymentStatusMap = [
                            'paid' => ['success', 'Payé'],
                            'pending' => ['warning', 'En attente'],
                            'failed' => ['danger', 'Échoué'],
                        ];
                        $paymentBadge = $paymentStatusMap[$order->payment_status] ?? ['secondary', ucfirst($order->payment_status)];
                    @endphp
                    <span class="badge bg-{{ $paymentBadge[0] }}">{{ $paymentBadge[1] }}</span>
                </div>
                @if($order->payment_reference)
                <div class="d-flex justify-content-between">
                    <span class="text-muted">Référence</span>
                    <span class="fw-bold small font-monospace">{{ Str::limit($order->payment_reference, 20) }}</span>
                </div>
                @endif
            </div>
        </div>

        <!-- Dates -->
        <div class="card border-0 rounded-4 shadow-sm">
            <div class="card-header bg-white rounded-top-4 border-0 py-3">
                <h5 class="mb-0 fw-bold"><i class="bi bi-calendar3 me-2 text-primary"></i>Historique</h5>
            </div>
            <div class="card-body">
                <div class="d-flex justify-content-between mb-3">
                    <span class="text-muted">Créée le</span>
                    <span class="fw-bold">{{ $order->created_at->format('d/m/Y H:i') }}</span>
                </div>
                @if($order->shipped_at)
                <div class="d-flex justify-content-between mb-3">
                    <span class="text-muted">Expédiée le</span>
                    <span class="fw-bold">{{ $order->shipped_at->format('d/m/Y') }}</span>
                </div>
                @endif
                @if($order->delivered_at)
                <div class="d-flex justify-content-between">
                    <span class="text-muted">Livrée le</span>
                    <span class="fw-bold">{{ $order->delivered_at->format('d/m/Y') }}</span>
                </div>
                @endif
            </div>
        </div>

        <!-- Actions -->
        @if($order->status === 'delivered')
        <div class="mt-4">
            <a href="{{ route('member.disputes.create') }}?order_id={{ $order->id }}" class="btn btn-outline-danger w-100 rounded-pill">
                <i class="bi bi-exclamation-triangle me-2"></i>Signaler un problème
            </a>
        </div>
        @endif
    </div>
</div>
@endsection
