<?php

namespace IvyForms\Factory\Notification;

use IvyForms\Common\Exceptions\InvalidArgumentException;
use IvyForms\Entity\Notification\Notification as NotificationEntity;
use IvyForms\ValueObjects\Notification\Notification;
use IvyForms\ValueObjects\Notification\NotificationContact;

/**
 * Class NotificationFactory
 *
 * @package IvyForms\Factory\Notification
 */
class NotificationFactory
{
    /**
     * Create a NotificationEntity from an array of data.
     *
     * @param array<string, mixed> $data
     *
     * @return NotificationEntity
     * @throws InvalidArgumentException
     */
    public static function create(array $data): NotificationEntity
    {
        $contact = new NotificationContact(
            $data['sender'] ?? '',
            $data['receiver'] ?? '',
            $data['replyTo'] ?? ''
        );

        $notificationValueObject = new Notification(
            $data['id'] ?? 0,
            $data['name'] ?? '',
            $contact,
            $data['enabled'] ?? true,
            $data['subject'] ?? '',
            $data['message'] ?? '',
            $data['showEmptyFields'] ?? false,
            $data['smartLogic'] ?? false,
            $data['formId'] ?? 0
        );

        $notificationEntity = new NotificationEntity($notificationValueObject);

        if (isset($data['id'])) {
            $notificationEntity->setId($data['id']);
        }

        if (isset($data['name'])) {
            $notificationEntity->setName($data['name']);
        }

        if (isset($data['sender'])) {
            $notificationEntity->getNotificationContact()->setSender($data['sender']);
        }

        if (isset($data['replyTo'])) {
            $notificationEntity->getNotificationContact()->setReplyTo($data['replyTo']);
        }

        if (isset($data['receiver'])) {
            $notificationEntity->getNotificationContact()->setReceiver($data['receiver']);
        }

        if (isset($data['enabled'])) {
            $notificationEntity->setEnabled($data['enabled']);
        }

        if (isset($data['subject'])) {
            $notificationEntity->setSubject($data['subject']);
        }

        if (isset($data['message'])) {
            $notificationEntity->setMessage(wp_unslash($data['message']));
        }

        if (isset($data['showEmptyFields'])) {
            $notificationEntity->setShowEmptyFields($data['showEmptyFields']);
        }

        if (isset($data['smartLogic'])) {
            $notificationEntity->setSmartLogic($data['smartLogic']);
        }

        if (isset($data['formId'])) {
            $notificationEntity->setFormId($data['formId']);
        }

        return $notificationEntity;
    }
}
