{% extends '@CpCreationVitiCore/admin/base.html.twig' %}

{% block content %}
    {% set pricing = cart.getPricing %}
    {% set cart_checkout = cart.cartCheckout %}
    {% set invoice = cart.invoice %}
    {% set invoice_address = cart.invoiceAddress %}
    {% set delivery_address = cart.deliveryAddress %}
    {% set billing_address = invoice_address ?: delivery_address %}
    {% set use_shipping_address = cart.deliveryMethod is null or cart.deliveryMethod.category is null or not cart.deliveryMethod.category.disabledShippingAddress %}
    {% set checkout_status = cart.checkoutStatus %}
    {% set effective_payment_method = cart.paymentMethod ?: (cart_checkout ? cart_checkout.paymentMethod : null) %}
    {% set is_online_payment = effective_payment_method ? effective_payment_method.checkoutOnlineMethod : true %}
    {% set payment_failure_code = cart.paymentFailureCode %}
    {% set payment_failure_message = cart.paymentFailureMessage %}
    {% set order_comment = cart.comment|default('')|trim %}
    {% set is_order_paid = cart_checkout and cart_checkout.payedAt %}
    {% set can_send_document_email = is_order_paid and (document_label == 'checkout_design.document_order' or document_label == 'checkout_design.document_invoice') %}
    {% set send_document_email_label = document_label == 'checkout_design.document_order' ? 'Renvoyer le bon de commande au client' : (cart.isCheckoutPayed ? 'Renvoyer la facture au client' : 'Envoyer la pro forma au client') %}
    {% set email_type_labels = {
        account_activation: 'Activation de compte',
        password_reset: 'Réinitialisation du mot de passe',
        offline_order_customer: 'Bon de commande client',
        offline_order_admin: 'Bon de commande boutique',
        paid_order_customer: invoice_feature_enabled ? 'Facture client' : 'Bon de commande client',
        paid_order_admin: invoice_feature_enabled ? 'Facture boutique' : 'Bon de commande boutique',
        order_resend_customer: 'Renvoi bon de commande client',
        document_customer: 'Renvoi document client',
        delivery_customer: 'Avis d’expédition',
        credit_customer: 'Avoir client',
        withdrawal_acknowledgement: 'withdrawal.admin.email_type.acknowledgement'|trans,
        withdrawal_admin: 'withdrawal.admin.email_type.notification'|trans
    } %}
    {% set email_status_labels = {
        queued: { label: 'En file', class: 'label-info' },
        retrying: { label: 'Nouvelle tentative', class: 'label-warning' },
        sent: { label: 'Envoyé', class: 'label-success' },
        failed: { label: 'Échec', class: 'label-danger' }
    } %}

    <ol class="breadcrumb">
        <li><a href="{{ path('admin_order') }}">Commandes</a></li>
        <li class="active">Détail</li>
    </ol>

    <div class="page-header" style="margin-top: 0;">
        <div class="row">
            <div class="col-sm-8">
                <h1 style="margin-top: 0;">
                    Commande {{ cart.token ?: 'sans référence' }}
                </h1>
                <p class="text-muted" style="margin-bottom: 0;">
                    {% if cart.firstname or cart.lastname %}
                        {{ cart.firstname }} {{ cart.lastname }}
                    {% else %}
                        Client non renseigné
                    {% endif %}
                </p>
            </div>
            <div class="col-sm-4">
                <div style="display: flex; flex-wrap: wrap; justify-content: flex-end; gap: 8px;">
                    <a href="{{ path('admin_order') }}" class="btn btn-default">
                        Retour à la liste
                    </a>
                    {% if is_order_paid %}
                        <a href="{{ path('admin_order_purchase_order_pdf', { id: cart.id }) }}" class="btn btn-info" target="_blank">
                            {% if document_label == 'checkout_design.document_order' %}
                                Télécharger le bon de commande
                            {% else %}
                                {{ download_document_label|trans({}, 'messages', 'fr') }}
                            {% endif %}
                        </a>
                    {% endif %}
                    {% if can_send_document_email %}
                        <form
                            method="post"
                            action="{{ path('admin_order_send_document_email', { id: cart.id }) }}"
                            style="margin: 0;"
                            {% if document_label == 'checkout_design.document_order' %}
                                data-confirm-submit="true"
                                data-confirm-message="Confirmer le renvoi du bon de commande au client ?"
                            {% endif %}
                        >
                            <input type="hidden" name="_token" value="{{ csrf_token('send-document-email-' ~ cart.id) }}">
                            <button type="submit" class="btn btn-primary">
                                {{ send_document_email_label }}
                            </button>
                        </form>
                    {% endif %}
                    {% if not cart.isCheckoutPayed %}
                        <a href="{{ path('admin_order_redirect_payment', { id: cart.id }) }}" class="btn btn-info" target="_blank">
                            Page de paiement
                        </a>
                        <a
                            href="{{ path('admin_order_delete', { id: cart.id }) }}"
                            class="confirm-deletable btn btn-danger"
                            data-toggle="tooltip"
                            title="Supprimer la commande {{ cart.token ?: 'sans référence' }}"
                            data-title="Supprimer la commande {{ cart.token ?: 'sans référence' }} ?"
                        >
                            Supprimer
                        </a>
                    {% endif %}
                </div>
            </div>
        </div>
    </div>

    {% if cart.withdrawalRequest %}
        {% set withdrawal_request = cart.withdrawalRequest %}
        <div class="alert alert-warning" role="alert" style="margin-top: 20px;">
            <h2 style="margin-top: 0; font-size: 20px;">{{ 'withdrawal.admin.heading'|trans }}</h2>
            <p>
                {{ 'withdrawal.admin.received_on'|trans }} <strong>{{ withdrawal_request.submittedAt|date('d/m/Y H:i:s T') }}</strong>
                {{ 'withdrawal.admin.for_reference'|trans }} <strong>{{ withdrawal_request.contractReference }}</strong>.
            </p>
            <p>
                {{ 'withdrawal.admin.customer'|trans }} : {{ withdrawal_request.firstname }} {{ withdrawal_request.lastname }}<br>
                {{ 'withdrawal.admin.acknowledgement'|trans }} : {{ withdrawal_request.receiptEmail }}
                {% if withdrawal_request.acknowledgedAt %}{{ 'withdrawal.admin.sent_at'|trans({ '%date%': withdrawal_request.acknowledgedAt|date('d/m/Y H:i:s T') }) }}{% endif %}
                <br>{{ 'withdrawal.summary.order_received'|trans }} : {{ (withdrawal_request.orderReceived is same as(true) ? 'withdrawal.form.yes' : (withdrawal_request.orderReceived is same as(false) ? 'withdrawal.form.no' : 'withdrawal.form.not_provided'))|trans }}
                {% if withdrawal_request.orderReceived and withdrawal_request.receivedAt %}
                    <br>{{ 'withdrawal.summary.received_at'|trans }} : {{ withdrawal_request.receivedAt|date('d/m/Y') }}
                {% endif %}
                {% if withdrawal_request.reasonCode %}
                    <br>{{ 'withdrawal.summary.reason'|trans }} : {{ ('withdrawal.reason.' ~ withdrawal_request.reasonCode)|trans }}
                {% endif %}
                {% if withdrawal_request.comment %}
                    <br>{{ 'withdrawal.summary.comment'|trans }} : {{ withdrawal_request.comment|nl2br }}
                {% endif %}
            </p>
            {% if withdrawal_request.processedAt %}
                <p class="text-success" style="margin-bottom: 0;"><strong>{{ 'withdrawal.admin.processed_at'|trans({ '%date%': withdrawal_request.processedAt|date('d/m/Y H:i:s T') }) }}</strong></p>
            {% else %}
                <form method="post" action="{{ path('admin_order_withdrawal_processed', { id: cart.id }) }}" style="margin: 0;">
                    <input type="hidden" name="_token" value="{{ csrf_token('withdrawal-processed-' ~ cart.id) }}">
                    <button type="submit" class="btn btn-warning">{{ 'withdrawal.admin.mark_processed'|trans }}</button>
                </form>
            {% endif %}
        </div>
    {% endif %}

    <div class="row">
        <div class="col-md-9">
            {% if cart.isCheckoutPayed %}
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <strong>Mise en expédition</strong>
                    </div>
                    <div class="panel-body">
                        <p class="text-muted">
                            Marquez la commande comme expédiée pour prévenir le client par email que sa commande a été remise au transporteur.
                            Si le suivi peut être effectué, veuillez renseigner le code de suivi et sélectionner un transporteur pour générer automatiquement l'URL de suivi.
                        </p>

                        <form method="post" action="{{ path('admin_order_delivery', { id: cart.id }) }}">
                            <input type="hidden" name="_token" value="{{ csrf_token('mark-delivery-' ~ cart.id) }}">

                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="tracking_carrier">Transporteur</label>
                                        <select name="tracking_carrier" id="tracking_carrier" class="form-control">
                                            <option value="">Aucun</option>
                                            {% for carrier_key, carrier in tracking_carriers %}
                                                <option value="{{ carrier_key }}" {% if selected_tracking_carrier == carrier_key %}selected{% endif %}>
                                                    {{ carrier.label }}
                                                </option>
                                            {% endfor %}
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label for="code_carrier">Code de suivi</label>
                                        <input
                                            type="text"
                                            name="code_carrier"
                                            id="code_carrier"
                                            class="form-control"
                                            value="{{ cart.codeCarrier }}"
                                            placeholder="Ex. 8X01234567890"
                                        >
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="form-group">
                                        <label>Lien de suivi actuel</label>
                                        <p class="form-control-static" style="word-break: break-all;">
                                            {% if cart.urlDeSuiviCarrier %}
                                                <a href="{{ cart.urlDeSuiviCarrier }}" target="_blank" rel="noopener noreferrer">
                                                    {{ cart.urlDeSuiviCarrier }}
                                                </a>
                                            {% else %}
                                                Aucun lien généré pour le moment.
                                            {% endif %}
                                        </p>
                                    </div>
                                </div>
                            </div>

                            <button type="submit" class="btn btn-primary">
                                {% if cart.isDelivery %}
                                    Mettre à jour l'expédition
                                {% else %}
                                    Marquer la commande comme expédiée
                                {% endif %}
                            </button>
                        </form>
                    </div>
                </div>
            {% endif %}

            <div class="panel panel-default">
                <div class="panel-heading">
                    <strong>Panier</strong>
                </div>
                <div class="panel-body">
                    {% if pricing and pricing.lines is not empty %}
                        {% for line in pricing.lines %}
                            {% set line_previous_ttc = line.isPromoGift ? line.totalTTC : (line.degressiveTTC > 0 ? line.netTTC + line.degressiveTTC : null) %}
                            <div class="row" style="{% if not loop.last %}border-bottom: 1px solid #eee; margin-bottom: 20px; padding-bottom: 20px;{% endif %}">
                                <div class="col-sm-2">
                                    <div style="border: 1px solid #eee; background: #fff; padding: 8px; text-align: center;">
                                        {% if line.imagePath %}
                                            <img
                                                src="{{ asset(line.imagePath)|imagine_filter('relative_heighten_293_filter') }}"
                                                alt="{{ line.productName ? line.productName|upper : 'Produit' }}"
                                                style="max-width: 100%; max-height: 110px; object-fit: contain;"
                                            >
                                        {% else %}
                                            <span class="text-muted">Produit</span>
                                        {% endif %}
                                    </div>
                                </div>
                                <div class="col-sm-7">
                                    <div style="font-size: 16px; font-weight: 600; text-transform: uppercase;">
                                        {{ line.productName ? line.productName|upper : '-' }}
                                    </div>
                                    {% if line.typeName %}
                                        <div class="text-muted" style="margin-top: 6px;">
                                            {{ line.typeName }}{% if line.unitLabel %} ({{ line.unitLabel }}){% endif %}
                                        </div>
                                    {% elseif line.unitLabel %}
                                        <div class="text-muted" style="margin-top: 6px;">
                                            {{ line.unitLabel }}
                                        </div>
                                    {% endif %}
                                    {% if line.optionName %}
                                        <div class="text-muted" style="margin-top: 6px;">
                                            {{ 'shop.option_label'|trans }} : {{ line.optionName }}
                                            {% if line.optionTotalTTC > 0 %}
                                                (+{{ line.optionTotalTTC|price_format }} €{% if line.optionFlatFee %}, {{ 'shop.flat_fee'|trans|lower }}{% endif %})
                                            {% endif %}
                                        </div>
                                    {% endif %}
                                    {% if line.isPromoGift %}
                                        <div style="margin-top: 10px;">
                                            <span class="label label-warning">Offert</span>
                                        </div>
                                    {% endif %}
                                    {% if line.degressiveTTC > 0 %}
                                        <div class="text-muted" style="margin-top: 8px;">
                                            Dégressif : -{{ line.degressiveTTC|price_format }} €
                                        </div>
                                    {% endif %}
                                </div>
                                <div class="col-sm-3 text-right">
                                    <div class="text-muted">x{{ line.quantity }}</div>
                                    <div style="margin-top: 8px; font-size: 16px; font-weight: 600;">
                                        {% if line_previous_ttc is not null and line_previous_ttc > line.netTTC %}
                                            <span class="text-muted" style="text-decoration: line-through; margin-right: 6px;">
                                                {{ line_previous_ttc|price_format }} €
                                            </span>
                                        {% endif %}
                                        {% if line.isPromoGift %}
                                            Offert
                                        {% else %}
                                            {{ line.netTTC|price_format }} €
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        {% endfor %}
                    {% else %}
                        <p class="text-muted" style="margin-bottom: 0;">Ce panier est vide.</p>
                    {% endif %}
                </div>
            </div>

            <div class="panel panel-default">
                <div class="panel-heading">
                    <strong>Totaux</strong>
                </div>
                <div class="panel-body">
                    <table class="table" style="margin-bottom: 0;">
                        <tbody>
                        {% if pricing and pricing.degressiveTTC > 0 %}
                            <tr>
                                <th>{{ pricing.degressiveIsBottleOffered ? 'Bouteille offerte' : 'Dégressif' }}</th>
                                <td class="text-right">-{{ pricing.degressiveTTC|price_format }} €</td>
                            </tr>
                        {% endif %}
                        <tr>
                            <th>Sous-total</th>
                            <td class="text-right">
                                {% if pricing %}{{ pricing.subtotalTTC|price_format }} €{% else %}-{% endif %}
                            </td>
                        </tr>
                        {% for promo in cart.promos %}
                            {% if promo.discountItemsTTC > 0 %}
                                <tr>
                                    <th>Remise{% if promo.code %} - {{ promo.code }}{% endif %}</th>
                                    <td class="text-right">-{{ promo.discountItemsTTC|price_format }} €</td>
                                </tr>
                            {% endif %}
                        {% endfor %}
                        <tr>
                            <th>Livraison</th>
                            <td class="text-right">
                                {% if cart.cartShipping is not null %}
                                    {{ cart.cartShipping.amountTTC|price_format }} €
                                    {% if cart.cartShipping.name %}
                                        <br/><small class="text-muted">{{ cart.cartShipping.name }}</small>
                                    {% endif %}
                                {% else %}
                                    À définir
                                {% endif %}
                            </td>
                        </tr>
                        {% for promo in cart.promos %}
                            {% if promo.discountShippingTTC > 0 %}
                                <tr>
                                    <th>Remise livraison{% if promo.code %} - {{ promo.code }}{% endif %}</th>
                                    <td class="text-right">-{{ promo.discountShippingTTC|price_format }} €</td>
                                </tr>
                            {% endif %}
                        {% endfor %}
                        <tr>
                            <th style="font-size: 16px;">{{ 'shop.total_ttc'|trans }}</th>
                            <td class="text-right" style="font-size: 18px; font-weight: 700;">
                                {% if pricing %}{{ pricing.totalTTC|price_format }} €{% else %}-{% endif %}
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            </div>

            {% if order_comment %}
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <strong>Commentaires de commande</strong>
                    </div>
                    <div class="panel-body">
                        <p style="white-space: normal; margin-bottom: 0;">{{ order_comment|nl2br }}</p>
                    </div>
                </div>
            {% endif %}

            <div class="panel panel-default">
                <div class="panel-heading">
                    <strong>Paiement</strong>
                </div>
                <div class="panel-body">
                    <p>
                        <strong>Méthode :</strong><br>
                        {% if effective_payment_method %}
                            {{ effective_payment_method.method|trans }}
                        {% else %}
                            -
                        {% endif %}
                    </p>
                    <p><strong>Checkout :</strong><br>{% if cart_checkout %}Initialisé{% else %}Non initialisé{% endif %}</p>
                    {% if cart_checkout and cart_checkout.initiatedAt %}
                        <p><strong>Paiement initié le :</strong><br>{{ cart_checkout.initiatedAt|date('d/m/Y H:i') }}</p>
                    {% endif %}
                    {% if cart.abandonedAt %}
                        <p><strong>Panier abandonné le :</strong><br>{{ cart.abandonedAt|date('d/m/Y H:i') }}</p>
                    {% endif %}
                    <p><strong>Document :</strong><br>{{ document_label|trans({}, 'messages', 'fr') }}</p>
                    {% if checkout_status == 'failed' or checkout_status == 'canceled' %}
                        <div class="alert {% if checkout_status == 'failed' %}alert-danger{% else %}alert-warning{% endif %}" style="margin-bottom: 15px;">
                            <strong>{% if checkout_status == 'failed' %}Paiement échoué{% else %}Paiement annulé{% endif %}</strong>
                            {% if payment_failure_code %}
                                <br>Code erreur : {{ payment_failure_code }}
                            {% elseif payment_failure_message %}
                                <br>{{ payment_failure_message }}
                            {% endif %}
                        </div>
                    {% endif %}

                    {% if effective_payment_method and effective_payment_method.method == 'stripe' and cart_checkout and cart_checkout.response is not empty %}
                        {% set stripe_response = cart_checkout.response %}
                        {% set stripe_payment_reference = stripe_response.payment_reference|default(stripe_response.metadata.payment_reference|default(stripe_response.session.metadata.payment_reference|default(null))) %}
                        {% set stripe_customer_id = stripe_response.customer_id|default(stripe_response.session.customer_id|default(stripe_response.session.customer|default(null))) %}
                        {% set stripe_checkout_session = stripe_response.checkout_session_id|default(stripe_response.stripe_checkout_sync.checkout_session_id|default(stripe_response.stripe_checkout_init.checkout_session_id|default(null))) %}
                        {% set stripe_payment_intent = stripe_response.payment_intent|default(stripe_response.object.payment_intent.id|default(stripe_response.session.payment_intent.id|default(null))) %}
                        {% set stripe_checkout_status = stripe_response.status|default(stripe_response.stripe_checkout_sync.status|default(stripe_response.session.status|default(null))) %}
                        {% set stripe_payment_status = stripe_response.payment_status|default(stripe_response.stripe_checkout_sync.payment_status|default(stripe_response.session.payment_status|default(null))) %}
                        {% set stripe_payment_intent_status = stripe_response.payment_intent_status|default(stripe_response.stripe_checkout_sync.payment_intent_status|default(stripe_response.object.payment_intent.status|default(stripe_response.session.payment_intent.status|default(null)))) %}
                        {% set stripe_last_error = stripe_response.last_payment_error.message|default(
                            stripe_response.stripe_checkout_sync.last_payment_error.message|default(
                                stripe_response.object.payment_intent.last_payment_error.message|default(
                                    stripe_response.session.payment_intent.last_payment_error.message|default(
                                        stripe_response.last_payment_error.code|default(
                                            stripe_response.stripe_checkout_sync.last_payment_error.code|default(
                                                stripe_response.object.payment_intent.last_payment_error.code|default(
                                                    stripe_response.session.payment_intent.last_payment_error.code|default(null)
                                                )
                                            )
                                        )
                                    )
                                )
                            )
                        ) %}
                        {% set stripe_synced_at = stripe_response.synced_at|default(stripe_response.stripe_checkout_sync.synced_at|default(null)) %}
                        {% set stripe_livemode = stripe_response.session.livemode|default(stripe_response.object.livemode|default(false)) %}
                        {% set stripe_dashboard_base = stripe_livemode ? 'https://dashboard.stripe.com' : 'https://dashboard.stripe.com/test' %}
                        {% set stripe_checkout_status_labels = {
                            open: 'Ouverte',
                            complete: 'Terminée',
                            expired: 'Expirée'
                        } %}
                        {% set stripe_payment_status_labels = {
                            paid: 'Payé',
                            unpaid: 'Non payé',
                            no_payment_required: 'Aucun paiement requis'
                        } %}
                        {% set stripe_payment_intent_status_labels = {
                            succeeded: 'Réussi',
                            processing: 'En cours de traitement',
                            canceled: 'Annulé',
                            requires_payment_method: 'Moyen de paiement requis',
                            requires_confirmation: 'Confirmation requise',
                            requires_action: 'Action requise',
                            requires_capture: 'Capture requise'
                        } %}

                        <hr>
                        <p><strong>Référence de paiement :</strong><br>{{ stripe_payment_reference ?: '-' }}</p>
                        <p>
                            <strong>Client Stripe :</strong><br>
                            {% if stripe_customer_id %}
                                <a href="{{ stripe_dashboard_base }}/customers/{{ stripe_customer_id }}" target="_blank" rel="noopener noreferrer"><code>{{ stripe_customer_id }}</code></a>
                            {% else %}
                                -
                            {% endif %}
                        </p>
                        <p>
                            <strong>Session Checkout :</strong><br>
                            {% if stripe_checkout_session %}
                                <a href="{{ stripe_dashboard_base }}/payments/checkout/sessions/{{ stripe_checkout_session }}" target="_blank" rel="noopener noreferrer"><code>{{ stripe_checkout_session }}</code></a>
                            {% else %}
                                -
                            {% endif %}
                        </p>
                        <p>
                            <strong>Intention de paiement :</strong><br>
                            {% if stripe_payment_intent %}
                                <a href="{{ stripe_dashboard_base }}/payments/{{ stripe_payment_intent }}" target="_blank" rel="noopener noreferrer"><code>{{ stripe_payment_intent }}</code></a>
                            {% else %}
                                -
                            {% endif %}
                        </p>
                        <p><strong>Statut Checkout :</strong><br>{{ stripe_checkout_status_labels[stripe_checkout_status]|default(stripe_checkout_status ?: '-') }}</p>
                        <p><strong>Statut du paiement :</strong><br>{{ stripe_payment_status_labels[stripe_payment_status]|default(stripe_payment_status ?: '-') }}</p>
                        <p><strong>Statut de l’intention :</strong><br>{{ stripe_payment_intent_status_labels[stripe_payment_intent_status]|default(stripe_payment_intent_status ?: '-') }}</p>
                        <p><strong>Dernière synchro :</strong><br>{% if stripe_synced_at %}{{ stripe_synced_at|date('d/m/Y H:i') }}{% else %}-{% endif %}</p>

                        {% if stripe_last_error %}
                            <div class="alert alert-danger" style="margin-bottom: 15px;">
                                <strong>Dernière erreur Stripe :</strong><br>
                                {{ stripe_last_error }}
                            </div>
                        {% endif %}
                    {% endif %}

                    {% if not cart.isCheckoutPayed %}
                        <hr>
                        <p class="text-muted">
                            Tant que la commande n'est pas payée, vous pouvez laisser un bon de commande{% if invoice_feature_enabled %} ou basculer manuellement en facture pro forma{% endif %}. {% if invoice_feature_enabled %}Si la facturation est activée sur la boutique, le paiement générera ensuite automatiquement la facture finale.{% endif %}
                        </p>

                        <form method="post" action="{{ path('admin_order_document_type', { id: cart.id }) }}" style="margin-bottom: 20px;">
                            <input type="hidden" name="_token" value="{{ csrf_token('document-type-' ~ cart.id) }}">

                            <div class="form-group">
                                <label for="document_type">Type de document</label>
                                <select name="document_type" id="document_type" class="form-control">
                                    <option value="order" {% if cart.documentType == 'order' %}selected{% endif %}>
                                        {{ 'checkout_design.document_order'|trans({}, 'messages', 'fr') }}
                                    </option>
                                    {% if invoice_feature_enabled %}
                                        <option value="invoice" {% if cart.documentType == 'invoice' %}selected{% endif %}>
                                            {{ 'checkout_design.document_proforma'|trans({}, 'messages', 'fr') }}
                                        </option>
                                    {% endif %}
                                </select>
                            </div>

                            <button type="submit" class="btn btn-default">
                                Enregistrer le type de document
                            </button>
                        </form>

                        <hr>
                        <p class="text-muted">
                            Marquer manuellement cette commande comme payée.
                        </p>
                        {% if checkout_completion_issue %}
                            <div class="alert alert-warning">
                                {{ checkout_completion_issue }}
                            </div>
                        {% endif %}

                        <form method="post" action="{{ path('admin_order_mark_paid', { id: cart.id }) }}">
                            <input type="hidden" name="_token" value="{{ csrf_token('mark-paid-' ~ cart.id) }}">

                            <div class="form-group">
                                <label for="payment_method_id">Méthode de paiement</label>
                                <select name="payment_method_id" id="payment_method_id" class="form-control" required>
                                    <option value="">Choisir</option>
                                    {% for payment_method in payment_methods %}
                                        <option
                                            value="{{ payment_method.id }}"
                                            {% if cart.paymentMethod and cart.paymentMethod.id == payment_method.id %}selected{% endif %}
                                        >
                                            {% if payment_method.configuration['name'] is defined and payment_method.configuration['name'] %}
                                                {{ payment_method.configuration['name'] }}
                                            {% else %}
                                                {{ payment_method.method|trans }}
                                            {% endif %}
                                        </option>
                                    {% endfor %}
                                </select>
                            </div>

                            <div class="form-group">
                                <label for="payed_at">Date de paiement</label>
                                <input
                                    type="datetime-local"
                                    name="payed_at"
                                    id="payed_at"
                                    class="form-control"
                                    value="{{ (cart_checkout and cart_checkout.payedAt ? cart_checkout.payedAt : date())|date('Y-m-d\\TH:i') }}"
                                    required
                                >
                            </div>

                            <button type="submit" class="btn btn-success" {% if checkout_completion_issue %}disabled="disabled"{% endif %}>
                                Passer la commande en payé
                            </button>
                        </form>
                    {% endif %}
                </div>
            </div>
        </div>

        <div class="col-md-3">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <strong>État de la commande</strong>
                </div>
                <div class="panel-body">
                    {% if checkout_status == 'paid' %}
                        <span class="label label-success">Payée</span>
                    {% elseif checkout_status == 'initiated' %}
                        <span class="label label-primary">Paiement initié</span>
                    {% elseif checkout_status == 'failed' %}
                        <span class="label label-danger">Paiement échoué</span>
                        {% if payment_failure_code %}
                            <br>
                            <small><strong>Code erreur :</strong> {{ payment_failure_code }}</small>
                        {% elseif payment_failure_message %}
                            <br>
                            <small>{{ payment_failure_message }}</small>
                        {% endif %}
                    {% elseif checkout_status == 'canceled' %}
                        <span class="label label-default">Paiement annulé</span>
                        {% if payment_failure_code %}
                            <br>
                            <small><strong>Code erreur :</strong> {{ payment_failure_code }}</small>
                        {% elseif payment_failure_message %}
                            <br>
                            <small>{{ payment_failure_message }}</small>
                        {% endif %}
                    {% elseif checkout_status == 'abandoned' %}
                        <span class="label label-warning">Panier abandonné</span>
                    {% elseif checkout_status == 'ordered' %}
                        <span class="label label-order-validated">Paiement en attente de validation</span>
                        {% if effective_payment_method and not effective_payment_method.checkoutOnlineMethod %}
                            <br>
                            <small>{{ effective_payment_method.method|trans }}</small>
                        {% endif %}
                    {% else %}
                        <span class="label label-warning">En cours</span>
                    {% endif %}
                    <hr>
                    <p><strong>Créée le :</strong><br>{{ cart.createdAt|date('d/m/Y H:i') }}</p>
                    {% if cart_checkout and cart_checkout.initiatedAt %}
                        <p><strong>Paiement initié le :</strong><br>{{ cart_checkout.initiatedAt|date('d/m/Y H:i') }}</p>
                    {% endif %}
                    {% if cart_checkout and cart_checkout.orderedAt and checkout_status == 'ordered' %}
                        <p><strong>En attente de validation depuis :</strong><br>{{ cart_checkout.orderedAt|date('d/m/Y H:i') }}</p>
                    {% endif %}
                    {% if cart_checkout and cart_checkout.payedAt %}
                        <p><strong>Payée le :</strong><br>{{ cart_checkout.payedAt|date('d/m/Y H:i') }}</p>
                    {% endif %}
                    <p><strong>Référence :</strong><br>{{ cart.token ?: '-' }}</p>
                    <p>
                        <strong>{{ 'order.price_group'|trans }} :</strong><br>
                        {{ pricing and pricing.priceGroupName ? pricing.priceGroupName : '-' }}
                    </p>
                    <p>
                        <strong>{{ 'order.partner_code'|trans }} :</strong><br>
                        {{ cart.groupCode ?: '-' }}
                    </p>
                    <p>
                        <strong>Quantité :</strong><br>
                        {{ cart.quantity }}{% if pricing and pricing.degressiveIsBottleOffered %} + cadeau{% endif %}
                    </p>
                </div>
            </div>

            <div class="panel panel-default">
                <div class="panel-heading">
                    <strong>Historique des emails</strong>
                </div>
                <div class="panel-body">
                    {% for email_log in email_logs %}
                        {% set email_status = email_status_labels[email_log.status]|default({ label: email_log.status, class: 'label-default' }) %}
                        <div {% if not loop.last %}style="border-bottom: 1px solid #eee; padding-bottom: 12px; margin-bottom: 12px;"{% endif %}>
                            <div style="display: flex; justify-content: space-between; gap: 8px;">
                                <strong>{{ email_type_labels[email_log.type]|default(email_log.type) }}</strong>
                                <span class="label {{ email_status.class }}">{{ email_status.label }}</span>
                            </div>
                            <div class="text-muted" style="margin-top: 4px; word-break: break-word;">
                                {{ email_log.recipientName ? email_log.recipientName ~ ' · ' : '' }}{{ email_log.recipientEmail }}
                            </div>
                            <div class="text-muted" style="margin-top: 4px;">
                                {{ email_log.queuedAt|date('d/m/Y H:i') }} · {{ email_log.transportLabel }}
                            </div>
                            {% if email_log.subject %}
                                <div style="margin-top: 4px;">{{ email_log.subject }}</div>
                            {% endif %}
                            {% if email_log.sentAt %}
                                <div class="text-success" style="margin-top: 4px;">Envoyé le {{ email_log.sentAt|date('d/m/Y H:i') }}</div>
                            {% elseif email_log.failedAt %}
                                <div class="text-danger" style="margin-top: 4px;">Échec le {{ email_log.failedAt|date('d/m/Y H:i') }}</div>
                            {% endif %}
                            {% if email_log.error %}
                                <div class="text-danger" style="margin-top: 4px;">{{ email_log.error }}</div>
                            {% endif %}
                        </div>
                    {% else %}
                        <p class="text-muted" style="margin-bottom: 0;">Aucun email suivi pour cette commande.</p>
                    {% endfor %}
                </div>
            </div>

            <div class="panel panel-default">
                <div class="panel-heading">
                    <strong>Livraison</strong>
                </div>
                <div class="panel-body">
                    <p>
                        <strong>Statut :</strong><br>
                        {% if cart.isDelivery %}
                            <span class="label label-info">Expédiée</span>
                        {% else %}
                            <span class="label label-default">Non expédiée</span>
                        {% endif %}
                    </p>
                    <p>
                        <strong>Méthode :</strong><br>
                        {% if cart.deliveryMethod %}
                            {{ cart.deliveryMethod.name }}
                        {% elseif cart.cartShipping and cart.cartShipping.name %}
                            {{ cart.cartShipping.name }}
                        {% else %}
                            Livraison standard
                        {% endif %}
                    </p>
                    <p>
                        <strong>Code de suivi :</strong><br>
                        {{ cart.codeCarrier ?: '-' }}
                    </p>
                    <p>
                        <strong>Lien de suivi :</strong><br>
                        {% if cart.urlDeSuiviCarrier %}
                            <a href="{{ cart.urlDeSuiviCarrier }}" target="_blank" rel="noopener noreferrer">
                                Ouvrir le suivi
                            </a>
                        {% else %}
                            -
                        {% endif %}
                    </p>
                    {% if use_shipping_address and delivery_address %}
                        {% if delivery_address.company %}<p><strong>{{ delivery_address.company }}</strong></p>{% endif %}
                        <p>{{ delivery_address.firstname }} {{ delivery_address.lastname }}</p>
                        <p>{{ delivery_address.email ?: '-' }}</p>
                        <p>{{ delivery_address.phone ?: '-' }}</p>
                        <p>
                            {{ delivery_address.street }}<br>
                            {{ delivery_address.postal }} {{ delivery_address.city }}<br>
                            {{ delivery_address.country|country_name }}
                        </p>
                    {% elseif cart.deliveryMethod %}
                        <p>
                            <strong>{{ cart.deliveryMethod.category ? cart.deliveryMethod.category.name ~ ' : ' : '' }}{{ cart.deliveryMethod.name }}</strong>
                        </p>
                        {% if cart.deliveryMethod.description %}
                            <div class="text-muted">{{ cart.deliveryMethod.description|raw }}</div>
                        {% endif %}
                    {% else %}
                        <p class="text-muted" style="margin-bottom: 0;">Aucune adresse de livraison.</p>
                    {% endif %}
                </div>
            </div>

            <div class="panel panel-default">
                <div class="panel-heading">
                    <strong>Client</strong>
                </div>
                <div class="panel-body">
                    <p>
                        <strong>Compte site :</strong><br>
                        {% if siteUser %}
                            <span class="label label-success">Enregistré</span>
                        {% else %}
                            <span class="label label-default">Non enregistré</span>
                        {% endif %}
                    </p>
                    {% if cart.firstname or cart.lastname or cart.email or cart.phone or cart.company %}
                        {% if cart.company %}<p><strong>{{ cart.company }}</strong></p>{% endif %}
                        <p>{{ cart.firstname ?: '-' }} {{ cart.lastname ?: '' }}</p>
                        <p>{{ cart.email ?: '-' }}</p>
                        <p>{{ cart.phone ?: '-' }}</p>
                        {% if invoice_address and invoice_address.vatId %}
                            <p><strong>TVA :</strong> {{ invoice_address.vatId }}</p>
                        {% endif %}
                    {% else %}
                        <p>{{ cart.getEmail() ?: '-' }}</p>
                        <p class="text-muted" style="margin-bottom: 0;">Client non renseigné.</p>
                    {% endif %}
                </div>
            </div>

            {% if billing_address %}
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <strong>Adresse de facturation</strong>
                    </div>
                    <div class="panel-body">
                        {% if billing_address.company %}<p><strong>{{ billing_address.company }}</strong></p>{% endif %}
                        <p>
                            {{ billing_address.street }}<br>
                            {{ billing_address.postal }} {{ billing_address.city }}<br>
                            {{ billing_address.country|country_name }}
                        </p>
                    </div>
                </div>
            {% endif %}
        </div>
    </div>

    {% if invoice_feature_enabled and cart.isCheckoutPayed and invoice %}
        {% set credit_reference = null %}
        {% if invoice.numberCredit is not null and invoice.year is not null %}
            {% set credit_reference_parts = [] %}
            {% if invoice_prefix %}
                {% set credit_reference_parts = credit_reference_parts|merge([invoice_prefix]) %}
            {% endif %}
            {% set credit_reference_parts = credit_reference_parts|merge(['Avoir', invoice.year, '%05d'|format(invoice.numberCredit)]) %}
            {% set credit_reference = credit_reference_parts|join('-') %}
        {% endif %}
        <div class="row">
            <div class="col-md-12">
                <div class="panel panel-default">
                    <div class="panel-heading">
                        <strong>Avoir</strong>
                    </div>
                    <div class="panel-body">
                        {% if invoice.credit and credit_summary %}
                            <div class="alert alert-info">
                                <strong>Avoir créé :</strong> {{ credit_reference ?: 'Oui' }}
                                {% if credit_summary.created_at is defined and credit_summary.created_at %}
                                    le {{ credit_summary.created_at|date('d/m/Y H:i') }}
                                {% endif %}
                            </div>

                            <div style="margin-bottom: 15px;">
                                <a href="{{ path('admin_order_credit_pdf', { id: cart.id }) }}" class="btn btn-info" target="_blank">
                                    Télécharger l'avoir
                                </a>
                                {% if can_trigger_credit_refund %}
                                    <form
                                        method="post"
                                        action="{{ path('admin_order_credit_refund_card', { id: cart.id }) }}"
                                        style="display: inline-block;"
                                        data-confirm-submit="true"
                                        data-confirm-message="Confirmer le remboursement de cet avoir sur la carte bancaire ?"
                                    >
                                        <input type="hidden" name="_token" value="{{ csrf_token('refund-credit-card-' ~ cart.id) }}">
                                        <button type="submit" class="btn btn-warning">
                                            Rembourser sur la carte bancaire
                                        </button>
                                    </form>
                                {% endif %}
                                {% if can_cancel_credit %}
                                    <form
                                        method="post"
                                        action="{{ path('admin_order_cancel_credit', { id: cart.id }) }}"
                                        style="display: inline-block;"
                                        data-credit-confirm-form="cancel"
                                    >
                                        <input type="hidden" name="_token" value="{{ csrf_token('cancel-credit-' ~ cart.id) }}">
                                        <button
                                            type="submit"
                                            class="btn btn-danger"
                                            data-credit-confirm="cancel"
                                            data-credit-amount-ttc="{{ credit_summary.totals.total_ttc|default(0) }}"
                                        >
                                            Annuler l'avoir
                                        </button>
                                    </form>
                                {% else %}
                                    <span class="btn btn-danger disabled" aria-disabled="true">
                                        Annuler l'avoir
                                    </span>
                                    <span class="text-muted" style="margin-left: 8px;">
                                        Impossible si un autre avoir a été créé après ou si Stripe a déjà remboursé l'avoir.
                                    </span>
                                {% endif %}
                            </div>

                            <div class="row">
                                <div class="col-md-8">
                                    {% if credit_summary.items is defined and credit_summary.items is not empty %}
                                        <table class="table table-bordered">
                                            <thead>
                                            <tr>
                                                <th>Produit</th>
                                                <th>Qté remboursée</th>
                                                <th>Montant</th>
                                            </tr>
                                            </thead>
                                            <tbody>
                                            {% for refunded_item in credit_summary.items %}
                                                <tr>
                                                    <td>
                                                        {{ refunded_item.product_name }}
                                                        {% if refunded_item.type_name %}
                                                            <br><small class="text-muted">{{ refunded_item.type_name }}{% if refunded_item.unit_label %} ({{ refunded_item.unit_label }}){% endif %}</small>
                                                        {% elseif refunded_item.unit_label %}
                                                            <br><small class="text-muted">{{ refunded_item.unit_label }}</small>
                                                        {% endif %}
                                                    </td>
                                                    <td>{{ refunded_item.quantity_refunded }} / {{ refunded_item.quantity_ordered }}</td>
                                                    <td>{{ refunded_item.amount_ttc|price_format }} €</td>
                                                </tr>
                                            {% endfor %}
                                            </tbody>
                                        </table>
                                    {% else %}
                                        <p class="text-muted">Aucune ligne produit n'a été remboursée.</p>
                                    {% endif %}
                                </div>
                                <div class="col-md-4">
                                    <p><strong>Type :</strong><br>{{ credit_summary.mode == 'full' ? 'Avoir total' : 'Avoir partiel' }}</p>
                                    <p>
                                        <strong>Frais de port :</strong><br>
                                        {% if credit_summary.shipping.amount_ttc is defined and credit_summary.shipping.amount_ttc > 0 %}
                                            {{ credit_summary.shipping.amount_ttc|price_format }} €
                                            {% if credit_summary.shipping.percent is defined and credit_summary.shipping.percent is not null %}
                                                <br><small class="text-muted">{{ credit_summary.shipping.percent }} %</small>
                                            {% endif %}
                                        {% else %}
                                            Aucun remboursement
                                        {% endif %}
                                    </p>
                                    <p>
                                        <strong>Total avoir :</strong><br>
                                        <span style="font-size: 18px; font-weight: 700;">{{ credit_summary.totals.total_ttc|price_format }} €</span>
                                    </p>
                                    {% if credit_summary.stripe_refund is defined %}
                                        <hr>
                                        <p>
                                            <strong>Remboursement Stripe :</strong><br>
                                            {% if credit_summary.stripe_refund.status == 'succeeded' %}
                                                <span class="label label-success">Effectué</span>
                                            {% elseif credit_summary.stripe_refund.status == 'pending' %}
                                                <span class="label label-warning">En attente</span>
                                            {% elseif credit_summary.stripe_refund.status == 'failed' %}
                                                <span class="label label-danger">Echec</span>
                                            {% else %}
                                                <span class="label label-default">{{ credit_summary.stripe_refund.status|default('Non lance') }}</span>
                                            {% endif %}
                                        </p>
                                        {% if credit_summary.stripe_refund.amount_ttc is defined and credit_summary.stripe_refund.amount_ttc %}
                                            <p><strong>Montant rembourse :</strong><br>{{ credit_summary.stripe_refund.amount_ttc|price_format }} €</p>
                                        {% endif %}
                                        {% if credit_summary.stripe_refund.refund_id is defined and credit_summary.stripe_refund.refund_id %}
                                            <p><strong>ID Stripe :</strong><br><code>{{ credit_summary.stripe_refund.refund_id }}</code></p>
                                        {% endif %}
                                        {% if credit_summary.stripe_refund.message is defined and credit_summary.stripe_refund.message %}
                                            <p><strong>Message :</strong><br><small class="text-muted">{{ credit_summary.stripe_refund.message }}</small></p>
                                        {% endif %}
                                    {% endif %}
                                </div>
                            </div>
                        {% else %}
                            <p class="text-muted">
                                Sélectionnez les quantités à rembourser par produit. Vous pouvez aussi rembourser les frais de port
                                partiellement en pourcentage ou en totalité, ou générer directement un avoir total.
                            </p>
                            <p class="alert alert-info">
                                La création d'un avoir envoie automatiquement l'avoir au client par email, avec le PDF en pièce jointe.
                            </p>

                            <form
                                method="post"
                                action="{{ path('admin_order_create_credit', { id: cart.id }) }}"
                                data-credit-confirm-form="create"
                                data-shipping-paid-ttc="{{ credit_context.shipping_paid_ttc }}"
                            >
                                <input type="hidden" name="_token" value="{{ csrf_token('create-credit-' ~ cart.id) }}">

                                <div class="table-responsive">
                                    <table class="table table-bordered">
                                        <thead>
                                        <tr>
                                            <th>Produit</th>
                                            <th>Quantité commandée</th>
                                            <th>Montant ligne</th>
                                            <th style="width: 180px;">Quantité à rembourser</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        {% for credit_line in credit_context.lines %}
                                            <tr>
                                                <td>
                                                    {{ credit_line.product_name }}
                                                    {% if credit_line.type_name %}
                                                        <br><small class="text-muted">{{ credit_line.type_name }}{% if credit_line.unit_label %} ({{ credit_line.unit_label }}){% endif %}</small>
                                                    {% elseif credit_line.unit_label %}
                                                        <br><small class="text-muted">{{ credit_line.unit_label }}</small>
                                                    {% endif %}
                                                </td>
                                                <td>{{ credit_line.quantity }}</td>
                                                <td>{{ credit_line.line_total_ttc|price_format }} €</td>
                                                <td>
                                                    <input
                                                        type="number"
                                                        min="0"
                                                        max="{{ credit_line.quantity }}"
                                                        step="1"
                                                        name="credit_quantities[{{ credit_line.item_id }}]"
                                                        value="0"
                                                        class="form-control"
                                                        data-line-total-ttc="{{ credit_line.line_total_ttc }}"
                                                        data-quantity-ordered="{{ credit_line.quantity }}"
                                                    >
                                                </td>
                                            </tr>
                                        {% else %}
                                            <tr>
                                                <td colspan="4" class="text-muted">Aucune ligne remboursable.</td>
                                            </tr>
                                        {% endfor %}
                                        </tbody>
                                    </table>
                                </div>

                                <div class="row">
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="shipping_refund_mode">Remboursement frais de port</label>
                                            <select name="shipping_refund_mode" id="shipping_refund_mode" class="form-control">
                                                <option value="none">Aucun</option>
                                                <option value="percent">Pourcentage</option>
                                                <option value="full">Totalité</option>
                                            </select>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <div class="form-group">
                                            <label for="shipping_refund_percent">Pourcentage frais de port</label>
                                            <div class="input-group">
                                                <input
                                                    type="number"
                                                    min="0"
                                                    max="100"
                                                    step="1"
                                                    name="shipping_refund_percent"
                                                    id="shipping_refund_percent"
                                                    value="100"
                                                    class="form-control"
                                                >
                                                <span class="input-group-addon">%</span>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="col-md-4">
                                        <p style="margin-top: 25px;">
                                            <strong>Frais de port payés :</strong>
                                            {{ credit_context.shipping_paid_ttc|price_format }} €
                                        </p>
                                    </div>
                                </div>

                                {% if can_direct_credit_refund %}
                                    <div class="row">
                                        <div class="col-md-12">
                                            <div class="checkbox">
                                                <label>
                                                    <input type="checkbox" name="refund_to_card" value="1">
                                                    Rembourser aussi directement cet avoir sur la carte bancaire.
                                                </label>
                                            </div>
                                        </div>
                                    </div>
                                {% endif %}

                                <div class="row">
                                    <div class="col-md-12">
                                        <button
                                            type="submit"
                                            name="credit_action"
                                            value="full"
                                            class="btn btn-danger"
                                            data-credit-confirm="full"
                                        >
                                            Générer un avoir total
                                        </button>
                                        <button
                                            type="submit"
                                            name="credit_action"
                                            value="partial"
                                            class="btn btn-warning"
                                            data-credit-confirm="partial"
                                        >
                                            Générer l'avoir sélectionné
                                        </button>
                                    </div>
                                </div>
                            </form>
                        {% endif %}
                    </div>
                </div>
            </div>
        </div>
    {% endif %}

    <div class="modal fade" id="creditConfirmModal" tabindex="-1" role="dialog" aria-labelledby="creditConfirmModalTitle">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Fermer">
                        <span aria-hidden="true">&times;</span>
                    </button>
                    <h4 class="modal-title" id="creditConfirmModalTitle">Confirmer l'action</h4>
                </div>
                <div class="modal-body" id="creditConfirmModalBody"></div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Annuler</button>
                    <button type="button" class="btn btn-primary" id="creditConfirmModalSubmit">Confirmer</button>
                </div>
            </div>
        </div>
    </div>
{% endblock %}
