<?php

namespace Inside\DESK\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\Lang;
use Inside\DESK\Facades\UrlSigner;

class Newsletter extends Mailable
{
    use Queueable;
    use SerializesModels;

    private array $contents;
    private string $startDate;
    private bool $test;
    private string $userUuid;

    /**
     * @var string
     */
    public $locale;

    public function __construct(array $contents, ?string $locale, string $startDate, bool $test, string $userUuid)
    {
        $this->locale = $locale ?? 'en';
        $this->contents = $contents;
        $this->startDate = $startDate;
        $this->test = $test;
        $this->userUuid = $userUuid;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build(): self
    {
        $trackingPixelUrl = UrlSigner::signedRoute('desk.newsletters.viewed', ['newsletterDate' => strtotime($this->startDate), 'userUuid' => $this->userUuid]);
        $trackingClickUrl = UrlSigner::signedRoute('desk.newsletters.clicked', ['newsletterDate' => strtotime($this->startDate), 'userUuid' => $this->userUuid]);
        $trackingClickNewsRedirectUrl = UrlSigner::signedRoute(
            'desk.newsletters.clicked',
            [
                'newsletterDate' => strtotime($this->startDate),
                'userUuid' => $this->userUuid,
                'redirect' => $this->locale === 'fr' ? 'actualites' : 'news',
            ]
        );

        return $this->markdown('emails.newsletter')->subject(
            Lang::getFromJson('desk.newsletter.subject', [], $this->locale).($this->test ? ' [TEST]' : '')
        )->with(
            [
                'categories' => $this->contents,
                'locale' => $this->locale,
                'time' => $this->locale === 'fr' ? 'fr_FR.utf8' : 'en_US.utf8',
                'startDate' => strtotime($this->startDate),
                'trackingPixelUrl' => $trackingPixelUrl,
                'trackingClickUrl' => $trackingClickUrl,
                'trackingClickNewsRedirectUrl' => $trackingClickNewsRedirectUrl,
            ]
        );
    }
}
