<?php

namespace GriffinForms\Includes\Notifications\Channels;

use GriffinForms\Includes\Notifications\NotificationChannelInterface;

class EmailChannel implements NotificationChannelInterface
{
    public function getChannelId(): string
    {
        return 'email';
    }

    public function getLabel(): string
    {
        return __('Email', 'griffinforms-form-builder');
    }

    public function getOwningIntegrationId(): ?string
    {
        return null; // Built-in; always available.
    }

    public function getRequiredFieldType(): ?string
    {
        return 'inputemail';
    }

    public function getRecipientLabel(): string
    {
        return __('Email address', 'griffinforms-form-builder');
    }

    public function supportsStaticRecipients(): bool
    {
        return true;
    }

    public function secureRecipients(array $raw_recipients): array
    {
        $secured = [];

        foreach ($raw_recipients as $item) {
            if (!is_array($item) || empty($item['type']) || !isset($item['value'])) {
                continue;
            }

            $type  = $item['type'] === 'field' ? 'field' : 'static';
            $value = (string) $item['value'];

            if ($type === 'field') {
                $field_id = absint($value);
                if ($field_id > 0) {
                    $secured[] = ['type' => 'field', 'value' => (string) $field_id];
                }
            } else {
                $email = sanitize_email($value);
                if (!empty($email) && is_email($email)) {
                    $secured[] = ['type' => 'static', 'value' => $email];
                }
            }
        }

        return $secured;
    }

    public function send(array $action, array $resolved, array $context): void
    {
        $message_id    = absint($action['message_id'] ?? 0);
        $submission_id = absint($context['submission_id'] ?? 0);
        $form_id       = absint($context['form_id'] ?? 0);

        if (!$message_id || !$submission_id || !$form_id) {
            return;
        }

        $repository = \GriffinForms\Includes\Pipelines\JobRepository::getInstance();

        foreach ($resolved as $recipient) {
            $email = sanitize_email((string) ($recipient['value'] ?? ''));
            if (empty($email) || !is_email($email)) {
                continue;
            }

            $repository->enqueue('notification_dispatch_email', 'notification', $submission_id, $form_id, [
                'notification_id' => $action['id'] ?? '',
                'recipient'       => $email,
                'message_id'      => $message_id,
            ], 10);
        }
    }
}
