<?php

namespace AppBundle\Mail;

use AppBundle\Entity\User;
use AppBundle\Mail\Mailer;

/**
 * Gestion des newsletter via le fournisseur SendinBlue
 * 
 * @see https://fr.sendinblue.com/ Official site
 */
class NewsletterMailer
{
    private $mailer;
    private $listId;
    private $listIdUnlink;

    /**
     * Constructor
     * 
     * @param  $mailer 
     * @param int $listId 
     * @param int $listIdUnlink 
     */
    public function __construct( Mailer $mailer, int $listId, int $listIdUnlink)
    {
        $this->listId = $listId;
        $this->listIdUnlink = $listIdUnlink;
        $this->mailer = $mailer;
    }

    /**
     * Inscrit ou désinscrit un utilisateur de la newsletter
     *
     * @param User $user Utilisateur concerné
     * @return mixed
     */
    public function subscribe(User $user)
    {
        $data = [
            'email' => $user->getEmail(),
            'attributes' => [
                'NOM' => $user->getLastname(),
                'PRENOM' => $user->getFirstname(),
                'DATE_INSCRIPTION' => date('Y-m-d'),
            ],
            'blacklisted' => false,
            'listid' => [],
            'listid_unlink' => [],
            'blacklisted_sms' => false,
        ];

        if ($user->getNewsletter()) {
            $data['listid'][] = $this->listId;
        } else {
            $data['listid_unlink'][] = $this->listIdUnlink;
        }

        return $this->mailer->create_update_user($data);
    }
}
