<?php
/**
 * Tells the customer what the shop decided.
 *
 * @package SkyServers\Retragere
 */

declare(strict_types=1);

namespace SkyServers\Retragere\Wc\Emails;

use SkyServers\Retragere\Core\EmailComposer;
use SkyServers\Retragere\Wp\Repository;

/**
 * Not a legal obligation - the acknowledgement of receipt is. This one exists
 * because a customer who hears nothing after declaring a withdrawal calls, and
 * then complains.
 */
final class DecisionEmail extends BaseEmail
{
    /** @var string */
    private $outcome = 'aprobata';

    /** @var string */
    private $message = '';

    public function __construct()
    {
        $this->id             = 'ssrc_decision';
        $this->customer_email = true;
        $this->title          = __('Contract withdrawal decision', 'skyservers-retragere-contract');
        $this->description    = __('The response sent to the consumer after the request is processed.', 'skyservers-retragere-contract');
        $this->heading        = __('Response to your request', 'skyservers-retragere-contract');
        $this->subject        = __('Response to the withdrawal request', 'skyservers-retragere-contract');

        parent::__construct();
    }

    public function dispatch(int $recordId, string $outcome, string $message): bool
    {
        $this->recordId = $recordId;
        $this->outcome  = $outcome;
        $this->message  = $message;

        $composed = $this->compose($recordId);

        if (null === $composed) {
            return false;
        }

        $this->bodyHtml  = $composed['html'];
        $this->bodyText  = $composed['text'];
        $this->recipient = (string) get_post_meta($recordId, Repository::META_EMAIL, true);

        if (!$this->is_enabled() || '' === $this->recipient) {
            return false;
        }

        return $this->send(
            $this->get_recipient(),
            $composed['subject'],
            $this->get_content(),
            $this->get_headers(),
            $this->get_attachments()
        );
    }

    /**
     * @param mixed $request
     *
     * @return array{subject:string,html:string,text:string}
     */
    protected function build(
        EmailComposer $composer,
        $request,
        string $reference,
        string $localTime,
        string $timezone
    ): array {
        return $composer->decision($request, $reference, $localTime, $timezone, $this->outcome, $this->message);
    }
}
