<?php

namespace Velis\App;

use Exception;
use Velis\App;
use Velis\Notification\MobileNotification;
use Velis\Output;

/**
 * Mobile notification base
 *
 * @author Paweł Szołucha <pawel.szolucha@velistech.com>
 */
class MobileNotice extends MobileNotification
{
    public const USER_EDIT = 'user_edit';
    public const CONFIGURATION_EDIT  = 'configuration_edit';
    public const TICKET_EDIT = 'ticket_edit';

    private $users = [];

    public function __construct(
        private string $type,
        private ?array $data = null,
        private ?array $notificationData = null,
        private bool $silent = true
    ) {
    }

    /**
     * Propagates user edit event over push notification
     */
    public function send(): void
    {
        try {
            $fields = [
                "data" => $this->getDataSection(),
                "notification" => $this->notificationData,
            ];

            if (!$this->silent) {
                $fields["apns"] = [
                    "payload" => [
                        "aps" => [
                            "sound" => "default",
                        ],
                    ],
                ];
            }

            $this->setParams($fields);

            foreach ($this->getRecipients() as $recipient) {
                $this->setRecipient($recipient);
                parent::send();
            }
        } catch (Exception $e) {
            // do nothing
        }
    }

    /**
     * Add users that should receive notification
     *
     * @param int[]|int $users User ID or list of user ids
     * @return self
     */
    public function addUsers($users): self
    {
        if (!is_array($users)) {
            $users = [$users];
        }

        array_push($this->users, ...$users);

        return $this;
    }

    /**
     * Returns notification recipients
     * @return string[]
     */
    protected function getRecipients(): array
    {
        return match ($this->type) {
            self::USER_EDIT, self::TICKET_EDIT => array_map(fn($userId) => 'user_' . App::$config->settings->instanceAcro . '_' . $userId, $this->users),
            self::CONFIGURATION_EDIT => ['user_' . App::$config->settings->instanceAcro . '_configuration'],
            default => [],
        };
    }

    /**
     * Returns data section of notification
     *
     * @return array
     */
    protected function getDataSection(): array
    {
        $data = [
            "type" => $this->type,
            "date" => Output::formatIsoDateTime(date('Y-m-d H:i:s')),
        ];

        if (!empty($this->data)) {
            foreach ($this->data as $key => $value) {
                if (is_array($value)) {
                    $data[$key] = Output::jsonEncode($value);
                } else {
                    $data[$key] = $value;
                }
            }
        }

        return $data;
    }
}
