<?php

declare(strict_types=1);

namespace App\Services;

use App\Core\Database;

/**
 * EmailSignatureService
 *
 * Appends a per-business-line signature/footer to any outbound email
 * body — company name, phone, website, social links, and a physical
 * mailing address. This is used by every send path (campaigns,
 * automation, and personal emails) via the single MailService::send()
 * choke point, so a signature is never something a caller has to
 * remember to add — it's automatic once a business_line_id is known.
 *
 * The physical address matters beyond looking professional: CASL
 * (Canada) and CAN-SPAM (US) both require a valid postal address in
 * commercial email, and its absence is itself a spam-filter signal —
 * so this genuinely helps deliverability, not just appearance.
 */
final class EmailSignatureService
{
    /** In-process cache — a bulk send can call this hundreds of times for the same business line in one worker tick. */
    private array $cache = [];

    public function appendSignature(string $bodyHtml, ?int $businessLineId): string
    {
        if ($businessLineId === null) {
            return $bodyHtml;
        }

        $bl = $this->businessLine($businessLineId);
        if ($bl === null || !$this->hasMeaningfulDetails($bl)) {
            return $bodyHtml;
        }

        return $bodyHtml . $this->render($bl);
    }

    /** True once at least one real contact detail is filled in — avoids appending a barren footer (just a company name, nothing else) for a business line that hasn't been configured on Settings > Company Details yet. */
    private function hasMeaningfulDetails(array $bl): bool
    {
        foreach (['support_phone', 'website', 'address_line1', 'facebook_url', 'instagram_url', 'linkedin_url', 'tiktok_url', 'logo_url'] as $field) {
            if (!empty($bl[$field])) {
                return true;
            }
        }

        return false;
    }

    private function businessLine(int $id): ?array
    {
        if (!array_key_exists($id, $this->cache)) {
            $stmt = Database::connection()->prepare('SELECT * FROM business_lines WHERE id = :id');
            $stmt->execute(['id' => $id]);
            $row = $stmt->fetch();
            $this->cache[$id] = $row === false ? null : $row;
        }

        return $this->cache[$id];
    }

    private function render(array $bl): string
    {
        $name = e($bl['legal_name'] ?: $bl['name']);
        $phone = $bl['support_phone'] ?? null;
        $email = $bl['support_email'] ?? null;
        $website = $bl['website'] ?? null;

        $addressParts = array_filter([$bl['address_line1'] ?? null, $bl['city'] ?? null, $bl['province'] ?? null, $bl['postal_code'] ?? null]);
        $address = $addressParts === [] ? null : implode(', ', array_map('e', $addressParts));

        $contactLine = implode(' &nbsp;|&nbsp; ', array_filter([
            $phone ? '<a href="tel:' . e(preg_replace('/[^0-9+]/', '', $phone)) . '" style="color:#667085;text-decoration:none;">' . e($phone) . '</a>' : null,
            $email ? '<a href="mailto:' . e($email) . '" style="color:#667085;text-decoration:none;">' . e($email) . '</a>' : null,
            $website ? '<a href="' . e($website) . '" style="color:#667085;text-decoration:none;">' . e(preg_replace('#^https?://#', '', rtrim($website, '/'))) . '</a>' : null,
        ]));

        $socialIcons = [
            'facebook_url' => 'Facebook', 'instagram_url' => 'Instagram', 'linkedin_url' => 'LinkedIn', 'tiktok_url' => 'TikTok',
        ];
        $socialLinks = [];
        foreach ($socialIcons as $col => $label) {
            if (!empty($bl[$col])) {
                $socialLinks[] = '<a href="' . e($bl[$col]) . '" style="color:#667085;text-decoration:none;margin-right:10px;">' . $label . '</a>';
            }
        }
        $socialLine = $socialLinks === [] ? '' : '<div style="margin-top:6px;">' . implode('', $socialLinks) . '</div>';

        $brandColor = $bl['brand_color'] ?: '#174890';

        $logoCell = '';
        if (!empty($bl['logo_url'])) {
            $logoCell = '<td style="padding-right:14px;vertical-align:top;">'
                . '<img src="' . e($bl['logo_url']) . '" alt="' . $name . '" style="max-width:64px;max-height:64px;display:block;">'
                . '</td>';
        }

        return <<<HTML
            <div style="margin-top:28px;padding-top:16px;border-top:1px solid #E4E7EC;font-family:Arial,Helvetica,sans-serif;font-size:13px;line-height:1.5;color:#667085;">
              <table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>
                {$logoCell}
                <td style="vertical-align:top;">
                  <div style="font-weight:600;color:{$brandColor};">{$name}</div>
                  <div style="margin-top:2px;">{$contactLine}</div>
                  {$socialLine}
                  <div style="margin-top:8px;color:#98A2B3;font-size:11px;">
                    {$address}
                  </div>
                </td>
              </tr></table>
            </div>
            HTML;
    }
}
