<?php

namespace Licenzo\Helper\Settings;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Framework\Support\Arr;
use Licenzo\Helper\Filter;
use Licenzo\Helper\Settings;

class EmailNotificationSetting
{
    private const FOOTER_TEXT = 'Powered by Licenzo';

    public static function licenseExpiryNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'This is a friendly reminder that your license {license.key} for {product.name} will expire on {license.expire_date}. Please renew your license to avoid any interruption in service.' . "\n\n" .
            'Thank you for choosing {site.name}.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        $bodyText = Filter::apply('email/expiry_notification_body', $text); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.InvalidPrefixPassed - false positive

        $data = [
            'subject' => 'License Expiry Reminder: {product.name}',
            'body'    => static::appendFooter((string) $bodyText),
            'enabled' => 'yes'
        ];

        return Filter::apply('email/expiration_notification', $data); // phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.InvalidPrefixPassed - false positive
    }


    public static function customerWelcomeNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'Welcome to {site.name}! Your account is ready to use.' . "\n\n" .
            'We are excited to have you on board.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        $bodyText = Filter::apply('email/welcome_notification_body', $text);

        $data = [
            'subject' => 'Welcome to {site.name}',
            'body'    => static::appendFooter((string) $bodyText),
            'enabled' => 'yes'
        ];

        return Filter::apply('email/welcome_notification', $data);
    }


    public static function maximumActivationsHitNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'You have reached the maximum number of activations for license {license.key}.' . "\n\n" .
            'Please contact us for additional information or support.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        $bodyText = Filter::apply('email/maximum_activations_hit_notification_body', $text);

        $data = [
            'subject' => 'Activation Limit Reached: {product.name}',
            'body'    => static::appendFooter((string) $bodyText),
            'enabled' => 'yes'
        ];

        return Filter::apply('email/maximum_activations_hit_notification', $data);
    }

    public static function licenseActivationNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'We are pleased to inform you that license {license.key} for {product.name} has been successfully activated on {license.domain} on {license.activated_date}.' . "\n\n" .
            'Thank you for your purchase and support.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        $bodyText = Filter::apply('email/license_activation_notification_body', $text);

        $data = [
            'subject' => 'License Activated: {product.name}',
            'body'    => static::appendFooter((string) $bodyText),
            'enabled' => 'yes'
        ];

        return Filter::apply('email/license_activation_notification', $data);
    }

    public static function licenseExpiryWarningNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'Your license {license.key} for {product.name} will expire in {license.days_until_expiry} days on {license.expire_date}.' . "\n\n" .
            'Please renew before it expires to maintain uninterrupted access.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        return [
            'subject' => 'License Expiring Soon: {product.name}',
            'body'    => static::appendFooter($text),
            'enabled' => 'yes',
        ];
    }

    public static function subscriptionRenewedNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'Your subscription has been successfully renewed.' . "\n\n" .
            'Thank you for your continued support.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        return [
            'subject' => 'Subscription Renewed',
            'body'    => static::appendFooter($text),
            'enabled' => 'yes',
        ];
    }

    public static function subscriptionPausedNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'Your subscription has been paused. Your access will remain available until the end of your current billing period.' . "\n\n" .
            'You can resume your subscription at any time from your account.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        return [
            'subject' => 'Subscription Paused',
            'body'    => static::appendFooter($text),
            'enabled' => 'yes',
        ];
    }

    public static function subscriptionResumedNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'Your subscription has been resumed and is now active again.' . "\n\n" .
            'Thank you for staying with us.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        return [
            'subject' => 'Subscription Resumed',
            'body'    => static::appendFooter($text),
            'enabled' => 'yes',
        ];
    }

    public static function subscriptionCanceledNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'Your subscription has been canceled. You will continue to have access until the end of your current billing period.' . "\n\n" .
            'If this was a mistake, please contact us.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        return [
            'subject' => 'Subscription Canceled',
            'body'    => static::appendFooter($text),
            'enabled' => 'yes',
        ];
    }

    public static function subscriptionRequiresActionNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'Your recent payment requires additional verification. Please complete the authentication to continue your subscription.' . "\n\n" .
            'If you need assistance, please contact us.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        return [
            'subject' => 'Action Required: Subscription Payment',
            'body'    => static::appendFooter($text),
            'enabled' => 'yes',
        ];
    }

    public static function paymentFailedNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'We were unable to process your subscription payment. Please update your payment method to avoid any interruption in service.' . "\n\n" .
            'If you believe this is an error, please contact us.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        return [
            'subject' => 'Payment Failed: Action Required',
            'body'    => static::appendFooter($text),
            'enabled' => 'yes',
        ];
    }

    public static function gracePeriodStartedNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'Your subscription payment has failed and a grace period has started. Please update your payment method within the grace period to avoid suspension.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        return [
            'subject' => 'Grace Period Started: Update Payment Required',
            'body'    => static::appendFooter($text),
            'enabled' => 'yes',
        ];
    }

    public static function subscriptionSuspendedNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'Your subscription has been suspended due to a failed payment after the grace period. Please update your payment method and contact us to reactivate your subscription.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        return [
            'subject' => 'Subscription Suspended',
            'body'    => static::appendFooter($text),
            'enabled' => 'yes',
        ];
    }

    public static function renewalReminderNotification()
    {
        $text = 'Dear {customer.name},' . "\n\n" .
            'This is a friendly reminder that your subscription will renew soon. If you need to make any changes, please visit your account.' . "\n\n" .
            'Best regards,' . "\n" .
            '{site.name} Team';

        return [
            'subject' => 'Upcoming Subscription Renewal',
            'body'    => static::appendFooter($text),
            'enabled' => 'yes',
        ];
    }

    public static function all()
    {
        $settings = Settings::getNotificationSettings();

        $defaultValues = [
            'subject' => null,
            'body'    => null,
            'enabled' => null,
        ];

        $map = [
            'customer_welcome'             => static::customerWelcomeNotification(),
            'license_activation'           => static::licenseActivationNotification(),
            'license_expiration'           => static::licenseExpiryNotification(),
            'license_expiry_warning'       => static::licenseExpiryWarningNotification(),
            'maximum_activations'          => static::maximumActivationsHitNotification(),
            'subscription_renewed'         => static::subscriptionRenewedNotification(),
            'subscription_paused'          => static::subscriptionPausedNotification(),
            'subscription_resumed'         => static::subscriptionResumedNotification(),
            'subscription_canceled'        => static::subscriptionCanceledNotification(),
            'subscription_requires_action' => static::subscriptionRequiresActionNotification(),
            'payment_failed'               => static::paymentFailedNotification(),
            'grace_period_started'         => static::gracePeriodStartedNotification(),
            'subscription_suspended'       => static::subscriptionSuspendedNotification(),
            'renewal_reminder'             => static::renewalReminderNotification(),
        ];

        $resolved = [];
        foreach ($map as $key => $defaults) {
            $resolved[$key] = static::resolveNotificationConfig(
                Arr::get($settings, $key, $defaultValues),
                $defaults
            );
        }

        return $resolved;
    }


    public static function update($data = [])
    {
        Settings::updateNotificationSettings($data);
        return static::all();
    }

    private static function resolveNotificationConfig($stored, $defaults)
    {
        $stored = is_array($stored) ? $stored : [];
        $defaults = is_array($defaults) ? $defaults : [];

        $enabled = strtolower(trim((string) Arr::get($stored, 'enabled', Arr::get($defaults, 'enabled', 'no'))));
        if (!in_array($enabled, ['yes', 'no'], true)) {
            $enabled = (string) Arr::get($defaults, 'enabled', 'no');
        }

        $subject = trim((string) Arr::get($stored, 'subject', ''));
        if ($subject === '') {
            $subject = (string) Arr::get($defaults, 'subject', '');
        }

        $body = trim((string) Arr::get($stored, 'body', ''));
        if ($body === '') {
            $body = (string) Arr::get($defaults, 'body', '');
        }

        return [
            'enabled' => $enabled,
            'subject' => $subject,
            'body' => static::appendFooter($body),
        ];
    }

    private static function appendFooter(string $body): string
    {
        $body = trim($body);
        if ($body === '') {
            return static::FOOTER_TEXT;
        }

        if (stripos($body, static::FOOTER_TEXT) !== false) {
            return $body;
        }

        return $body . "\n\n" . static::FOOTER_TEXT;
    }
}
