<?php

declare(strict_types=1);

function mail_transport_mode(): string
{
    $configured = strtolower(trim((string) env('MAIL_TRANSPORT', 'auto')));
    if (in_array($configured, ['mail', 'log', 'off', 'brevo', 'brevo_api'], true)) {
        return $configured === 'brevo_api' ? 'brevo' : $configured;
    }

    $brevoApiKey = trim((string) env('BREVO_API_KEY', ''));
    if ($brevoApiKey !== '') {
        return 'brevo';
    }

    $appEnv = strtolower(trim((string) env('APP_ENV', 'local')));
    if (in_array($appEnv, ['local', 'dev', 'development', 'test'], true)) {
        return 'log';
    }

    return 'mail';
}

function mail_log_event(string $event, string $to, string $subject, string $body): void
{
    ensure_dir(runtime_path('mail'));
    $logLine = sprintf(
        "[%s] %s to=%s subject=%s\n%s\n\n",
        date('Y-m-d H:i:s'),
        $event,
        $to,
        $subject,
        $body
    );
    file_put_contents(runtime_path('mail/mail.log'), $logLine, FILE_APPEND | LOCK_EX);
}

function mail_escape_html(string $value): string
{
    return htmlspecialchars($value, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function mail_to_float(mixed $value, float $default = 0.0): float
{
    if (is_int($value) || is_float($value) || is_numeric((string) $value)) {
        return (float) $value;
    }

    return $default;
}

function mail_format_money_eur(float $amount): string
{
    return number_format($amount, 2, ',', ' ') . ' EUR';
}

function mail_company_profile(): array
{
    return [
        'legal_name' => 'CAM PARTS FRANCE',
        'trade_name' => 'Camparts',
        'siren' => '841 535 396',
        'siret' => '841 535 396 00011',
        'vat' => 'FR04841535396',
        'legal_form' => 'SARL',
        'address' => '45 AVENUE VICTOR HUGO BAT.278, 93300 AUBERVILLIERS',
    ];
}

function mail_footer_text(): string
{
    $company = mail_company_profile();
    $supportEmail = trim((string) env('ORDER_ADMIN_EMAIL', 'campartsfr@gmail.com'));

    return implode("\n", [
        '---',
        $company['legal_name'],
        'SIREN: ' . $company['siren'] . ' | SIRET: ' . $company['siret'],
        'TVA: ' . $company['vat'] . ' | Forme: ' . $company['legal_form'],
        'Adresse: ' . $company['address'],
        'Support: ' . ($supportEmail !== '' ? $supportEmail : 'campartsfr@gmail.com'),
        'Mentions legales et politique de confidentialite disponibles sur le site.',
    ]);
}

function mail_footer_html(): string
{
    $company = mail_company_profile();
    $supportEmail = trim((string) env('ORDER_ADMIN_EMAIL', 'campartsfr@gmail.com'));
    $support = $supportEmail !== '' ? $supportEmail : 'campartsfr@gmail.com';

    return '<div style="margin-top:20px;padding:14px 16px;border:1px solid #dbe3f2;border-radius:10px;background:#f8fbff;color:#3e4c66;font-size:12px;line-height:1.6;">'
        . '<strong style="color:#1f2b46;">' . mail_escape_html($company['legal_name']) . '</strong><br>'
        . 'SIREN: ' . mail_escape_html($company['siren']) . ' | SIRET: ' . mail_escape_html($company['siret']) . '<br>'
        . 'TVA: ' . mail_escape_html($company['vat']) . ' | Forme: ' . mail_escape_html($company['legal_form']) . '<br>'
        . 'Adresse: ' . mail_escape_html($company['address']) . '<br>'
        . 'Support: <a href="mailto:' . mail_escape_html($support) . '" style="color:#1f63ff;text-decoration:none;">' . mail_escape_html($support) . '</a><br>'
        . 'Mentions legales et politique de confidentialite disponibles sur le site.'
        . '</div>';
}

function mail_summary_table_html(array $rows): string
{
    if ($rows === []) {
        return '';
    }

    $html = '<table role="presentation" cellpadding="0" cellspacing="0" style="width:100%;border-collapse:collapse;margin:14px 0;border:1px solid #dbe3f2;border-radius:10px;overflow:hidden;">';
    foreach ($rows as $row) {
        $label = mail_escape_html(trim((string) ($row['label'] ?? '')));
        $value = mail_escape_html(trim((string) ($row['value'] ?? '')));
        if ($label === '' || $value === '') {
            continue;
        }

        $html .= '<tr>'
            . '<td style="padding:10px 12px;border-bottom:1px solid #e7edf9;background:#f8fbff;color:#546583;font-size:13px;width:40%;">' . $label . '</td>'
            . '<td style="padding:10px 12px;border-bottom:1px solid #e7edf9;color:#1f2b46;font-size:13px;font-weight:600;">' . $value . '</td>'
            . '</tr>';
    }
    $html .= '</table>';

    return $html;
}

function mail_base_layout_html(
    string $title,
    string $subtitle,
    string $badge,
    string $contentHtml,
    string $preheader = ''
): string {
    $titleEsc = mail_escape_html($title);
    $subtitleEsc = mail_escape_html($subtitle);
    $badgeEsc = mail_escape_html($badge);
    $preheaderEsc = mail_escape_html($preheader);
    $company = mail_company_profile();
    $footerHtml = mail_footer_html();

    $preheaderBlock = $preheaderEsc !== ''
        ? '<div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;">' . $preheaderEsc . '</div>'
        : '';

    return '<!doctype html>'
        . '<html lang="fr"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0">'
        . '<title>' . $titleEsc . '</title></head>'
        . '<body style="margin:0;padding:0;background:#eff3fb;font-family:Arial,Helvetica,sans-serif;color:#1f2b46;">'
        . $preheaderBlock
        . '<table role="presentation" cellpadding="0" cellspacing="0" style="width:100%;padding:24px 10px;background:#eff3fb;">'
        . '<tr><td align="center">'
        . '<table role="presentation" cellpadding="0" cellspacing="0" style="width:100%;max-width:680px;border-collapse:collapse;">'
        . '<tr><td style="padding:0 0 14px 0;color:#5b6f92;font-size:12px;">' . mail_escape_html($company['trade_name']) . '</td></tr>'
        . '<tr><td style="border-radius:14px;overflow:hidden;background:#ffffff;border:1px solid #dbe3f2;">'
        . '<div style="padding:18px 20px;background:linear-gradient(135deg,#1f63ff 0%,#1949bf 100%);color:#ffffff;">'
        . '<div style="font-size:12px;opacity:0.9;letter-spacing:0.3px;">' . $badgeEsc . '</div>'
        . '<h1 style="margin:8px 0 4px 0;font-size:22px;line-height:1.2;">' . $titleEsc . '</h1>'
        . '<p style="margin:0;font-size:14px;opacity:0.95;">' . $subtitleEsc . '</p>'
        . '</div>'
        . '<div style="padding:18px 20px;">' . $contentHtml . $footerHtml . '</div>'
        . '</td></tr>'
        . '<tr><td style="padding:10px 2px 0 2px;color:#7384a4;font-size:11px;">Email automatique Camparts - ne pas repondre directement a ce message.</td></tr>'
        . '</table></td></tr></table></body></html>';
}

function send_brevo_mail(string $to, string $subject, string $body, string $htmlBody = ''): bool
{
    $apiKey = trim((string) env('BREVO_API_KEY', ''));
    if ($apiKey === '') {
        mail_log_event('BREVO_CONFIG_MISSING', $to, $subject, $body);
        return false;
    }

    $fromEmail = trim((string) env('MAIL_FROM', ''));
    if (!filter_var($fromEmail, FILTER_VALIDATE_EMAIL)) {
        mail_log_event('BREVO_SENDER_INVALID', $to, $subject, $body);
        return false;
    }

    $fromName = trim((string) env('MAIL_FROM_NAME', 'Camparts'));
    $endpoint = trim((string) env('BREVO_API_URL', 'https://api.brevo.com/v3/smtp/email'));
    $timeout = (int) env('BREVO_TIMEOUT_SECONDS', '8');
    if ($timeout < 3) {
        $timeout = 3;
    }
    if ($timeout > 30) {
        $timeout = 30;
    }

    $sender = ['email' => $fromEmail];
    if ($fromName !== '') {
        $sender['name'] = $fromName;
    }

    $payload = [
        'sender' => $sender,
        'to' => [
            ['email' => $to],
        ],
        'subject' => $subject,
        'textContent' => $body,
    ];
    if (trim($htmlBody) !== '') {
        $payload['htmlContent'] = $htmlBody;
    }

    $json = json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if (!is_string($json) || $json === '') {
        mail_log_event('BREVO_JSON_FAIL', $to, $subject, $body);
        return false;
    }

    if (function_exists('curl_init')) {
        $ch = curl_init($endpoint);
        if ($ch === false) {
            mail_log_event('BREVO_CURL_INIT_FAIL', $to, $subject, $body);
            return false;
        }

        curl_setopt_array($ch, [
            CURLOPT_POST => true,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HTTPHEADER => [
                'Accept: application/json',
                'Content-Type: application/json',
                'api-key: ' . $apiKey,
            ],
            CURLOPT_POSTFIELDS => $json,
            CURLOPT_TIMEOUT => $timeout,
        ]);

        $response = curl_exec($ch);
        $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $curlError = curl_error($ch);
        curl_close($ch);

        $ok = $httpCode >= 200 && $httpCode < 300;
        if ($ok) {
            return true;
        }

        $errorDetails = trim(($curlError !== '' ? $curlError . ' ' : '') . (string) $response);
        if ($errorDetails === '') {
            $errorDetails = 'HTTP ' . $httpCode;
        }
        mail_log_event('BREVO_FAIL', $to, $subject, $errorDetails);
        return false;
    }

    $headers = [
        'Accept: application/json',
        'Content-Type: application/json',
        'api-key: ' . $apiKey,
    ];

    $context = stream_context_create([
        'http' => [
            'method' => 'POST',
            'header' => implode("\r\n", $headers),
            'content' => $json,
            'timeout' => $timeout,
            'ignore_errors' => true,
        ],
    ]);

    $response = @file_get_contents($endpoint, false, $context);
    $lastError = error_get_last();
    $statusLine = '';
    if (isset($http_response_header[0]) && is_string($http_response_header[0])) {
        $statusLine = $http_response_header[0];
    }
    $ok = str_contains($statusLine, ' 200 ')
        || str_contains($statusLine, ' 201 ')
        || str_contains($statusLine, ' 202 ');
    if ($ok) {
        return true;
    }

    $errorDetails = trim($statusLine . ' ' . (string) $response);
    if (
        $errorDetails === ''
        && $response === false
        && is_array($lastError)
        && isset($lastError['message'])
    ) {
        $errorDetails = trim((string) $lastError['message']);
    }
    if (!extension_loaded('openssl')) {
        $errorDetails = trim($errorDetails . ' [openssl extension missing]');
    }
    if ($errorDetails === '') {
        $errorDetails = 'HTTP unknown';
    }
    mail_log_event('BREVO_FAIL', $to, $subject, $errorDetails);

    return false;
}

function send_plain_mail(
    string $to,
    string $subject,
    string $body,
    array $extraHeaders = [],
    string $htmlBody = ''
): bool {
    $to = trim($to);
    if (!filter_var($to, FILTER_VALIDATE_EMAIL)) {
        return false;
    }

    $from = trim((string) env('MAIL_FROM', 'campartsfr@gmail.com'));
    $headers = [
        'MIME-Version: 1.0',
        (trim($htmlBody) !== '' ? 'Content-Type: text/html; charset=UTF-8' : 'Content-Type: text/plain; charset=UTF-8'),
        'From: ' . $from,
    ];

    foreach ($extraHeaders as $header) {
        $header = trim((string) $header);
        if ($header !== '') {
            $headers[] = $header;
        }
    }

    $transport = mail_transport_mode();
    if ($transport === 'off') {
        mail_log_event('MAIL_OFF', $to, $subject, $body);
        return false;
    }
    if ($transport === 'log') {
        mail_log_event('MAIL_LOG_ONLY', $to, $subject, $body);
        return true;
    }
    if ($transport === 'brevo') {
        $ok = send_brevo_mail($to, $subject, $body, $htmlBody);
        if (!$ok) {
            mail_log_event('MAIL_FAIL_BREVO', $to, $subject, $body);
        }
        return $ok;
    }

    $mailContent = trim($htmlBody) !== '' ? $htmlBody : $body;
    $ok = @mail($to, $subject, $mailContent, implode("\r\n", $headers));
    if ($ok) {
        return true;
    }

    mail_log_event('MAIL_FAIL', $to, $subject, $body);

    return false;
}

function mail_collect_recipients_from_env(string ...$keys): array
{
    $recipients = [];
    foreach ($keys as $key) {
        $raw = trim((string) env($key, ''));
        if ($raw === '') {
            continue;
        }

        $parts = preg_split('/[;,\\s]+/', $raw) ?: [];
        foreach ($parts as $part) {
            $email = strtolower(trim((string) $part));
            if ($email === '' || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
                continue;
            }
            $recipients[$email] = true;
        }
    }

    return array_keys($recipients);
}

function mail_admin_recipients(): array
{
    $recipients = mail_collect_recipients_from_env('ORDER_ADMIN_EMAIL', 'ORDER_ADMIN_EMAILS');
    $fallback = 'campartsfr@gmail.com';
    if (!in_array($fallback, $recipients, true)) {
        $recipients[] = $fallback;
    }

    return array_values(array_unique(array_filter($recipients)));
}

function mail_send_to_recipients(array $recipients, string $subject, string $body, string $htmlBody = ''): array
{
    $success = [];
    $failed = [];

    foreach ($recipients as $recipient) {
        $email = strtolower(trim((string) $recipient));
        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
            continue;
        }

        if (send_plain_mail($email, $subject, $body, [], $htmlBody)) {
            $success[] = $email;
        } else {
            $failed[] = $email;
        }
    }

    return [
        'sent' => $success !== [],
        'success' => $success,
        'failed' => $failed,
    ];
}

function send_order_notification_emails(array $order, array $payload): array
{
    $adminRecipients = mail_admin_recipients();
    $customerMail = trim((string) (
        $payload['utilisateur']['mail']
        ?? $payload['utilisateur']['email']
        ?? ''
    ));
    $customerName = trim((string) (
        $payload['utilisateur']['nom']
        ?? $payload['utilisateur']['name']
        ?? $customerMail
    ));

    $reference = trim((string) ($order['reference'] ?? ''));
    if ($reference === '') {
        $reference = 'CMD-' . date('Ymd-His');
    }

    $createdAt = (string) ($order['created_at'] ?? date('Y-m-d H:i:s'));
    $lines = is_array($order['lines'] ?? null) ? $order['lines'] : [];
    $totalFromOrder = mail_to_float($order['total'] ?? ($order['total_ttc'] ?? 0), 0.0);

    $lineTextRows = [];
    $lineHtmlRows = '';
    $itemCount = 0;
    $subtotalHt = 0.0;
    $lineIndex = 0;

    foreach ($lines as $line) {
        if (!is_array($line)) {
            continue;
        }

        $lineIndex++;
        $qty = max(1, (int) ($line['qty'] ?? 1));
        $unitPrice = max(0.0, mail_to_float($line['prix_unitaire'] ?? 0.0, 0.0));
        $lineTotal = round($unitPrice * $qty, 2);
        $itemCount += $qty;
        $subtotalHt += $lineTotal;

        $lineRef = trim((string) ($line['reference'] ?? ''));
        $lineName = trim((string) ($line['nom'] ?? 'Article'));
        if ($lineRef === '') {
            $lineRef = '#L' . $lineIndex;
        }
        if ($lineName === '') {
            $lineName = 'Article';
        }

        $lineTextRows[] = $lineIndex . '. '
            . $lineRef . ' | '
            . $lineName . ' | '
            . $qty . ' x ' . mail_format_money_eur($unitPrice)
            . ' = ' . mail_format_money_eur($lineTotal);

        $lineHtmlRows .= '<tr>'
            . '<td style="padding:8px 10px;border-bottom:1px solid #e7edf9;font-size:12px;color:#2f3f60;">' . mail_escape_html($lineRef) . '</td>'
            . '<td style="padding:8px 10px;border-bottom:1px solid #e7edf9;font-size:12px;color:#2f3f60;">' . mail_escape_html($lineName) . '</td>'
            . '<td style="padding:8px 10px;border-bottom:1px solid #e7edf9;font-size:12px;color:#2f3f60;text-align:center;">' . $qty . '</td>'
            . '<td style="padding:8px 10px;border-bottom:1px solid #e7edf9;font-size:12px;color:#2f3f60;text-align:right;">' . mail_escape_html(mail_format_money_eur($unitPrice)) . '</td>'
            . '<td style="padding:8px 10px;border-bottom:1px solid #e7edf9;font-size:12px;color:#1f2b46;text-align:right;font-weight:700;">' . mail_escape_html(mail_format_money_eur($lineTotal)) . '</td>'
            . '</tr>';
    }

    if ($lineTextRows === []) {
        $lineTextRows[] = '- Details des lignes indisponibles.';
    }
    if ($lineHtmlRows === '') {
        $lineHtmlRows = '<tr><td colspan="5" style="padding:10px;border-bottom:1px solid #e7edf9;font-size:12px;color:#687b9e;">Details des lignes indisponibles.</td></tr>';
    }

    $subtotalHt = round($subtotalHt, 2);
    if ($itemCount <= 0) {
        $itemCount = max(1, (int) mail_to_float($order['item_count'] ?? 0, 1));
    }

    $totalTtc = $totalFromOrder > 0 ? $totalFromOrder : round($subtotalHt * 1.2, 2);
    $customerDisplayName = $customerName !== '' ? $customerName : 'Client';

    $customerSubject = 'Confirmation commande ' . $reference;
    $customerBody = implode("\n", [
        'Bonjour ' . $customerDisplayName . ',',
        '',
        'Votre commande a bien ete enregistree.',
        'Reference: ' . $reference,
        'Date: ' . $createdAt,
        'Articles: ' . $itemCount,
        'Total TTC: ' . mail_format_money_eur($totalTtc),
        '',
        'Lignes de commande:',
        implode("\n", $lineTextRows),
        '',
        'Merci pour votre confiance.',
        mail_footer_text(),
    ]);

    $customerSummary = mail_summary_table_html([
        ['label' => 'Reference', 'value' => $reference],
        ['label' => 'Date', 'value' => $createdAt],
        ['label' => 'Articles', 'value' => (string) $itemCount],
        ['label' => 'Sous-total HT', 'value' => mail_format_money_eur($subtotalHt)],
        ['label' => 'Total TTC', 'value' => mail_format_money_eur($totalTtc)],
    ]);
    $customerLinesTable = '<table role="presentation" cellpadding="0" cellspacing="0" style="width:100%;border-collapse:collapse;border:1px solid #dbe3f2;border-radius:10px;overflow:hidden;">'
        . '<tr style="background:#f4f8ff;color:#506284;font-size:12px;">'
        . '<th align="left" style="padding:8px 10px;border-bottom:1px solid #dbe3f2;">Ref</th>'
        . '<th align="left" style="padding:8px 10px;border-bottom:1px solid #dbe3f2;">Article</th>'
        . '<th align="center" style="padding:8px 10px;border-bottom:1px solid #dbe3f2;">Qt</th>'
        . '<th align="right" style="padding:8px 10px;border-bottom:1px solid #dbe3f2;">PU HT</th>'
        . '<th align="right" style="padding:8px 10px;border-bottom:1px solid #dbe3f2;">Total HT</th>'
        . '</tr>'
        . $lineHtmlRows
        . '</table>';
    $customerHtml = mail_base_layout_html(
        'Confirmation de commande',
        'Votre achat a ete enregistre avec succes.',
        'Commande ' . $reference,
        '<p style="margin:0 0 12px 0;font-size:14px;color:#344869;">Bonjour <strong>' . mail_escape_html($customerDisplayName) . '</strong>, votre commande est en cours de traitement.</p>'
        . $customerSummary
        . '<h3 style="margin:18px 0 8px 0;font-size:15px;color:#1f2b46;">Detail des articles</h3>'
        . $customerLinesTable,
        'Commande ' . $reference . ' confirmee'
    );

    $adminSubject = 'Nouvelle commande ' . $reference;
    $adminBody = implode("\n", [
        'Nouvelle commande recue.',
        'Reference: ' . $reference,
        'Date: ' . $createdAt,
        'Client: ' . ($customerMail !== '' ? $customerMail : 'inconnu'),
        'Articles: ' . $itemCount,
        'Total TTC: ' . mail_format_money_eur($totalTtc),
        '',
        'Lignes de commande:',
        implode("\n", $lineTextRows),
        '',
        'Action: verifier et preparer la commande dans le panel admin.',
        mail_footer_text(),
    ]);
    $adminSummary = mail_summary_table_html([
        ['label' => 'Reference', 'value' => $reference],
        ['label' => 'Date', 'value' => $createdAt],
        ['label' => 'Client', 'value' => ($customerMail !== '' ? $customerMail : 'inconnu')],
        ['label' => 'Articles', 'value' => (string) $itemCount],
        ['label' => 'Total TTC', 'value' => mail_format_money_eur($totalTtc)],
    ]);
    $adminHtml = mail_base_layout_html(
        'Nouvelle commande client',
        'Une nouvelle commande vient d etre placee.',
        'Admin',
        $adminSummary
        . '<h3 style="margin:18px 0 8px 0;font-size:15px;color:#1f2b46;">Lignes commande</h3>'
        . $customerLinesTable
        . '<p style="margin:14px 0 0 0;font-size:13px;color:#425475;"><strong>Action requise:</strong> verifier la commande, le stock, puis mettre a jour le statut.</p>',
        'Nouvelle commande ' . $reference
    );

    $customerSent = $customerMail !== ''
        ? send_plain_mail($customerMail, $customerSubject, $customerBody, [], $customerHtml)
        : false;
    $adminDelivery = mail_send_to_recipients($adminRecipients, $adminSubject, $adminBody, $adminHtml);

    return [
        'customer_email' => $customerMail,
        'customer_sent' => $customerSent,
        'admin_email' => $adminRecipients[0] ?? '',
        'admin_emails' => $adminRecipients,
        'admin_sent' => (bool) ($adminDelivery['sent'] ?? false),
        'admin_sent_count' => count((array) ($adminDelivery['success'] ?? [])),
        'admin_failed_count' => count((array) ($adminDelivery['failed'] ?? [])),
    ];
}

function send_low_stock_alert_emails(array $order): array
{
    $adminRecipients = mail_admin_recipients();
    if ($adminRecipients === []) {
        return [
            'sent' => false,
            'items' => [],
        ];
    }

    $lines = $order['lines'] ?? [];
    if (!is_array($lines) || $lines === []) {
        return [
            'sent' => false,
            'items' => [],
        ];
    }

    $articleIds = [];
    foreach ($lines as $line) {
        if (!is_array($line)) {
            continue;
        }
        $articleId = (int) ($line['article_id'] ?? 0);
        if ($articleId > 0) {
            $articleIds[] = $articleId;
        }
    }
    $articleIds = array_values(array_unique($articleIds));

    if ($articleIds === []) {
        return [
            'sent' => false,
            'items' => [],
        ];
    }

    $threshold = (int) env('LOW_STOCK_ALERT_THRESHOLD', '0');
    if ($threshold < 0) {
        $threshold = 0;
    }

    $articles = repo_find_articles_by_ids($articleIds);
    $depleted = [];
    foreach ($articleIds as $articleId) {
        $article = $articles[$articleId] ?? null;
        if (!is_array($article)) {
            continue;
        }
        $remainingStock = (int) ($article['stock'] ?? 0);
        if ($remainingStock <= $threshold) {
            $depleted[] = [
                'article_id' => $articleId,
                'reference' => (string) ($article['reference'] ?? ''),
                'nom' => (string) ($article['nom'] ?? ''),
                'stock' => $remainingStock,
            ];
        }
    }

    if ($depleted === []) {
        return [
            'sent' => false,
            'items' => [],
        ];
    }

    $reference = (string) ($order['reference'] ?? '');
    $subject = 'Alerte stock faible apres commande ' . $reference;
    $linesText = array_map(
        static fn (array $item): string => '- #' . $item['article_id']
            . ' | ' . $item['reference']
            . ' | ' . $item['nom']
            . ' | stock=' . $item['stock'],
        $depleted
    );
    $body = implode("\n", [
        'Des articles sont en stock faible apres commande.',
        'Reference commande: ' . $reference,
        'Seuil alerte: ' . $threshold,
        'Date: ' . date('Y-m-d H:i:s'),
        '',
        ...$linesText,
        '',
        mail_footer_text(),
    ]);

    $delivery = mail_send_to_recipients($adminRecipients, $subject, $body);

    return [
        'sent' => (bool) ($delivery['sent'] ?? false),
        'admin_emails' => $adminRecipients,
        'admin_sent_count' => count((array) ($delivery['success'] ?? [])),
        'admin_failed_count' => count((array) ($delivery['failed'] ?? [])),
        'items' => $depleted,
    ];
}

function send_account_registration_notification_emails(array $userPayload, bool $isAdminSignup = false): array
{
    $customerMail = strtolower(trim((string) ($userPayload['mail'] ?? $userPayload['email'] ?? '')));
    $nom = trim((string) ($userPayload['nom'] ?? ''));
    $prenom = trim((string) ($userPayload['prenom'] ?? ''));
    $numero = trim((string) ($userPayload['numero'] ?? ''));
    $adresse = trim((string) ($userPayload['adresse'] ?? ''));
    $siret = trim((string) ($userPayload['siret'] ?? ''));

    $displayName = trim($nom . ' ' . $prenom);
    if ($displayName === '') {
        $displayName = $customerMail !== '' ? $customerMail : 'Client';
    }

    $createdAt = date('Y-m-d H:i:s');
    $adminRecipients = mail_admin_recipients();
    $accountTypeLabel = $isAdminSignup ? 'Administrateur' : 'Client';
    $accountStatusLabel = $isAdminSignup ? 'Actif' : 'En attente de validation';

    $customerSubject = $isAdminSignup
        ? 'Compte admin Camparts cree'
        : 'Compte Camparts cree';
    $customerBody = implode("\n", [
        'Bonjour ' . $displayName . ',',
        '',
        $isAdminSignup
            ? 'Votre compte administrateur Camparts a ete cree.'
            : 'Votre compte Camparts a bien ete cree.',
        'Type de compte: ' . $accountTypeLabel,
        'Statut: ' . $accountStatusLabel,
        'Date de creation: ' . $createdAt,
        '',
        $isAdminSignup
            ? 'Vous pouvez des a present vous connecter.'
            : 'Un administrateur doit valider votre compte avant la premiere connexion.',
        '',
        'Merci,',
        mail_footer_text(),
    ]);
    $customerHtml = mail_base_layout_html(
        'Creation de compte',
        $isAdminSignup
            ? 'Votre acces administrateur est actif.'
            : 'Votre compte est cree, validation admin en attente.',
        $accountTypeLabel,
        '<p style="margin:0 0 12px 0;font-size:14px;color:#344869;">Bonjour <strong>' . mail_escape_html($displayName) . '</strong>, merci pour votre inscription.</p>'
        . mail_summary_table_html([
            ['label' => 'Nom', 'value' => $displayName],
            ['label' => 'Email', 'value' => ($customerMail !== '' ? $customerMail : '-')],
            ['label' => 'Type de compte', 'value' => $accountTypeLabel],
            ['label' => 'Statut', 'value' => $accountStatusLabel],
            ['label' => 'Date de creation', 'value' => $createdAt],
        ])
        . '<p style="margin:14px 0 0 0;font-size:13px;color:#425475;">'
        . ($isAdminSignup
            ? 'Vous pouvez maintenant utiliser toutes les fonctions d administration.'
            : 'Vous recevrez une confirmation des que le compte sera valide.')
        . '</p>',
        'Inscription Camparts'
    );

    $adminSubject = $isAdminSignup
        ? 'Nouveau compte administrateur cree'
        : 'Nouveau compte en attente de validation';
    $adminBody = implode("\n", [
        $isAdminSignup
            ? 'Un compte administrateur vient d etre cree.'
            : 'Nouveau compte client cree.',
        'Date: ' . $createdAt,
        'Nom: ' . $displayName,
        'Email: ' . ($customerMail !== '' ? $customerMail : 'inconnu'),
        'Telephone: ' . ($numero !== '' ? $numero : '-'),
        'Adresse: ' . ($adresse !== '' ? $adresse : '-'),
        'SIRET: ' . ($siret !== '' ? $siret : '-'),
        'Type de compte: ' . $accountTypeLabel,
        '',
        $isAdminSignup
            ? 'Action: verifier les droits admin dans le panel.'
            : 'Action requise: valider/refuser depuis le panel admin > Comptes.',
        '',
        mail_footer_text(),
    ]);
    $adminHtml = mail_base_layout_html(
        'Nouvelle inscription',
        $isAdminSignup
            ? 'Creation d un compte administrateur.'
            : 'Compte client en attente de validation.',
        'Admin',
        mail_summary_table_html([
            ['label' => 'Date', 'value' => $createdAt],
            ['label' => 'Nom', 'value' => $displayName],
            ['label' => 'Email', 'value' => ($customerMail !== '' ? $customerMail : 'inconnu')],
            ['label' => 'Telephone', 'value' => ($numero !== '' ? $numero : '-')],
            ['label' => 'Adresse', 'value' => ($adresse !== '' ? $adresse : '-')],
            ['label' => 'SIRET', 'value' => ($siret !== '' ? $siret : '-')],
            ['label' => 'Type de compte', 'value' => $accountTypeLabel],
        ])
        . '<p style="margin:14px 0 0 0;font-size:13px;color:#425475;"><strong>Action:</strong> '
        . ($isAdminSignup
            ? 'verifier les droits et la securite du compte admin.'
            : 'valider ou refuser le compte depuis Admin > Comptes.')
        . '</p>',
        'Inscription utilisateur'
    );

    $customerSent = $customerMail !== ''
        ? send_plain_mail($customerMail, $customerSubject, $customerBody, [], $customerHtml)
        : false;
    $adminDelivery = mail_send_to_recipients($adminRecipients, $adminSubject, $adminBody, $adminHtml);

    return [
        'customer_email' => $customerMail,
        'customer_sent' => $customerSent,
        'admin_email' => $adminRecipients[0] ?? '',
        'admin_emails' => $adminRecipients,
        'admin_sent' => (bool) ($adminDelivery['sent'] ?? false),
        'admin_sent_count' => count((array) ($adminDelivery['success'] ?? [])),
        'admin_failed_count' => count((array) ($adminDelivery['failed'] ?? [])),
    ];
}
