<?php

namespace App\Services;

use App\Models\Campaign;
use App\Models\User;

class BusinessSettings
{
    /**
     * Resolve the "Email Settings" section (Settings > Email Settings) that
     * should apply to a given campaign send, with sensible defaults filled
     * in for anything unset. Settings are stored per-user (`users.global_settings`),
     * so we resolve via the campaign's creator  sending happens in queued
     * jobs with no authenticated session, so `auth()->id()` only works as a
     * fallback for request-time calls (test sends, previews) with no campaign yet.
     */
    public static function emailSettings(?int $campaignId = null): array
    {
        $userId = $campaignId ? Campaign::find($campaignId)?->user_id : null;
        $userId ??= auth()->id();

        $stored = $userId ? (User::find($userId)?->global_settings['email'] ?? []) : [];

        return array_merge([
            'from_name'                => '',
            'from_email'               => '',
            'reply_to_name'            => '',
            'reply_to_email'           => '',
            'rate_limit_per_second'    => 15,
            'tracking_enabled'         => true,
            'footer_notice'            => "You're receiving this email because you subscribed to our newsletter.",
            'footer_copyright'         => '© ' . date('Y') . ' Your Company · All rights reserved',
            'footer_show_unsubscribe'  => true,
            'footer_show_privacy'      => true,
            'footer_privacy_url'       => '',
            'unsubscribe_redirect_url' => '',
        ], array_filter($stored, fn ($v) => $v !== null && $v !== ''));
    }

    // Whether open/click tracking is allowed for this tenant  some countries'
    // privacy laws require the ability to disable pixel/link tracking entirely.
    public static function trackingEnabled(?int $campaignId = null): bool
    {
        return (bool) self::emailSettings($campaignId)['tracking_enabled'];
    }

    /**
     * The tenant's configured timezone (Settings > General Settings), used to
     * drive all campaign scheduling/sending. Resolution order matches
     * emailSettings(): explicit $userId, else via the campaign's owner, else
     * the current session  this must work from queued jobs/console commands
     * with no authenticated session, so callers there should always pass the
     * campaign's user_id explicitly.
     */
    public static function timezone(?int $userId = null, ?int $campaignId = null): string
    {
        $userId ??= $campaignId ? Campaign::find($campaignId)?->user_id : null;
        $userId ??= auth()->id();

        $stored = $userId ? (User::find($userId)?->global_settings['general']['timezone'] ?? null) : null;

        return $stored ?: config('app.timezone');
    }

    // Settings > Business Setup  not a sender identity, purely a source of
    // {{business_name}}/{{business_logo}}/{{business_address}} merge tags a
    // user can drop anywhere in a campaign's content, header, or footer.
    public static function business(?int $campaignId = null): array
    {
        $userId = $campaignId ? Campaign::find($campaignId)?->user_id : null;
        $userId ??= auth()->id();

        $stored = $userId ? (User::find($userId)?->global_settings['business'] ?? []) : [];

        return array_merge([
            'name'    => '',
            'logo'    => '',
            'address' => '',
        ], array_filter($stored, fn ($v) => $v !== null && $v !== ''));
    }

    /**
     * Merge-tag values for Business Setup fields, keyed to match how they're
     * typed in content: {{business_name}}, {{business_logo}}, {{business_address}}.
     * The logo path is resolved to an absolute URL so it works when dropped
     * straight into an <img src="{{business_logo}}"> in an HTML block.
     */
    public static function mergeTags(?int $campaignId = null): array
    {
        $business = self::business($campaignId);

        $logo = $business['logo'];
        if ($logo && !preg_match('#^(https?://|data:)#i', $logo)) {
            $logo = rtrim(config('app.url'), '/') . '/' . ltrim($logo, '/');
        }

        return [
            'business_name'    => $business['name'],
            'business_logo'    => $logo,
            'business_address' => $business['address'],
        ];
    }
}
