@extends('layouts.seller')

@section('title', 'Commande #' . ($order->order_number ?? $order->id))

@section('content')
<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="mb-1">Commande #{{ $order->order_number ?? $order->id }}</h2>
            <p class="text-muted mb-0">Détails de vos produits dans cette commande</p>
        </div>
        <a href="{{ route('seller.orders.index') }}" class="btn btn-outline-secondary">
            <i class="bi bi-arrow-left me-1"></i> Retour
        </a>
    </div>

    @if(session('success'))
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="bi bi-check-circle me-2"></i>{{ session('success') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="bi bi-exclamation-circle me-2"></i>{{ session('error') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    @endif

    <div class="row">
        <div class="col-lg-8">
            <!-- Résumé financier pour ce seller -->
            <div class="card border-0 shadow-sm mb-4" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                <div class="card-body text-white">
                    <div class="row text-center">
                        <div class="col-4">
                            <div class="h4 mb-1">{{ number_format($sellerTotal, 0, ',', ' ') }} XOF</div>
                            <small class="opacity-75">Montant brut</small>
                        </div>
                        <div class="col-4 border-start border-end border-white-50">
                            <div class="h4 mb-1 text-warning">-{{ number_format($sellerCommission, 0, ',', ' ') }} XOF</div>
                            <small class="opacity-75">Commission ({{ $seller->commission_rate ?? 10 }}%)</small>
                        </div>
                        <div class="col-4">
                            <div class="h4 mb-1">{{ number_format($sellerNetAmount, 0, ',', ' ') }} XOF</div>
                            <small class="opacity-75">Montant net</small>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Articles du seller dans cette commande -->
            <div class="card mb-4">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="bi bi-box me-2"></i>Mes produits dans cette commande</h5>
                    @php
                        $statusBadges = [
                            'pending' => 'bg-warning text-dark',
                            'processing' => 'bg-info',
                            'shipped' => 'bg-primary',
                            'delivered' => 'bg-success',
                            'cancelled' => 'bg-danger'
                        ];
                        $statusLabels = [
                            'pending' => 'En attente',
                            'processing' => 'En préparation',
                            'shipped' => 'Expédiée',
                            'delivered' => 'Livrée',
                            'cancelled' => 'Annulée'
                        ];
                    @endphp
                    <span class="badge {{ $statusBadges[$order->status] ?? 'bg-secondary' }} fs-6">
                        {{ $statusLabels[$order->status] ?? $order->status }}
                    </span>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table">
                            <thead>
                                <tr>
                                    <th>Produit</th>
                                    <th class="text-center">Qté</th>
                                    <th class="text-end">Prix unit.</th>
                                    <th class="text-end">Total</th>
                                    <th class="text-end">Commission</th>
                                    <th class="text-end">Net</th>
                                </tr>
                            </thead>
                            <tbody>
                                @foreach($sellerItems as $item)
                                <tr>
                                    <td>
                                        <div class="d-flex align-items-center gap-2">
                                            @if($item->product && $item->product->image)
                                            <img src="{{ asset('storage/' . $item->product->image) }}" class="rounded" style="width:50px;height:50px;object-fit:cover" loading="lazy">
                                            @else
                                            <div class="bg-light rounded d-flex align-items-center justify-content-center" style="width:50px;height:50px">
                                                <i class="bi bi-image text-muted"></i>
                                            </div>
                                            @endif
                                            <div>
                                                <span class="fw-medium">{{ $item->product->name ?? $item->product_name ?? 'Produit supprimé' }}</span>
                                                @if($item->seller_paid)
                                                    <br><span class="badge bg-success-subtle text-success small">
                                                        <i class="bi bi-check-circle me-1"></i>Payé
                                                    </span>
                                                @endif
                                            </div>
                                        </div>
                                    </td>
                                    <td class="text-center">{{ $item->quantity }}</td>
                                    <td class="text-end">{{ number_format($item->price, 0, ',', ' ') }} XOF</td>
                                    <td class="text-end fw-bold">{{ number_format($item->total_price, 0, ',', ' ') }} XOF</td>
                                    <td class="text-end text-danger">-{{ number_format($item->seller_commission, 0, ',', ' ') }} XOF</td>
                                    <td class="text-end fw-bold text-success">{{ number_format($item->seller_amount, 0, ',', ' ') }} XOF</td>
                                </tr>
                                @endforeach
                            </tbody>
                            <tfoot class="table-light">
                                <tr>
                                    <td colspan="3" class="text-end">Total brut (vos produits)</td>
                                    <td class="text-end fw-bold">{{ number_format($sellerTotal, 0, ',', ' ') }} XOF</td>
                                    <td class="text-end text-danger">-{{ number_format($sellerCommission, 0, ',', ' ') }} XOF</td>
                                    <td class="text-end fw-bold text-success fs-5">{{ number_format($sellerNetAmount, 0, ',', ' ') }} XOF</td>
                                </tr>
                            </tfoot>
                        </table>
                    </div>
                </div>
            </div>

            <!-- Mettre à jour le statut -->
            <div class="card mb-4">
                <div class="card-header bg-white">
                    <h5 class="mb-0"><i class="bi bi-arrow-repeat me-2"></i>Mettre à jour le statut</h5>
                </div>
                <div class="card-body">
                    @php
                        $statusOrder = ['pending' => 1, 'processing' => 2, 'shipped' => 3, 'delivered' => 4, 'cancelled' => 0];
                        $currentStatusOrder = $statusOrder[$order->status] ?? 0;
                        $isFinalStatus = in_array($order->status, ['delivered', 'cancelled']);
                        $allStatuses = [
                            'pending' => 'En attente',
                            'processing' => 'En préparation',
                            'shipped' => 'Expédiée',
                            'delivered' => 'Livrée',
                            'cancelled' => 'Annulée'
                        ];
                    @endphp
                    
                    @if($isFinalStatus)
                        <div class="alert alert-info mb-0">
                            <i class="bi bi-lock me-2"></i>
                            <strong>Statut final</strong> - Cette commande est en statut "{{ $allStatuses[$order->status] }}" et ne peut plus être modifiée.
                        </div>
                    @else
                        <div class="alert alert-warning mb-3">
                            <i class="bi bi-exclamation-triangle me-2"></i>
                            <small><strong>Important:</strong> Le statut d'une commande ne peut qu'avancer (pending → processing → shipped → delivered). Aucune rétrogradation n'est possible pour garantir la transparence.</small>
                        </div>
                        <form action="{{ route('seller.orders.update-status', $order) }}" method="POST" class="row g-3">
                            @csrf @method('PUT')
                            <div class="col-md-8">
                                <select name="status" class="form-select" id="sellerStatusSelect">
                                    <option value="">-- Choisir un nouveau statut --</option>
                                    @foreach($allStatuses as $statusKey => $statusLabel)
                                        @php
                                            $statusOrd = $statusOrder[$statusKey];
                                            // Afficher uniquement les statuts supérieurs au statut actuel
                                            // ou cancelled si pas encore livré
                                            $canSelect = ($statusOrd > $currentStatusOrder) || 
                                                         ($statusKey === 'cancelled' && $order->status !== 'delivered' && $order->delivery_proof_status !== 'approved');
                                        @endphp
                                        @if($canSelect)
                                            <option value="{{ $statusKey }}">
                                                {{ $statusLabel }}
                                                @if($statusKey === 'cancelled') ⚠️ @endif
                                            </option>
                                        @endif
                                    @endforeach
                                </select>
                            </div>
                            <div class="col-md-4">
                                <button type="submit" class="btn btn-primary w-100" id="sellerStatusBtn" disabled>
                                    <i class="bi bi-check me-1"></i> Mettre à jour
                                </button>
                            </div>
                        </form>
                        <script>
                            document.getElementById('sellerStatusSelect').addEventListener('change', function() {
                                document.getElementById('sellerStatusBtn').disabled = !this.value;
                                if (this.value === 'cancelled') {
                                    if (!confirm('⚠️ ATTENTION: L\'annulation est définitive et ne peut pas être annulée. Continuer?')) {
                                        this.value = '';
                                        document.getElementById('sellerStatusBtn').disabled = true;
                                    }
                                }
                            });
                        </script>
                    @endif
                </div>
            </div>

            <!-- Preuve de livraison -->
            <div class="card">
                <div class="card-header bg-white d-flex justify-content-between align-items-center">
                    <h5 class="mb-0"><i class="bi bi-truck me-2"></i>Preuve de livraison</h5>
                    @php
                        $proofStatusBadges = [
                            'none' => 'bg-secondary',
                            'submitted' => 'bg-warning text-dark',
                            'approved' => 'bg-success',
                            'rejected' => 'bg-danger'
                        ];
                        $proofStatusLabels = [
                            'none' => 'Non soumise',
                            'submitted' => 'En attente de validation',
                            'approved' => 'Approuvée',
                            'rejected' => 'Rejetée'
                        ];
                    @endphp
                    <span class="badge {{ $proofStatusBadges[$order->delivery_proof_status ?? 'none'] }}">
                        {{ $proofStatusLabels[$order->delivery_proof_status ?? 'none'] }}
                    </span>
                </div>
                <div class="card-body">
                    @if($order->delivery_proof_status === 'approved')
                        <div class="alert alert-success mb-3">
                            <i class="bi bi-check-circle me-2"></i>
                            Preuve de livraison approuvée le {{ $order->delivery_confirmed_at ? \Carbon\Carbon::parse($order->delivery_confirmed_at)->format('d/m/Y à H:i') : '-' }}
                            @if($order->deliveryConfirmedBy)
                                par {{ $order->deliveryConfirmedBy->name }}
                            @endif
                        </div>
                    @elseif($order->delivery_proof_status === 'rejected')
                        <div class="alert alert-danger mb-3">
                            <i class="bi bi-x-circle me-2"></i>
                            <strong>Preuve rejetée.</strong> Veuillez soumettre une nouvelle preuve.
                            @if($order->delivery_proof_notes && str_contains($order->delivery_proof_notes, 'REJETÉ:'))
                                <br><small>{{ str_replace('REJETÉ: ', '', $order->delivery_proof_notes) }}</small>
                            @endif
                        </div>
                    @endif

                    @if($order->delivery_proof)
                        <div class="mb-3">
                            <label class="form-label text-muted">Preuve actuelle</label>
                            <div class="border rounded p-3 bg-light">
                                @php
                                    $extension = pathinfo($order->delivery_proof, PATHINFO_EXTENSION);
                                @endphp
                                @if(in_array(strtolower($extension), ['jpg', 'jpeg', 'png', 'gif']))
                                    <img src="{{ asset('storage/' . $order->delivery_proof) }}" class="img-fluid rounded mb-2" style="max-height: 200px;">
                                @endif
                                <div>
                                    <a href="{{ asset('storage/' . $order->delivery_proof) }}" target="_blank" class="btn btn-outline-primary btn-sm">
                                        <i class="bi bi-eye me-1"></i> Voir la preuve
                                    </a>
                                    <a href="{{ asset('storage/' . $order->delivery_proof) }}" download class="btn btn-outline-secondary btn-sm">
                                        <i class="bi bi-download me-1"></i> Télécharger
                                    </a>
                                </div>
                                @if($order->delivery_proof_notes && !str_contains($order->delivery_proof_notes, 'REJETÉ:'))
                                    <p class="mt-2 mb-0 text-muted small"><i class="bi bi-chat-text me-1"></i>{{ $order->delivery_proof_notes }}</p>
                                @endif
                                @if($order->delivery_proof_submitted_at)
                                    <small class="text-muted d-block mt-2">
                                        <i class="bi bi-clock me-1"></i>Soumise le {{ \Carbon\Carbon::parse($order->delivery_proof_submitted_at)->format('d/m/Y à H:i') }}
                                    </small>
                                @endif
                            </div>
                        </div>
                    @endif

                    @if(in_array($order->status, ['shipped', 'delivered']) && $order->delivery_proof_status !== 'approved')
                        <form action="{{ route('seller.orders.upload-delivery-proof', $order) }}" method="POST" enctype="multipart/form-data">
                            @csrf
                            <div class="mb-3">
                                <label class="form-label fw-bold">
                                    {{ $order->delivery_proof ? 'Soumettre une nouvelle preuve' : 'Télécharger une preuve de livraison' }}
                                </label>
                                <input type="file" name="delivery_proof" class="form-control" accept=".jpg,.jpeg,.png,.pdf" required>
                                <small class="text-muted">Photo du colis livré, signature client, bon de livraison (JPG, PNG, PDF - max 10MB)</small>
                            </div>
                            <div class="mb-3">
                                <label class="form-label">Notes (optionnel)</label>
                                <textarea name="notes" class="form-control" rows="2" placeholder="Détails sur la livraison..."></textarea>
                            </div>
                            <button type="submit" class="btn btn-success">
                                <i class="bi bi-upload me-1"></i> Soumettre la preuve
                            </button>
                        </form>
                    @elseif(!in_array($order->status, ['shipped', 'delivered']))
                        <div class="alert alert-info mb-0">
                            <i class="bi bi-info-circle me-2"></i>
                            Vous pourrez soumettre une preuve de livraison après avoir marqué la commande comme expédiée.
                        </div>
                    @endif

                    <div class="alert alert-secondary mt-3 mb-0">
                        <small>
                            <i class="bi bi-clock me-1"></i>
                            <strong>Délai Z:</strong> Après {{ $delayZ ?? 7 }} jours sans action du client, la commande sera automatiquement validée comme livrée.
                        </small>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-4">
            <!-- Informations client -->
            <div class="card mb-4">
                <div class="card-header bg-white">
                    <h5 class="mb-0"><i class="bi bi-person me-2"></i>Client</h5>
                </div>
                <div class="card-body">
                    <p class="mb-2"><strong>Nom:</strong> {{ $order->customer_name ?? $order->user->name ?? '-' }}</p>
                    <p class="mb-2"><strong>Email:</strong> {{ $order->customer_email ?? $order->user->email ?? '-' }}</p>
                    <p class="mb-2"><strong>Tél:</strong> {{ $order->customer_phone ?? $order->user->phone ?? '-' }}</p>
                </div>
            </div>

            <!-- Adresse de livraison -->
            <div class="card mb-4">
                <div class="card-header bg-white">
                    <h5 class="mb-0"><i class="bi bi-geo-alt me-2"></i>Adresse de livraison</h5>
                </div>
                <div class="card-body">
                    <p class="mb-0">{{ $order->shipping_address ?? '-' }}</p>
                    @if($order->shipping_district)
                        <p class="mb-0 text-muted">{{ $order->shipping_district }}</p>
                    @endif
                    @if($order->shipping_city)
                        <p class="mb-0 text-muted">{{ $order->shipping_city }}, {{ $order->shipping_country ?? '' }}</p>
                    @endif
                </div>
            </div>

            <!-- Paiement -->
            <div class="card mb-4">
                <div class="card-header bg-white">
                    <h5 class="mb-0"><i class="bi bi-credit-card me-2"></i>Paiement</h5>
                </div>
                <div class="card-body">
                    <p class="mb-2">
                        <strong>Statut:</strong>
                        @if($order->payment_status === 'paid')
                            <span class="badge bg-success">Payé</span>
                        @elseif($order->payment_status === 'pending')
                            <span class="badge bg-warning text-dark">En attente</span>
                        @else
                            <span class="badge bg-secondary">{{ $order->payment_status }}</span>
                        @endif
                    </p>
                    <p class="mb-0"><strong>Méthode:</strong> {{ ucfirst($order->payment_method ?? '-') }}</p>
                </div>
            </div>

            <!-- Chronologie -->
            <div class="card">
                <div class="card-header bg-white">
                    <h5 class="mb-0"><i class="bi bi-calendar me-2"></i>Chronologie</h5>
                </div>
                <div class="card-body">
                    <ul class="list-unstyled mb-0">
                        <li class="mb-2 pb-2 border-bottom">
                            <small class="text-muted">Commandée le</small><br>
                            <i class="bi bi-check-circle text-success me-1"></i>{{ $order->created_at->format('d/m/Y à H:i') }}
                        </li>
                        @if($order->shipped_at)
                        <li class="mb-2 pb-2 border-bottom">
                            <small class="text-muted">Expédiée le</small><br>
                            <i class="bi bi-check-circle text-success me-1"></i>{{ \Carbon\Carbon::parse($order->shipped_at)->format('d/m/Y à H:i') }}
                        </li>
                        @endif
                        @if($order->delivered_at)
                        <li class="mb-2 pb-2 border-bottom">
                            <small class="text-muted">Livrée le</small><br>
                            <i class="bi bi-check-circle text-success me-1"></i>{{ \Carbon\Carbon::parse($order->delivered_at)->format('d/m/Y à H:i') }}
                        </li>
                        @endif
                        @if($order->delivery_proof_submitted_at)
                        <li class="mb-2">
                            <small class="text-muted">Preuve soumise le</small><br>
                            <i class="bi bi-upload text-primary me-1"></i>{{ \Carbon\Carbon::parse($order->delivery_proof_submitted_at)->format('d/m/Y à H:i') }}
                        </li>
                        @endif
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>
@endsection
