<?php

use AmeliaBooking\Application\Services\Helper\HelperService;
use AmeliaBooking\Infrastructure\WP\Translations\BackendStrings;

/** @var HelperService $helperService */
$helperService = $this->container->get('application.helper.service');

$data = $invoiceData['placeholders'];


// CUSTOM: Récupérer l'adhésion depuis la DB et l'ajouter aux montants
$adhesion_amount = 0;
global $wpdb;

// Essayer de trouver le payment via plusieurs méthodes
$payment_data = null;

// Méthode 1: Via le invoice_number (méthode la plus fiable)
$invoice_number = $data['invoice_number'] ?? null;
if (!empty($invoice_number)) {
    $payment_data = $wpdb->get_row(
        $wpdb->prepare(
            "SELECT id, data, gateway, amount, status FROM {$wpdb->prefix}amelia_payments WHERE invoiceNumber = %d",
            $invoice_number
        ),
        ARRAY_A
    );
}

// Méthode 2: Via le payment_id si disponible
if (!$payment_data) {
    $payment_id = $data['payment_id'] ?? $invoiceData['payment_id'] ?? null;
    if (!empty($payment_id)) {
        $payment_data = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT id, data, gateway, amount, status FROM {$wpdb->prefix}amelia_payments WHERE id = %d",
                $payment_id
            ),
            ARRAY_A
        );
    }
}

// Méthode 3: Chercher le payment via customer_email et correspondance approximative de montant
if (!$payment_data && !empty($data['customer_email'])) {
    // Chercher le customer ID
    $customer = $wpdb->get_row(
        $wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}amelia_users WHERE email = %s AND type = 'customer'",
            $data['customer_email']
        ),
        ARRAY_A
    );

    if ($customer) {
        // Chercher le payment le plus récent pour ce client avec un montant proche
        // Le montant total devrait être proche de invoice_paid_amount (291.4) ou subtotal (310)
        $expected_amount = $invoiceData['items'][0]['invoice_paid_amount'] ?? $invoiceData['paid'];

        $payment_data = $wpdb->get_row(
            $wpdb->prepare(
                "SELECT p.id, p.data, p.gateway, p.amount, p.status
                 FROM {$wpdb->prefix}amelia_payments p
                 WHERE p.customerBookingId IN (
                     SELECT cb.id FROM {$wpdb->prefix}amelia_customer_bookings cb
                     WHERE cb.customerId = %d
                 )
                 AND p.amount >= %f
                 AND p.data LIKE %s
                 ORDER BY p.id DESC
                 LIMIT 1",
                $customer['id'],
                $expected_amount - 10, // Tolérance de -10€ pour la recherche
                '%adhesion_annuelle%'
            ),
            ARRAY_A
        );
    }
}

// Calculer la réduction du quotient familial
$quotientFamilialReduction = 0;
if (!empty($invoiceData['items'])) {
    foreach ($invoiceData['items'] as $item) {
        if (!empty($item['invoice_subtotal']) && !empty($item['invoice_paid_amount'])) {
            $itemReduction = $item['invoice_subtotal'] - $item['invoice_paid_amount'];
            if ($itemReduction > 0) {
                $quotientFamilialReduction += $itemReduction;
            }
        }
    }
}

// Flag pour éviter d'appliquer les ajustements plusieurs fois
if (!isset($invoiceData['_familya_adjusted'])) {
    if ($payment_data && !empty($payment_data['data'])) {
        $data_array = json_decode($payment_data['data'], true);

        if (isset($data_array['adhesion_annuelle']['amount'])) {
            $adhesion_amount = (float) $data_array['adhesion_annuelle']['amount'];
            $payment_gateway = $payment_data['gateway'] ?? '';
            $payment_amount = (float) ($payment_data['amount'] ?? 0);
            $payment_status = $payment_data['status'] ?? '';

            // Note: L'adhésion est déjà incluse dans le prix du booking (ex: 42,5€ = 40€ atelier + 2,5€ adhésion/personne)
            // On ne l'ajoute donc PAS au subtotal/total pour éviter la double comptabilisation
            // Elle sera affichée comme une ligne séparée dans la facture (lignes 507-518)

            // Soustraire la réduction du quotient familial du total
            if ($quotientFamilialReduction > 0) {
                $invoiceData['total'] -= $quotientFamilialReduction;
            }

            // CORRECTION : Pour les événements, invoice_paid_amount n'est pas toujours calculé correctement
            // Si le montant payé est anormalement bas (< montant du paiement), on le recalcule
            if ($payment_status === 'paid' || $payment_status === 'approved') {
                if ($invoiceData['paid'] < $payment_amount) {
                    // Le montant payé devrait être au minimum le montant du paiement
                    $invoiceData['paid'] = $payment_amount;
                }
            }

            // Ajouter l'adhésion au montant payé SEULEMENT si ce n'est pas un paiement sur place
            // Note: invoice_paid_amount inclut déjà la réduction du QF, donc pas besoin de la soustraire
            if ($payment_gateway !== 'onSite') {
                $invoiceData['paid'] += $adhesion_amount;
            }

            // Recalculer le montant restant à payer
            $invoiceData['leftToPay'] = $invoiceData['total'] - $invoiceData['paid'];

            // Marquer comme déjà ajusté
            $invoiceData['_familya_adjusted'] = true;
        }
    }
}
// FIN CUSTOM

$locale = get_locale();
$localePrefix = substr($locale, 0, 2);

$googleFontCss = null;
switch ($localePrefix) {
    case 'ja':
        $googleFontCss = 'https://fonts.googleapis.com/css2?family=Noto+Sans+JP:wght@400;700&display=swap';
        $fontFamily = "'Noto Sans JP', 'DejaVu Sans', sans-serif";
        break;
    case 'ko':
        $googleFontCss = 'https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@400;700&display=swap';
        $fontFamily = "'Noto Sans KR', 'DejaVu Sans', sans-serif";
        break;
    case 'th':
        $googleFontCss = 'https://fonts.googleapis.com/css2?family=Noto+Sans+Thai:wght@400;700&display=swap';
        $fontFamily = "'Noto Sans Thai', 'DejaVu Sans', sans-serif";
        break;
    case 'zh':
        $googleFontCss = 'https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;700&display=swap';
        $fontFamily = "'Noto Sans SC', 'DejaVu Sans', sans-serif";
        break;
    default:
        $fontFamily = "'DejaVu Sans', sans-serif";
}

?>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <?php if (!empty($googleFontCss)) : ?>
        <link rel="stylesheet" href="<?php echo $googleFontCss; ?>">
    <?php endif; ?>
  <style>
      body { margin: 0; font-family: <?php echo $fontFamily; ?>; line-height: 15px; }
      html { margin: 0; font-family: <?php echo $fontFamily; ?>; line-height: 15px;}
      @page { margin: 0; font-family: <?php echo $fontFamily; ?>; line-height: 15px;}

      .invoice-header {
          background-color: #F5F5F5;
          padding: 44px;
      }

      .invoice-header-first-line {
          margin-bottom: 10px;
          display: block
      }

      .invoice-header-first-line table {
          float: right;
      }

      .invoice-header-first-line table tr td:first-child {
          vertical-align: middle;
          padding-right: 16px
      }

      .invoice-header img {
          width: 50px;
          height: 50px;
      }

      .invoice-header-first-line-company-name {
          vertical-align: middle;
          font-weight: 700;
          font-size: 16px;
          color: #1A2C37
      }

      .invoice-header h2 {
          float:left;
          color: #0E1920;
          font-size: 22px
      }

      .invoice-header-second-line {
          padding-bottom: 8px
      }

      .invoice-header-table {
          width: 100%;
          font-size: 14px;
          font-weight: 400;
          color: #1A2C37;
          border-spacing: 0 2px;
      }

      .invoice-header-table-company {
          text-align: right;
      }

      .invoice-header-table-company-name {
          font-size: 16px;
      }

      .invoice-header-table-invoice-number-value, .invoice-header-table-invoice-issued-date {
          text-align: right;
          padding-left: 8px
      }

      .invoice-body {
          padding: 0 44px;
          margin-top: 25px
      }

      .invoice-body-customer {
          width: 49%;
          color: #1A2C37;
          margin-bottom: 35px;
          float: left;
      }

      .invoice-body-customer td {
          font-size: 14px;
          font-weight: 400;
          padding-bottom: 5px;
      }

      .invoice-body-customer tr td:first-child {
          text-align: left;
      }

      .invoice-body-customer-to td {
          font-weight: bold;
          padding-bottom: 10px
      }

      .invoice-body-cf {
          width: 49%;
          color: #1A2C37;
          margin-bottom: 35px;
          float: right;
          text-align: right;
      }

      .invoice-body-cf tr:first-child td {
        font-weight: bold;
        padding-bottom: 10px
      }

      .invoice-body-cf td {
          font-size: 14px;
          font-weight: 400;
          padding-bottom: 5px;
      }

      .invoice-body-items {
          width: 100%;
          margin-bottom: 20px;
          clear: both;
      }

      .invoice-body-items td {
          padding: 10px;
          font-weight: 400;
          font-size: 12px;
      }

      .invoice-body-items tr td {
          text-align: right;
      }

      .invoice-body-items tr td:first-child {
          text-align: left;
      }

      .invoice-body-items-name {
          background-color: #F5F5F5;
          color: #808A90;
      }

      .invoice-body-items-data {
          color: #1A2C37;
      }

      .invoice-body-items-data td {
          border-bottom: 1px dashed lightgray;
      }

      .invoice-body-sum {
          float: right;
          width: 50%;
          font-size: 13px;
          font-weight: 400;
          color: #1A2C37
      }

      .invoice-body-sum > div {
          margin-bottom: 10px;
      }

      .invoice-body-sum > div > span:nth-child(2) {
          float: right;
      }

      .invoice-body-total {
          font-size: 16px;
          margin-bottom: 20px;
      }

      .invoice-body-sum hr {
          color:lightgray;
      }

      .invoice-footer {
          padding: 44px;
          background-color: #F5F5F5;
          position: absolute;
          bottom: 0;
          width: 100%;
      }

      .invoice-footer-info {
          font-weight: bolder;
          font-size: 12px;
          color: #808A90;
          margin-bottom: 10px
      }

      .invoice-footer-method > div:first-child {
          font-weight: bolder;
          font-size: 11px;
          color: #1A2C37;
          margin-bottom: 5px
      }

      .invoice-footer-method > div:nth-child(2) {
          font-weight: bold;
          font-size: 12px;
          color: #808A90;
      }

  </style>
  <title><?php echo BackendStrings::get('invoice') ?></title>
</head>
<body>
<div class="invoice">

    <div class="invoice-header">

        <div class="invoice-header-first-line">
            <table class="invoice-header-first-line-company">
                <tr>
                    <?php if (!empty($data['company_name']) && $invoiceData['companyLogo']) : ?>
                        <td class="invoice-header-first-line-company-name">
                            <span><b><?php echo $data['company_name'] ?></b></span>
                        </td>
                    <?php endif; ?>
                    <?php if ($invoiceData['companyLogo']) : ?>
                        <td>
                            <img src='data:<?php echo $invoiceData['companyLogo']['mime']; ?>;base64,<?php echo $invoiceData['companyLogo']['img']; ?>'
                                 alt="logo">
                        </td>
                    <?php endif; ?>
                </tr>
            </table>

            <h2>
                <?php echo BackendStrings::get('invoice') ?>
            </h2>

        </div>

        <br><br><br><br>

        <div class="invoice-header-second-line">

            <table class="invoice-header-table">
                <tr>
                    <td class="invoice-header-table-invoice-number">
                        <span class="invoice-header-table-invoice-number-label"><?php echo BackendStrings::get('invoice') ?></span>
                        <span class="invoice-header-table-invoice-number-value">#<?php echo str_pad($data['invoice_number'], 4, '0', STR_PAD_LEFT) ?></span>
                    </td>
                    <td class="invoice-header-table-company invoice-header-table-company-name">
                        <span><?php echo $data['company_name'] ?></span>
                    </td>
                </tr>
                <tr>
                    <td class="invoice-header-table-invoice-issued">
                        <span class="invoice-header-table-invoice-issued-label"><?php echo BackendStrings::get('issued') ?></span>
                        <span class="invoice-header-table-invoice-issued-date"><?php echo $data['invoice_issued'] ?></span>
                    </td>
                    <td class="invoice-header-table-company">
                        <?php if (!empty($data['company_address'])) : ?>
                            <span><?php echo $data['company_address']?></span>
                        <?php elseif (!empty($data['company_email']) || !empty($data['company_phone'])) : ?>
                            <?php echo !empty($data['company_email']) ? $data['company_email'] : ''?>
                            <?php if (!empty($data['company_email']) && !empty($data['company_phone'])) : ?>
                                |
                            <?php endif; ?>
                            <?php echo !empty($data['company_phone']) ? $data['company_phone'] : ''?>
                        <?php elseif (!empty($data['company_vat_number'])) : ?>
                            <?php echo $data['company_vat_number'] ?>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php if ((!empty($data['company_email']) || !empty($data['company_phone'])) && !empty($data['company_address'])) : ?>
                    <tr>
                        <td></td>
                        <td class="invoice-header-table-company">
                            <?php echo !empty($data['company_email']) ? $data['company_email'] : ''?>
                            <?php if (!empty($data['company_email']) && !empty($data['company_phone'])) : ?>
                                 |
                            <?php endif; ?>
                            <?php echo !empty($data['company_phone']) ? $data['company_phone'] : ''?>
                        </td>
                    </tr>
                <?php endif; ?>
                <?php if (!empty($data['company_vat_number']) && (!empty($data['company_address']) || !empty($data['company_email']) || !empty($data['company_phone']))) : ?>
                    <tr>
                        <td></td>
                        <td class="invoice-header-table-company">
                            <?php echo $data['company_vat_number'] ?>
                        </td>
                    </tr>
                <?php endif; ?>
            </table>
        </div>

    </div>

    <div class="invoice-body">
        <table class="invoice-body-customer">
            <tr class="invoice-body-customer-to">
                <td><?php echo BackendStrings::get('to_upper') ?></td>
            </tr>
            <tr>
                <td class="invoice-body-customer-name"><?php echo $data['customer_full_name'] ?></td>
            </tr>
            <tr>
                <td class="invoice-body-customer-email"><?php echo !empty($data['customer_email']) ? $data['customer_email'] : ' ' ?></td>
            </tr>
            <tr>
                <td class="invoice-body-customer-phone"><?php echo !empty($data['customer_phone']) ? $data['customer_phone'] : ' ' ?></td>
            </tr>
        </table>

        <?php if (!empty($data['customer_custom_fields'])) : ?>
            <table class="invoice-body-cf">
                <tr>
                    <td><?php echo BackendStrings::get('invoice_additional_information') ?></td>
                </tr>
                <?php foreach ($data['customer_custom_fields'] as $key => $customerCustomField) : ?>
                    <tr>
                        <td><?php echo $customerCustomField ?></td>
                    </tr>
                <?php endforeach; ?>
            </table>
        <?php endif; ?>


        <table class='invoice-body-items'>
            <thead class="invoice-body-items-name">
            <tr>
                <td><?php echo BackendStrings::get('invoice_item'); ?></td>
                <td><?php echo BackendStrings::get('invoice_unit_price') .
                        ($invoiceData['includedTax'] ? BackendStrings::get('invoice_incl_tax') : ''); ?></td>
                <td><?php echo BackendStrings::get('invoice_qty'); ?></td>
                <td><?php echo BackendStrings::get('invoice_total_item_price') .
                        ($invoiceData['includedTax'] ? BackendStrings::get('invoice_incl_tax') : ''); ?></td>
                <?php if ($invoiceData['taxEnabled']) : ?>
                    <td><?php echo BackendStrings::get('invoice_tax_rate'); ?></td>
                    <td><?php echo BackendStrings::get('invoice_tax_amount'); ?></td>
                <?php endif; ?>
            </tr>
            </thead>
            <?php
            foreach ($invoiceData['items'] as $key => $appData) :
                // Calculer le prix unitaire sans l'adhésion
                $unit_price_displayed = $appData['invoice_unit_price'];
                if ($adhesion_amount > 0 && !empty($appData['invoice_qty']) && $appData['invoice_qty'] > 0) {
                    $adhesion_per_person = $adhesion_amount / $appData['invoice_qty'];
                    $unit_price_displayed = $appData['invoice_unit_price'] - $adhesion_per_person;
                }
            ?>
                <tr class="invoice-body-items-data">
                    <td><?php echo $appData['item_name'] ?></td>
                    <td><?php echo $helperService->getFormattedPrice($unit_price_displayed) ?></td>
                    <td><?php echo $appData['invoice_qty'] ?></td>
                    <td><?php echo $helperService->getFormattedPrice($unit_price_displayed * $appData['invoice_qty']) ?></td>
                    <?php if ($invoiceData['taxEnabled']) : ?>
                        <td><?php echo !empty($appData['invoice_tax_rate']) ? $appData['invoice_tax_rate'] : 0 ?></td>
                        <td><?php echo $helperService->getFormattedPrice(!empty($appData['invoice_tax']) ? $appData['invoice_tax'] : 0) ?></td>
                    <?php endif; ?>
                </tr>
            <?php endforeach; ?>
              <?php if ($adhesion_amount > 0) : ?>
            <tr class="invoice-body-items-data">
                <td>Adhésion annuelle</td>
                <td><?php echo $helperService->getFormattedPrice($adhesion_amount) ?></td>
                <td>1</td>
                <td><?php echo $helperService->getFormattedPrice($adhesion_amount) ?></td>
                <?php if ($invoiceData['taxEnabled']) : ?>
                    <td>0</td>
                    <td><?php echo $helperService->getFormattedPrice(0) ?></td>
                <?php endif; ?>
            </tr>
            <?php endif; ?>
        </table>

        <div class="invoice-body-sum">
              <?php
            // Recalculer le sous-total et le total en tenant compte de l'adhésion
            // Le prix du booking inclut l'adhésion (ex: 75,6€ = 73,1€ atelier + 2,5€ adhésion/personne)
            // On affiche le prix sans adhésion (73,1€) + une ligne adhésion séparée (5€)
            // Donc le sous-total doit être : (prix avec adhésion × qty) = somme des lignes affichées + adhésion

            $displayedSubtotal = $invoiceData['subtotal'];
            $displayedTotal = $invoiceData['total'];

            if ($adhesion_amount > 0) {
                // Le sous-total doit inclure l'adhésion pour correspondre aux lignes affichées
                // Sous-total = (prix affiché sans adhésion × qty) + adhésion séparée
                $displayedSubtotal = $invoiceData['subtotal'];

                // Vérifier si le sous-total a été réduit (il devrait être prix_booking × qty)
                $expectedSubtotal = 0;
                foreach ($invoiceData['items'] as $item) {
                    if (!empty($item['invoice_unit_price']) && !empty($item['invoice_qty'])) {
                        // Utiliser le prix original (avec adhésion) pour le calcul
                        $expectedSubtotal += $item['invoice_unit_price'] * $item['invoice_qty'];
                    }
                }

                // Si le sous-total calculé par Amelia est différent de ce qu'on attend, l'ajuster
                if ($expectedSubtotal > 0 && abs($displayedSubtotal - $expectedSubtotal) > 0.01) {
                    $displayedSubtotal = $expectedSubtotal;
                }

                // Distinguer les réductions Amelia (code promo) des réductions custom (QF)
                if ($invoiceData['discount'] > 0) {
                    // Code promo Amelia : appliquer la réduction sur le sous-total
                    $displayedTotal = $displayedSubtotal - $invoiceData['discount'];
                } else {
                    // Réduction custom (QF) : La réduction calculée peut inclure l'adhésion
                    // car le paid_amount ne compte que le prix de l'atelier (l'adhésion est comptabilisée séparément)
                    // On ne doit soustraire que la VRAIE réduction QF, pas l'adhésion
                    $realReduction = max(0, $quotientFamilialReduction - $adhesion_amount);
                    $displayedTotal = $displayedSubtotal - $realReduction;
                }
            }
            ?>
            <?php if ($displayedSubtotal !== $displayedTotal) : ?>
                <div>
                    <span><?php echo BackendStrings::get('invoice_subtotal');?></span>
                    <span><?php echo $helperService->getFormattedPrice($displayedSubtotal) ?></span>
                </div>
            <?php endif; ?>
            <?php if ($invoiceData['discount'] > 0) : ?>
                <div>
                    <span><?php echo BackendStrings::get('invoice_discount'); ?></span>
                    <span><?php echo $helperService->getFormattedPrice($invoiceData['discount']) ?></span>
                </div>
            <?php endif; ?>
            <?php if ($invoiceData['tax'] > 0) : ?>
                <div>
                    <span><?php echo BackendStrings::get('invoice_tax'); ?></span>
                    <span><?php echo $helperService->getFormattedPrice($invoiceData['tax']) ?></span>
                </div>
            <?php endif; ?>
            <?php if ($displayedSubtotal !== $displayedTotal || $invoiceData['tax'] > 0) : ?>
                <hr>
            <?php endif; ?>
            <div class="invoice-body-total">
                <span><?php echo BackendStrings::get('invoice_total') .
                        ($invoiceData['includedTax'] && $displayedTotal > 0 ? BackendStrings::get('invoice_incl_tax') : ''); ?></span>
                <span><?php echo $helperService->getFormattedPrice($displayedTotal) ?></span>
            </div>
            <?php if ($invoiceData['paid']) : ?>
                <hr>
                <div>
                    <span><?php echo BackendStrings::get('invoice_paid'); ?></span>
                    <span><?php echo $helperService->getFormattedPrice($invoiceData['paid']) ?></span>
                </div>
                <div>
                    <span><?php echo BackendStrings::get('invoice_left_to_pay'); ?></span>
                    <span><?php echo $helperService->getFormattedPrice($displayedTotal - $invoiceData['paid']) ?></span>
                </div>
            <?php endif; ?>
        </div>

    </div>

    <div class="invoice-footer">
<!--        <div class="invoice-footer-info">--><?php //echo BackendStrings::get('invoice_payment_info'); ?><!--</div>-->
        <div class="invoice-footer-method">
            <div><?php echo BackendStrings::get('invoice_payment_method'); ?></div>
            <div><?php echo $data['invoice_method'] ?></div>
        </div>
    </div>

</div>

</body>
</html>
