@extends('bo.layouts.backend')

@section('title', 'Finance 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">Finance BO</h1>
                    <h2 class="fs-base lh-base fw-medium text-muted mb-0 bo-page-subtitle">
                        Paiements clients, retraits liners et supervision des statuts.
                    </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" aria-current="page">Finance</li>
                    </ol>
                </nav>
            </div>
            <div class="bo-hero-actions">
                <a href="{{ route('bo.dashboard') }}" class="btn btn-sm btn-alt-secondary">
                    <i class="si si-speedometer me-1"></i> Tableau de bord
                </a>
                <a href="{{ route('bo.payouts.index') }}" class="btn btn-sm btn-alt-primary">
                    <i class="si si-wallet me-1"></i> Retraits
                </a>
                <a href="{{ route('bo.missions.index') }}" class="btn btn-sm btn-alt-secondary">
                    <i class="si si-briefcase me-1"></i> Missions
                </a>
            </div>
        </div>
    </div>

    <div class="content bo-page-content">
        @if (session('status'))
            <div class="alert alert-success d-flex align-items-center" role="alert">
                <i class="fa fa-check-circle me-2"></i>
                <p class="mb-0">{{ session('status') }}</p>
            </div>
        @endif

        @if ($errors->any())
            <div class="alert alert-danger d-flex align-items-center" role="alert">
                <i class="fa fa-triangle-exclamation me-2"></i>
                <p class="mb-0">{{ $errors->first() }}</p>
            </div>
        @endif

        <div class="row items-push">
            <div class="col-sm-6 col-xxl-2">
                <div class="block block-rounded h-100 mb-0 bo-kpi-card">
                    <div class="block-content block-content-full">
                        <div class="fs-sm fw-medium text-muted mb-1">Paiements encaisses</div>
                        <div class="fs-4 fw-semibold">{{ number_format($summary['payments_paid'], 2, ',', ' ') }} €</div>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xxl-2">
                <div class="block block-rounded h-100 mb-0 bo-kpi-card">
                    <div class="block-content block-content-full">
                        <div class="fs-sm fw-medium text-muted mb-1">Paiements en attente</div>
                        <div class="fs-4 fw-semibold">{{ number_format($summary['payments_pending'], 2, ',', ' ') }} €</div>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xxl-2">
                <div class="block block-rounded h-100 mb-0 bo-kpi-card">
                    <div class="block-content block-content-full">
                        <div class="fs-sm fw-medium text-muted mb-1">Paiements en echec</div>
                        <div class="fs-4 fw-semibold">{{ $summary['payments_failed'] }}</div>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xxl-2">
                <div class="block block-rounded h-100 mb-0 bo-kpi-card">
                    <div class="block-content block-content-full">
                        <div class="fs-sm fw-medium text-muted mb-1">Retraits verses</div>
                        <div class="fs-4 fw-semibold">{{ number_format($summary['payouts_paid'], 2, ',', ' ') }} €</div>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xxl-2">
                <div class="block block-rounded h-100 mb-0 bo-kpi-card">
                    <div class="block-content block-content-full">
                        <div class="fs-sm fw-medium text-muted mb-1">Retraits en attente</div>
                        <div class="fs-4 fw-semibold">{{ number_format($summary['payouts_pending'], 2, ',', ' ') }} €</div>
                    </div>
                </div>
            </div>
            <div class="col-sm-6 col-xxl-2">
                <div class="block block-rounded h-100 mb-0 bo-kpi-card">
                    <div class="block-content block-content-full">
                        <div class="fs-sm fw-medium text-muted mb-1">Retraits en echec</div>
                        <div class="fs-4 fw-semibold">{{ $summary['payouts_failed'] }}</div>
                    </div>
                </div>
            </div>
        </div>

        @php
            $mask = function (?string $value): string {
                $value = trim((string) $value);
                if ($value === '') {
                    return 'Non configure';
                }
                $visible = min(6, strlen($value));
                return str_repeat('•', max(0, strlen($value) - $visible)) . substr($value, -$visible);
            };
        @endphp

        <div class="block block-rounded">
            <div class="block-header block-header-default">
                <h3 class="block-title"><i class="si si-settings me-1"></i>Configuration des passerelles (Stripe / PayPal)</h3>
                <div class="block-options">
                    <span class="badge {{ ($gatewaySettings['simulate'] ?? true) ? 'bg-warning text-dark' : 'bg-success' }}">
                        {{ ($gatewaySettings['simulate'] ?? true) ? 'Simulation active' : 'Production active' }}
                    </span>
                </div>
            </div>
            <div class="block-content">
                <div class="alert alert-info py-2">
                    Les valeurs affichees sont lues en priorite depuis <code>.env</code>
                    (<code>LINEUP_*</code> / <code>PAYPAL_*</code> / <code>STRIPE_*</code>).
                </div>
                <div class="alert alert-warning py-2">
                    Stripe / PayPal / simulate sont forces depuis <code>.env</code> et sont affiches ci-dessous en lecture seule.
                </div>
                <form method="POST" action="{{ route('bo.finance.gateway_settings.update') }}">
                    @csrf
                    <div class="row g-3">
                        <div class="col-12">
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="simulate" value="1"
                                    @checked((bool) ($gatewaySettings['simulate'] ?? true)) disabled>
                                <label class="form-check-label" for="simulate">
                                    Mode simulation paiements (force via .env)
                                </label>
                            </div>
                        </div>

                        <div class="col-12">
                            <hr class="my-2">
                            <h4 class="fs-base fw-semibold mb-3">Stripe</h4>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="stripe_secret_key">Cle secrete Stripe</label>
                            <input id="stripe_secret_key" name="stripe_secret_key" class="form-control"
                                placeholder="sk_live_..."
                                value="{{ old('stripe_secret_key', $gatewaySettings['stripe']['secret_key'] ?? '') }}"
                                readonly>
                            <small class="text-muted d-block mt-1">Actuel: {{ $mask(($gatewaySettings['stripe']['secret_key'] ?? '')) }}</small>
                        </div>
                        <div class="col-md-6">
                            <label class="form-label" for="stripe_webhook_secret">Secret webhook Stripe</label>
                            <input id="stripe_webhook_secret" name="stripe_webhook_secret" class="form-control"
                                placeholder="whsec_..."
                                value="{{ old('stripe_webhook_secret', $gatewaySettings['stripe']['webhook_secret'] ?? '') }}"
                                readonly>
                            <small class="text-muted d-block mt-1">Actuel: {{ $mask(($gatewaySettings['stripe']['webhook_secret'] ?? '')) }}</small>
                        </div>

                        <div class="col-12">
                            <hr class="my-2">
                            <h4 class="fs-base fw-semibold mb-3">PayPal</h4>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label" for="paypal_mode">Mode PayPal</label>
                            <select id="paypal_mode" name="paypal_mode" class="form-select" disabled>
                                <option value="sandbox" @selected(old('paypal_mode', $gatewaySettings['paypal']['mode'] ?? 'sandbox') === 'sandbox')>sandbox</option>
                                <option value="live" @selected(old('paypal_mode', $gatewaySettings['paypal']['mode'] ?? 'sandbox') === 'live')>live</option>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label" for="paypal_client_id">ID client PayPal</label>
                            <input id="paypal_client_id" name="paypal_client_id" class="form-control"
                                value="{{ old('paypal_client_id', $gatewaySettings['paypal']['client_id'] ?? '') }}"
                                readonly>
                            <small class="text-muted d-block mt-1">Actuel: {{ $mask(($gatewaySettings['paypal']['client_id'] ?? '')) }}</small>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label" for="paypal_client_secret">Secret client PayPal</label>
                            <input id="paypal_client_secret" name="paypal_client_secret" class="form-control"
                                value="{{ old('paypal_client_secret', $gatewaySettings['paypal']['client_secret'] ?? '') }}"
                                readonly>
                            <small class="text-muted d-block mt-1">Actuel: {{ $mask(($gatewaySettings['paypal']['client_secret'] ?? '')) }}</small>
                        </div>
                        <div class="col-md-3">
                            <label class="form-label" for="paypal_webhook_id">ID webhook PayPal</label>
                            <input id="paypal_webhook_id" name="paypal_webhook_id" class="form-control"
                                value="{{ old('paypal_webhook_id', $gatewaySettings['paypal']['webhook_id'] ?? '') }}"
                                readonly>
                            <small class="text-muted d-block mt-1">Actuel: {{ $mask(($gatewaySettings['paypal']['webhook_id'] ?? '')) }}</small>
                        </div>

                        <div class="col-12">
                            <button type="submit" class="btn btn-alt-primary">
                                <i class="fa fa-floppy-disk opacity-50 me-1"></i> Enregistrer la configuration
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>

        <div class="block block-rounded">
            <div class="block-header block-header-default">
                <h3 class="block-title"><i class="si si-equalizer me-1"></i>Filtres</h3>
                <div class="block-options">
                    <a href="{{ route('bo.finance') }}" class="btn btn-sm btn-alt-secondary">
                        <i class="fa fa-rotate-left opacity-50 me-1"></i> Reinitialiser
                    </a>
                </div>
            </div>
            <div class="block-content">
                <form class="row g-3 align-items-end bo-filter-form" method="GET" action="{{ route('bo.finance') }}">
                    <div class="col-md-4">
                        <label class="form-label" for="payment_status">Filtre paiements</label>
                        <select id="payment_status" class="form-select" name="payment_status">
                            <option value="">Tous</option>
                            <option value="paid" @selected($paymentStatus === 'paid')>Paye</option>
                            <option value="pending" @selected($paymentStatus === 'pending')>En attente</option>
                            <option value="failed" @selected($paymentStatus === 'failed')>Echoue</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label" for="payout_status">Filtre retraits</label>
                        <select id="payout_status" class="form-select" name="payout_status">
                            <option value="">Tous</option>
                            <option value="paid" @selected($payoutStatus === 'paid')>Paye</option>
                            <option value="pending" @selected($payoutStatus === 'pending')>En attente</option>
                            <option value="failed" @selected($payoutStatus === 'failed')>Echoue</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label class="form-label" for="liner_id">Liner ID</label>
                        <input id="liner_id" class="form-control" type="number" min="1" name="liner_id" value="{{ $linerId > 0 ? $linerId : '' }}" placeholder="Ex: 12">
                    </div>
                    <div class="col-md-12 bo-filter-actions">
                        <button type="submit" class="btn btn-alt-primary">
                            <i class="fa fa-filter opacity-50 me-1"></i> Appliquer filtres
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="row items-push">
            <div class="col-xxl-6">
                <div class="block block-rounded mb-0">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-credit-card me-1"></i>Paiements clients</h3>
                    </div>
                    <div class="block-content p-0">
                        <div class="table-responsive">
                            <table class="table table-vcenter table-striped table-hover fs-sm mb-0 bo-table">
                                <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Mission</th>
                                    <th>Client</th>
                                    <th>Liner</th>
                                    <th>Montant</th>
                                    <th>Fournisseur</th>
                                    <th>Statut</th>
                                    <th style="width: 240px;">Actions</th>
                                </tr>
                                </thead>
                                <tbody>
                                @forelse($payments as $payment)
                                    <tr>
                                        <td>#{{ $payment->id }}</td>
                                        <td>{{ $payment->mission?->title ?? '-' }}</td>
                                        <td>{{ $payment->client?->name ?? '-' }}</td>
                                        <td>{{ $payment->liner?->name ?? '-' }}</td>
                                        <td>{{ number_format((float) $payment->amount, 2, ',', ' ') }} {{ $payment->currency }}</td>
                                        <td>
                                            <div>{{ strtoupper($payment->provider ?? '-') }}</div>
                                            @if($hasPaymentMethodsTable && $payment->paymentMethod)
                                                <small class="text-muted">{{ $payment->paymentMethod->label }} ({{ strtoupper($payment->paymentMethod->provider) }})</small>
                                            @endif
                                            @if($payment->provider_reference)
                                                <small class="d-block text-muted">{{ $payment->provider_reference }}</small>
                                            @endif
                                        </td>
                                        <td>
                                            @php
                                                $paymentBadgeClass = match ($payment->status) {
                                                    'paid' => 'bg-success',
                                                    'failed' => 'bg-danger',
                                                    default => 'bg-warning text-dark',
                                                };
                                                $paymentStatusLabel = match ($payment->status) {
                                                    'paid' => 'Paye',
                                                    'pending' => 'En attente',
                                                    'failed' => 'Echoue',
                                                    default => ucfirst(str_replace('_', ' ', (string) $payment->status)),
                                                };
                                            @endphp
                                            <span class="badge {{ $paymentBadgeClass }}">{{ $paymentStatusLabel }}</span>
                                            @if($payment->failure_reason)
                                                <small class="d-block text-danger mt-1">{{ $payment->failure_reason }}</small>
                                            @endif
                                        </td>
                                        <td>
                                            <div class="bo-table-actions">
                                                @if($payment->mission_id)
                                                    <form method="POST" action="{{ route('bo.finance.payments.retry', $payment) }}">
                                                        @csrf
                                                        <button class="btn btn-sm btn-alt-primary" type="submit">
                                                        <i class="fa fa-rotate me-1"></i>Reessayer
                                                        </button>
                                                    </form>
                                                @endif
                                                <form method="POST" action="{{ route('bo.finance.payments.mark_paid', $payment) }}">
                                                    @csrf
                                                    <button class="btn btn-sm btn-success" type="submit">
                                                        <i class="fa fa-check me-1"></i>Marquer paye
                                                    </button>
                                                </form>
                                                <form method="POST" action="{{ route('bo.finance.payments.mark_failed', $payment) }}" class="d-flex gap-2">
                                                    @csrf
                                                    <input class="form-control form-control-sm" type="text" name="reason" placeholder="Motif">
                                                    <button class="btn btn-sm btn-danger" type="submit">
                                                        <i class="fa fa-xmark me-1"></i>Marquer en echec
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="8" class="text-center text-muted">Aucun paiement.</td>
                                    </tr>
                                @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="block-content">
                        {{ $payments->links() }}
                    </div>
                </div>
            </div>

            <div class="col-xxl-6">
                <div class="block block-rounded mb-0">
                    <div class="block-header block-header-default">
                        <h3 class="block-title"><i class="si si-wallet me-1"></i>Retraits liners</h3>
                        @if($linerId > 0)
                            <div class="block-options">
                                <span class="badge bg-info">Filtre liner #{{ $linerId }}</span>
                            </div>
                        @endif
                    </div>
                    <div class="block-content p-0">
                        <div class="table-responsive">
                            <table class="table table-vcenter table-striped table-hover fs-sm mb-0 bo-table">
                                <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>Liner</th>
                                    <th>Montant</th>
                                    <th>Fournisseur</th>
                                    <th>Statut</th>
                                    <th style="width: 220px;">Actions</th>
                                </tr>
                                </thead>
                                <tbody>
                                @forelse($payouts as $payout)
                                    <tr id="payout-{{ $payout->id }}">
                                        <td>#{{ $payout->id }}</td>
                                        <td>{{ $payout->liner?->name ?? '-' }}</td>
                                        <td>{{ number_format((float) $payout->amount, 2, ',', ' ') }} {{ $payout->currency }}</td>
                                        <td>
                                            <div>{{ strtoupper($payout->provider ?? '-') }}</div>
                                            @if($hasPaymentMethodsTable && $payout->paymentMethod)
                                                <small class="text-muted">{{ $payout->paymentMethod->label }} ({{ strtoupper($payout->paymentMethod->provider) }})</small>
                                            @endif
                                            @if($payout->provider_reference)
                                                <small class="d-block text-muted">{{ $payout->provider_reference }}</small>
                                            @endif
                                        </td>
                                        <td>
                                            @php
                                                $payoutBadgeClass = match ($payout->status) {
                                                    'paid' => 'bg-success',
                                                    'failed' => 'bg-danger',
                                                    default => 'bg-warning text-dark',
                                                };
                                                $payoutStatusLabel = match ($payout->status) {
                                                    'paid' => 'Paye',
                                                    'pending' => 'En attente',
                                                    'failed' => 'Echoue',
                                                    default => ucfirst(str_replace('_', ' ', (string) $payout->status)),
                                                };
                                            @endphp
                                            <span class="badge {{ $payoutBadgeClass }}">{{ $payoutStatusLabel }}</span>
                                            @if($payout->failure_reason)
                                                <small class="d-block text-danger mt-1">{{ $payout->failure_reason }}</small>
                                            @endif
                                        </td>
                                        <td>
                                            <div class="bo-table-actions">
                                                <form method="POST" action="{{ route('bo.finance.payouts.process', $payout) }}">
                                                    @csrf
                                                    <button class="btn btn-sm btn-alt-primary" type="submit">
                                                        <i class="fa fa-rotate me-1"></i>Traiter
                                                    </button>
                                                </form>
                                                <form method="POST" action="{{ route('bo.finance.payouts.mark_paid', $payout) }}">
                                                    @csrf
                                                    <button class="btn btn-sm btn-success" type="submit">
                                                        <i class="fa fa-check me-1"></i>Marquer paye
                                                    </button>
                                                </form>
                                                <form method="POST" action="{{ route('bo.finance.payouts.mark_failed', $payout) }}" class="d-flex gap-2">
                                                    @csrf
                                                    <input class="form-control form-control-sm" type="text" name="reason" placeholder="Motif" required>
                                                    <button class="btn btn-sm btn-danger" type="submit">
                                                        <i class="fa fa-xmark me-1"></i>Marquer en echec
                                                    </button>
                                                </form>
                                            </div>
                                        </td>
                                    </tr>
                                @empty
                                    <tr>
                                        <td colspan="6" class="text-center text-muted">Aucun retrait.</td>
                                    </tr>
                                @endforelse
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="block-content">
                        {{ $payouts->links() }}
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection
