<?php

namespace App\Services\EmailCampaign\Drivers;

use App\Models\EmailCampaign;
use App\Models\EmailCampaignLink;
use App\Models\EmailCampaignRecipient;
use App\Services\EmailCampaign\Contracts\EmailCampaignDriverInterface;

abstract class AbstractEmailCampaignDriver implements EmailCampaignDriverInterface
{
    /**
     * Compile campaign HTML body for a recipient: rewrite links + inject open pixel.
     */
    protected function compileBody(EmailCampaign $campaign, ?EmailCampaignRecipient $recipient): string
    {
        $html = (string) ($campaign->content_html ?? '');
        if ($html === '') {
            return '';
        }

        $token = $recipient?->recipient_token ?? 'test';
        $appUrl = rtrim((string) config('app.url'), '/');

        // Rewrite anchor href -> tracking URL
        $html = preg_replace_callback(
            '#<a([^>]*)href=(["\'])(.*?)\2#i',
            function ($m) use ($campaign, $token, $appUrl) {
                $url = $m[3];
                if (! preg_match('#^https?://#i', $url)) {
                    return $m[0];
                }
                $linkHash = substr(md5($campaign->id.'|'.$url), 0, 16);
                EmailCampaignLink::firstOrCreate(
                    ['campaign_id' => $campaign->id, 'link_hash' => $linkHash],
                    ['url' => $url],
                );
                $tracked = "$appUrl/email/campaign-track/click/$token/$linkHash";
                return "<a{$m[1]}href={$m[2]}{$tracked}{$m[2]}";
            },
            $html
        );

        // Inject open pixel before </body> (or append)
        $pixel = '<img src="'.$appUrl.'/email/campaign-track/open/'.$token.'.gif" width="1" height="1" alt="" style="display:none" />';
        if (stripos($html, '</body>') !== false) {
            $html = preg_replace('#</body>#i', $pixel.'</body>', $html, 1);
        } else {
            $html .= $pixel;
        }

        return $html;
    }
}
