<?php

namespace Velis\Notification;

use Velis\Output;
use Exception;

/**
 * Additional headers trait to be used by Notification, Log and Mail classes
 * @author Olek Procki <olo@velis.pl>
 */
trait HeadersTrait
{
    /**
     * List of acceptable additional headers
     * @var array
     */
    protected static array $_acceptableAdditionalHeaders = [
        'X-External-Ticket-Id',
        'X-Instance-Acro',
        'X-Ticket-Action',
        'X-Ticket-Id',
        'X-Ticket-Title',
    ];


    /**
     * Additional notification mail headers
     * @var array
     */
    protected array $_additionalHeaders = [];


    /**
     * Sets additional header value for notification email
     *
     * @param string $header
     * @param string $value
     *
     * @return \Velis\Notification
     */
    public function setAdditionalHeader($header, $value)
    {
        if (!isset($this->_additionalHeaders)) {
            $this->_additionalHeaders = [];
        }
        if ($value === null) {
            unset($this->_additionalHeaders[$header]);
        } else {
            $this->_additionalHeaders[$header] = $value;
        }

        return $this;
    }


    /**
     * Sets additional headers for notification email passed as array or JSON string
     *
     * @param mixed $headers
     * @return \Velis\Notification
     */
    public function setAdditionalHeaders($headers)
    {
        if (!$headers) {
            return $this;
        }

        // Decode JSON in case headers passed via JSON string
        if (!is_array($headers)) {
            try {
                $headers = Output::jsonDecode($headers);
            } catch (Exception $e) {
                $headers = null;
            }
        }

        if (is_array($headers)) {
            foreach ($headers as $header => $value) {
                $this->setAdditionalHeader($header, $value);
            }
        }

        return $this;
    }


    /**
     * Returns additional headers for notification mail
     * @return array
     */
    public function getAdditionalHeaders()
    {
        return $this->_additionalHeaders;
    }


    /**
     * Returns true if notification has additional headers set to be sent
     * @return bool
     */
    public function hasAdditionalHeaders()
    {
        return is_array($this->_additionalHeaders) &&
               count($this->_additionalHeaders) > 0;
    }


    /**
     * Returns true if $header exists in additional headers
     *
     * @param string $header
     * @return bool
     */
    public function hasAdditionalHeader($header)
    {
        return isset($this->_additionalHeaders[$header]);
    }
}
