<?php

declare(strict_types=1);

require_once __DIR__ . \DIRECTORY_SEPARATOR . '..' . \DIRECTORY_SEPARATOR . 'classes' . \DIRECTORY_SEPARATOR . 'CustomerPush.php';

class NotificationManager
{
    protected \GuzzleHttp\Client $client;

    protected function getPushUrl(): string
    {
        return 'http://mvs-prod-pushd:8080/';
    }

    public function __construct()
    {
        $this->client = new \GuzzleHttp\Client();
    }

    /**
     * Envoi d'une notification à un utilisateur.
     */
    public function sendNotification(CustomerPush $customerPush, string $message): void
    {
        // On enregistre le PushID auprès de plusieurs subscriptions en fonction de l'utilisateur
        $subscribedPushReponse = $this->client->post(
            $this->getPushUrl() . 'subscribers',
            [
                'form_params' => [
                    'proto' => strtolower($customerPush->push_type),
                    'token' => $customerPush->push_id,
                    'lang' => 'fr',
                ],
            ]
        );
        // Récupère l'ID dans PushD
        $subscribedPushId = str_replace('/subscriber/', '', $subscribedPushReponse->getHeader('Location')[0]);

        $this->client->post(
            $this->getPushUrl() . 'subscriber/' . $subscribedPushId . '/subscriptions/mvsmobile_' . $customerPush->id
        );

        // ///////////////////////////////////////
        // / On envoi une notif à l'event ayant le nom d'utilisateur
        $this->client->post(
            $this->getPushUrl() . 'event/mvsmobile_' . $customerPush->id,
            [
                'form_params' => [
                    'msg' => $message,
                ],
            ]
        );
    }
}
