<?php

namespace PloverCRM\Modules\PushNotifications\Services;

use PloverCRM\Core\Plugin;
use PloverCRM\Core\Services\PlaceholderService;

/**
 * Notification Sender Service
 * 
 * Handles sending push notifications to mobile devices
 */
class NotificationSender
{
    /**
     * Default settings
     */
    const DEFAULTS = [
        'title' => 'New Lead Added!',
        'body_template' => '{full_name} | from {city}, {country} | Workspace: {workspace} | Time: {datetime}',
    ];

    /**
     * Send new contact notification
     */
    public static function sendNewContactNotification($subscriber_id, string $providerId = ''): void
    {
        // Get settings
        $options = get_option('plover_crm_push_notifications', []);
        $settings = array_merge(self::DEFAULTS, $options);

        $container = Plugin::getInstance()->getContainer();
        $crmManager = $container->get('crm');
        $crm = $crmManager;

        if ($providerId !== '' && method_exists($crmManager, 'getProviderById')) {
            $provider = $crmManager->getProviderById($providerId);
            if ($provider) {
                $crm = $provider;
            }
        }

        if (!$crm->isAvailable()) {
            return;
        }

        $subscriber = $crm->getContact($subscriber_id);

        if (!$subscriber) {
            return;
        }

        // Check notification lock to prevent duplicates
        $lock_key = 'plover_crm_notification_lock_' . ($subscriber['email'] ?? $subscriber['id']);
        $notification_lock = get_transient($lock_key);
        if ($notification_lock) {
            return;
        }

        // Set lock for 30 seconds
        set_transient($lock_key, true, 30);

        // Parse title and body using PlaceholderService
        $title = PlaceholderService::parse($settings['title'], $subscriber);
        $body = PlaceholderService::parse($settings['body_template'], $subscriber);

        // Prepare notification data
        $site_url = get_site_url();
        $domain = preg_replace('#^https?://#', '', rtrim($site_url, '/'));

        $response = HubPushGateway::sendOperational([
            'title' => $title,
            'body' => $body,
            'subscriber_id' => (int) $subscriber['id'],
            'destination_type' => 'app',
            'destination' => '/leads/' . $subscriber['id'],
        ]);

        // Send web push notifications to browser subscribers
        WebPushSender::send($title, $body, [
            'subscriber_id' => $subscriber['id'],
            'url' => '/leads/' . $subscriber['id'],
            'domain' => $domain,
        ]);

        // Initialize logger
        $logger = new Logger();

        // Log errors
        if (is_wp_error($response)) {
            $error_email = 'dev.webplover@gmail.com';

            wp_mail(
                $error_email,
                'Push Notification Failed',
                sprintf(
                    "Error sending push notification for subscriber: %s\nError: %s\nSite: %s",
                    $subscriber['email'] ?? $subscriber['id'],
                    $response->get_error_message(),
                    $domain
                )
            );

            $logger->logNotificationError($subscriber, $response->get_error_message());
        } else {
            $logger->logNotificationSent($subscriber);
        }
    }
}
