@extends('bo.layouts.backend')

@section('title', 'Mission BO · LineUp France')

@section('content')
    <div class="bg-body-light bo-page-top">
        <div class="content content-full bo-page-top-content">
            <div class="d-flex flex-column flex-sm-row justify-content-sm-between align-items-sm-center py-2 bo-page-head">
                <div class="flex-grow-1">
                    <h1 class="h3 fw-bold mb-1 bo-page-title">Mission #{{ $mission->id }}</h1>
                    <h2 class="fs-base lh-base fw-medium text-muted mb-0 bo-page-subtitle">Vue detaillee, suivi et moderation des preuves.</h2>
                </div>
                <nav class="flex-shrink-0 mt-3 mt-sm-0 ms-sm-3" aria-label="breadcrumb">
                    <ol class="breadcrumb breadcrumb-alt bo-breadcrumb">
                        <li class="breadcrumb-item">LineUp France</li>
                        <li class="breadcrumb-item"><a href="{{ route('bo.missions.index') }}">Missions</a></li>
                        <li class="breadcrumb-item active" aria-current="page">#{{ $mission->id }}</li>
                    </ol>
                </nav>
            </div>
            <div class="bo-hero-actions">
                <a href="{{ route('bo.missions.index') }}" class="btn btn-sm btn-alt-secondary">
                    <i class="fa fa-arrow-left me-1"></i> Retour liste
                </a>
                <a href="{{ route('bo.missions.edit', $mission) }}" class="btn btn-sm btn-alt-primary">
                    <i class="fa fa-pen me-1"></i> Modifier
                </a>
            </div>
        </div>
    </div>

    <div class="content bo-page-content">
        <div class="row g-4">
            <div class="col-12 col-xl-8">
                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-briefcase me-1"></i>Mission</h3>
                    </div>
                    <div class="block-content">
                        <div class="row g-3">
                            <div class="col-md-6">
                                <div class="fs-sm text-muted">Titre</div>
                                <div class="fw-semibold">{{ $mission->title }}</div>
                            </div>
                            <div class="col-md-6">
                                <div class="fs-sm text-muted">Statut</div>
                                <div class="fw-semibold">{{ ucfirst(str_replace('_', ' ', $mission->status)) }}</div>
                            </div>
                            <div class="col-md-6">
                                <div class="fs-sm text-muted">Lieu</div>
                                <div>{{ $mission->location }}</div>
                            </div>
                            <div class="col-md-6">
                                <div class="fs-sm text-muted">Debut prevu</div>
                                <div>{{ $mission->expected_start_at?->format('d/m/Y H:i') ?? '-' }}</div>
                            </div>
                            <div class="col-md-6">
                                <div class="fs-sm text-muted">Budget</div>
                                <div>{{ number_format((float) $mission->budget_amount, 2, ',', ' ') }} {{ $mission->currency }}</div>
                            </div>
                            <div class="col-md-6">
                                <div class="fs-sm text-muted">Evenement</div>
                                <div>{{ $mission->event_name ?: '-' }}</div>
                            </div>
                            <div class="col-12">
                                <div class="fs-sm text-muted">Description</div>
                                <div>{{ $mission->description ?: '-' }}</div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-shield me-1"></i>Preuves mission</h3>
                        <div class="block-options"><span class="badge bg-primary">{{ $mission->proofs->count() }}</span></div>
                    </div>
                    <div class="block-content">
                        @forelse($mission->proofs as $proof)
                            <div class="border rounded p-3 mb-3">
                                <div class="d-flex flex-column flex-md-row justify-content-between gap-3">
                                    <div>
                                        <div class="fw-semibold">#{{ $proof->id }} · {{ ucfirst($proof->type) }}</div>
                                        <div class="fs-sm text-muted">Envoyee le {{ $proof->created_at?->format('d/m/Y H:i') ?? '-' }} par {{ $proof->liner?->name ?? '-' }}</div>
                                        <div class="mt-2">
                                            <span class="badge {{ $proof->status === 'approved' ? 'bg-success' : ($proof->status === 'rejected' ? 'bg-danger' : 'bg-warning text-dark') }}">{{ ucfirst($proof->status ?? 'pending') }}</span>
                                        </div>
                                        @php
                                            $proofUrl = (string) ($proof->proof_url ?? '');
                                            $proofPath = strtolower(parse_url($proofUrl, PHP_URL_PATH) ?? '');
                                            $isImageProof = str_ends_with($proofPath, '.jpg')
                                                || str_ends_with($proofPath, '.jpeg')
                                                || str_ends_with($proofPath, '.png')
                                                || str_ends_with($proofPath, '.webp');
                                            $isPdfProof = str_ends_with($proofPath, '.pdf');
                                            $proofPayload = is_array($proof->payload) ? $proof->payload : [];
                                        @endphp
                                        @if($proofUrl !== '')
                                            <div class="mt-3">
                                                @if($isImageProof)
                                                    <a href="{{ $proofUrl }}" target="_blank" rel="noopener">
                                                        <img
                                                            src="{{ $proofUrl }}"
                                                            alt="Preuve mission #{{ $proof->id }}"
                                                            style="width: 120px; height: 120px; object-fit: cover; border-radius: 14px; border: 1px solid #E5E7EB;"
                                                        >
                                                    </a>
                                                @else
                                                    <div class="d-inline-flex align-items-center gap-2 px-3 py-2 rounded border bg-body-light">
                                                        <i class="fa {{ $isPdfProof ? 'fa-file-pdf text-danger' : 'fa-file-lines text-primary' }}"></i>
                                                        <span class="small">{{ $isPdfProof ? 'Preuve PDF' : 'Piece jointe' }}</span>
                                                    </div>
                                                @endif
                                            </div>
                                            <div class="d-flex gap-2 mt-2">
                                                <a href="{{ $proofUrl }}" target="_blank" rel="noopener" class="btn btn-sm btn-alt-primary">
                                                    <i class="fa fa-up-right-from-square me-1"></i>Ouvrir
                                                </a>
                                                <a href="{{ $proofUrl }}" target="_blank" rel="noopener" download class="btn btn-sm btn-alt-secondary">
                                                    <i class="fa fa-download me-1"></i>Telecharger
                                                </a>
                                            </div>
                                        @endif
                                        @if(!empty($proofPayload))
                                            <div class="mt-2 small text-muted">
                                                @if(!empty($proofPayload['file_name']))
                                                    <div><strong>Fichier:</strong> {{ $proofPayload['file_name'] }}</div>
                                                @endif
                                                @if(!empty($proofPayload['mime_type']))
                                                    <div><strong>Type MIME:</strong> {{ $proofPayload['mime_type'] }}</div>
                                                @endif
                                                @if(!empty($proofPayload['file_size']))
                                                    <div><strong>Taille:</strong> {{ number_format(((int) $proofPayload['file_size']) / 1024, 1, ',', ' ') }} Ko</div>
                                                @endif
                                            </div>
                                            <pre class="mt-2 p-2 bg-body-light rounded small mb-0">{{ json_encode($proofPayload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) }}</pre>
                                        @endif
                                        @if($proof->review_notes)
                                            <div class="mt-2 small text-muted"><strong>Notes moderation:</strong> {{ $proof->review_notes }}</div>
                                        @endif
                                    </div>
                                    <div class="d-flex flex-column gap-2" style="min-width: 280px;">
                                        <form method="POST" action="{{ route('bo.proofs.approve', $proof) }}" class="d-flex gap-2">
                                            @csrf
                                            <input type="text" name="review_notes" class="form-control" placeholder="Note moderation (optionnel)">
                                            <button type="submit" class="btn btn-success">Valider</button>
                                        </form>
                                        <form method="POST" action="{{ route('bo.proofs.reject', $proof) }}" class="d-flex gap-2">
                                            @csrf
                                            <input type="text" name="review_notes" class="form-control" placeholder="Motif de refus">
                                            <button type="submit" class="btn btn-danger">Refuser</button>
                                        </form>
                                        @if($proof->reviewer)
                                            <div class="small text-muted">Derniere moderation par {{ $proof->reviewer->name }} le {{ $proof->reviewed_at?->format('d/m/Y H:i') ?? '-' }}</div>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        @empty
                            <p class="text-muted mb-0">Aucune preuve pour cette mission.</p>
                        @endforelse
                    </div>
                </div>

                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-clock me-1"></i>Timeline</h3>
                    </div>
                    <div class="block-content">
                        @forelse($mission->statusEvents as $event)
                            <div class="border-start border-3 ps-3 mb-3">
                                <div class="fw-semibold">{{ ucfirst(str_replace('_', ' ', $event->status)) }}</div>
                                <div class="small text-muted">{{ $event->created_at?->format('d/m/Y H:i') ?? '-' }}</div>
                                @if($event->note)
                                    <div class="mt-1">{{ $event->note }}</div>
                                @endif
                                @if($event->latitude && $event->longitude)
                                    <div class="small text-muted mt-1">{{ $event->latitude }}, {{ $event->longitude }}</div>
                                @endif
                            </div>
                        @empty
                            <p class="text-muted mb-0">Aucun evenement de statut.</p>
                        @endforelse
                    </div>
                </div>
            </div>

            <div class="col-12 col-xl-4">
                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-users me-1"></i>Participants</h3>
                    </div>
                    <div class="block-content">
                        <div class="mb-3">
                            <div class="fs-sm text-muted">Client</div>
                            <div class="fw-semibold">{{ $mission->client?->name ?? '-' }}</div>
                            <div class="small text-muted">{{ $mission->client?->email ?? '-' }}</div>
                            <div class="small text-muted">{{ $mission->client?->phone ?? '-' }}</div>
                        </div>
                        <div>
                            <div class="fs-sm text-muted">Liner retenu</div>
                            <div class="fw-semibold">{{ $mission->liner?->name ?? '-' }}</div>
                            <div class="small text-muted">{{ $mission->liner?->email ?? '-' }}</div>
                            <div class="small text-muted">{{ $mission->liner?->phone ?? '-' }}</div>
                        </div>
                    </div>
                </div>

                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-user-following me-1"></i>Candidatures liners</h3>
                        <div class="block-options"><span class="badge bg-primary">{{ $mission->applications->count() }}</span></div>
                    </div>
                    <div class="block-content">
                        @forelse($mission->applications as $application)
                            <div class="border rounded p-3 mb-3">
                                <div class="d-flex justify-content-between align-items-start gap-3">
                                    <div>
                                        <div class="fw-semibold">{{ $application->liner?->name ?? '-' }}</div>
                                        <div class="small text-muted">{{ $application->liner?->email ?? '-' }}</div>
                                        <div class="small text-muted">{{ $application->liner?->phone ?? '-' }}</div>
                                    </div>
                                    <div class="text-end">
                                        <span class="badge {{ $application->status === 'accepted' ? 'bg-success' : ($application->status === 'rejected' ? 'bg-danger' : 'bg-warning text-dark') }}">{{ ucfirst($application->status) }}</span>
                                        <div class="small text-muted mt-2">Postule le {{ $application->created_at?->format('d/m/Y H:i') ?? '-' }}</div>
                                        @if($application->accepted_at)
                                            <div class="small text-success">Acceptee le {{ $application->accepted_at->format('d/m/Y H:i') }}</div>
                                        @endif
                                        @if($application->rejected_at)
                                            <div class="small text-danger">Refusee le {{ $application->rejected_at->format('d/m/Y H:i') }}</div>
                                        @endif
                                    </div>
                                </div>
                                @php
                                    $paymentLocked = in_array(($latestPayment?->status ?? ''), ['pending', 'paid'], true);
                                    $canSelectApplication = in_array($application->status, ['pending', 'rejected'], true) && !$paymentLocked;
                                @endphp
                                @if($canSelectApplication)
                                    <div class="d-flex gap-2 mt-3">
                                        <form method="POST" action="{{ route('bo.missions.applications.accept', [$mission, $application]) }}">
                                            @csrf
                                            <button type="submit" class="btn btn-sm btn-success">
                                                <i class="fa fa-check me-1"></i> {{ $application->status === 'rejected' ? 'Retenir a la place' : 'Accepter ce liner' }}
                                            </button>
                                        </form>
                                        @if($application->status === 'pending')
                                            <form method="POST" action="{{ route('bo.missions.applications.reject', [$mission, $application]) }}">
                                                @csrf
                                                <button type="submit" class="btn btn-sm btn-danger">
                                                    <i class="fa fa-times me-1"></i> Refuser
                                                </button>
                                            </form>
                                        @endif
                                    </div>
                                @elseif($application->status === 'accepted')
                                    <div class="small text-success mt-3">Liner retenu pour cette mission.</div>
                                @elseif($paymentLocked)
                                    <div class="small text-muted mt-3">Selection verrouillee car un paiement est deja en attente ou confirme.</div>
                                @endif
                            </div>
                        @empty
                            <p class="text-muted mb-0">Aucune candidature pour cette mission.</p>
                        @endforelse
                    </div>
                </div>

                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-wallet me-1"></i>Paiement mission</h3>
                    </div>
                    <div class="block-content">
                        @if($latestPayment)
                            <div class="border rounded p-3">
                                <div class="d-flex justify-content-between align-items-start gap-3">
                                    <div>
                                        <div class="fw-semibold">{{ number_format((float) $latestPayment->amount, 2, ',', ' ') }} {{ $latestPayment->currency }}</div>
                                        <div class="small text-muted">Provider: {{ $latestPayment->provider ?? '-' }}</div>
                                        <div class="small text-muted">Methode: {{ $latestPayment->paymentMethod?->label ?? '-' }}</div>
                                        @if($latestPayment->provider_reference)
                                            <div class="small text-muted">Reference: {{ $latestPayment->provider_reference }}</div>
                                        @endif
                                        @if($latestPayment->failure_reason)
                                            <div class="small text-danger">Echec: {{ $latestPayment->failure_reason }}</div>
                                        @endif
                                    </div>
                                    <div class="text-end">
                                        <span class="badge {{ $latestPayment->status === 'paid' ? 'bg-success' : ($latestPayment->status === 'failed' ? 'bg-danger' : 'bg-warning text-dark') }}">{{ strtoupper($latestPayment->status) }}</span>
                                        <div class="small text-muted mt-2">Cree le {{ $latestPayment->created_at?->format('d/m/Y H:i') ?? '-' }}</div>
                                        <div class="small text-muted">Validation client: {{ $mission->client_validated_at?->format('d/m/Y H:i') ?? 'non' }}</div>
                                        @if($latestPayment->paid_at)
                                            <div class="small text-success">Paye le {{ $latestPayment->paid_at->format('d/m/Y H:i') }}</div>
                                        @endif
                                    </div>
                                </div>
                            </div>
                        @else
                            <p class="text-muted mb-0">Aucun paiement rattache a cette mission.</p>
                        @endif
                    </div>
                </div>

                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-credit-card me-1"></i>Retraits liner</h3>
                        @if($mission->liner_id)
                            <div class="block-options">
                                <a href="{{ route('bo.finance', ['liner_id' => $mission->liner_id]) }}" class="btn btn-sm btn-alt-primary">
                                    <i class="si si-wallet me-1"></i> Voir finance filtree
                                </a>
                            </div>
                        @endif
                    </div>
                    <div class="block-content">
                        @if($linerPayouts->isNotEmpty())
                            @foreach($linerPayouts as $payout)
                                <div class="border rounded p-3 mb-3">
                                    <div class="d-flex justify-content-between align-items-start gap-3">
                                        <div>
                                            <div class="fw-semibold">{{ number_format((float) $payout->amount, 2, ',', ' ') }} {{ $payout->currency }}</div>
                                            <div class="small text-muted">Provider: {{ $payout->provider ?? '-' }}</div>
                                            <div class="small text-muted">Methode: {{ $payout->paymentMethod?->label ?? '-' }}</div>
                                            @if($payout->provider_reference)
                                                <div class="small text-muted">Reference: {{ $payout->provider_reference }}</div>
                                                <div class="mt-2">
                                                    <a href="{{ route('bo.finance', ['liner_id' => $mission->liner_id]) }}#payout-{{ $payout->id }}" class="btn btn-sm btn-alt-secondary">
                                                        <i class="si si-wallet me-1"></i> Ouvrir dans Finance
                                                    </a>
                                                </div>
                                            @endif
                                            @if($payout->failure_reason)
                                                <div class="small text-danger">Echec: {{ $payout->failure_reason }}</div>
                                            @endif
                                        </div>
                                        <div class="text-end">
                                            <span class="badge {{ $payout->status === 'paid' ? 'bg-success' : ($payout->status === 'failed' ? 'bg-danger' : 'bg-warning text-dark') }}">{{ strtoupper($payout->status) }}</span>
                                            <div class="small text-muted mt-2">Demande le {{ $payout->requested_at?->format('d/m/Y H:i') ?? $payout->created_at?->format('d/m/Y H:i') ?? '-' }}</div>
                                            @if($payout->paid_at)
                                                <div class="small text-success">Paye le {{ $payout->paid_at->format('d/m/Y H:i') }}</div>
                                            @endif
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                        @elseif($mission->liner_id)
                            <p class="text-muted mb-0">Aucun retrait recent pour ce liner.</p>
                        @else
                            <p class="text-muted mb-0">Aucun liner retenu sur cette mission.</p>
                        @endif
                    </div>
                </div>

                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-list me-1"></i>Transactions wallet liner</h3>
                    </div>
                    <div class="block-content">
                        @if($linerWalletTransactions->isNotEmpty())
                            @foreach($linerWalletTransactions as $transaction)
                                <div class="border rounded p-3 mb-3">
                                    <div class="d-flex justify-content-between align-items-start gap-3">
                                        <div>
                                            <div class="fw-semibold">{{ ucfirst($transaction->type) }} · {{ number_format((float) $transaction->amount, 2, ',', ' ') }} €</div>
                                            <div class="small text-muted">{{ $transaction->description ?: 'Transaction wallet' }}</div>
                                            <div class="small text-muted">Ref: {{ class_basename((string) $transaction->reference_type) }} #{{ $transaction->reference_id ?? '-' }}</div>
                                        </div>
                                        <div class="text-end">
                                            <span class="badge {{ $transaction->type === 'credit' ? 'bg-success' : 'bg-warning text-dark' }}">{{ strtoupper($transaction->type) }}</span>
                                            <div class="small text-muted mt-2">{{ $transaction->created_at?->format('d/m/Y H:i') ?? '-' }}</div>
                                        </div>
                                    </div>
                                </div>
                            @endforeach
                        @elseif($mission->liner_id)
                            <p class="text-muted mb-0">Aucune transaction wallet recente pour ce liner.</p>
                        @else
                            <p class="text-muted mb-0">Aucun liner retenu sur cette mission.</p>
                        @endif
                    </div>
                </div>

                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-star me-1"></i>Evaluation client</h3>
                    </div>
                    <div class="block-content">
                        @if($missionRating)
                            <div class="border rounded p-3">
                                <div class="d-flex justify-content-between align-items-start gap-3">
                                    <div>
                                        <div class="fw-semibold">{{ $missionRating->stars }}/5</div>
                                        <div class="small text-muted">Laissee le {{ $missionRating->created_at?->format('d/m/Y H:i') ?? '-' }}</div>
                                        <div class="small text-muted">Client #{{ $missionRating->client_id }} · Liner #{{ $missionRating->liner_id }}</div>
                                    </div>
                                    <span class="badge bg-warning text-dark">Note mission</span>
                                </div>
                                <div class="mt-3">
                                    {{ $missionRating->comment ?: 'Aucun commentaire laisse.' }}
                                </div>
                            </div>
                        @else
                            <p class="text-muted mb-0">Aucune evaluation client pour cette mission.</p>
                        @endif
                    </div>
                </div>

                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-info me-1"></i>Litiges</h3>
                    </div>
                    <div class="block-content">
                        @forelse($mission->disputes as $dispute)
                            <div class="border rounded p-3 mb-3">
                                <div class="fw-semibold">{{ ucfirst(str_replace('_', ' ', $dispute->category ?? 'litige')) }}</div>
                                <div class="small text-muted">{{ $dispute->created_at?->format('d/m/Y H:i') ?? '-' }} · {{ $dispute->reporter?->name ?? '-' }}</div>
                                <div class="mt-2">{{ $dispute->description }}</div>
                                <div class="mt-2"><span class="badge bg-secondary">{{ ucfirst($dispute->status ?? 'open') }}</span></div>
                            </div>
                        @empty
                            <p class="text-muted mb-0">Aucun litige.</p>
                        @endforelse
                    </div>
                </div>

                <div class="block block-rounded">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-bubbles me-1"></i>Derniers messages</h3>
                    </div>
                    <div class="block-content">
                        @forelse($mission->messages as $message)
                            <div class="border rounded p-3 mb-3">
                                <div class="small text-muted">{{ $message->created_at?->format('d/m/Y H:i') ?? '-' }}</div>
                                <div class="mt-1">{{ $message->message }}</div>
                            </div>
                        @empty
                            <p class="text-muted mb-0">Aucun message recent.</p>
                        @endforelse
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
