<?php
require 'vendor/autoload.php';
require 'mailhandling.php';

class Mail extends Mailhandling {
    // protected $mbox = null;
    protected $folder = '';
    protected $uid = 0;
    
    public function __construct(?string $templateName = null) {
        parent::__construct();
        if (!$this->connectToImap()) {
            $this->templateName = 'imaperror';
            return;
        }
        $params = $this->getUriParams();
        $this->uid = $params['uid'];
        $this->folder = urldecode($params['folder']);
        $this->content['uid'] = $this->uid;
    }
    
    protected function generateContent(): void {
        $folder = $this->mbox->getFolderByName($this->folder);
        $message = $folder->query()->getMessageByUid($this->uid);
        if (!$message) {
            return;
        }
        $this->content['subject'] = $message->subject;
        $this->content['sender'] = $message->getHeader()->decode($message->from);
        $this->content['receiver'] = $message->getHeader()->decode($message->to);
        $this->content['senddate'] = $message->date->toDate()->format('d.m.Y');
        $this->content['emailbody'] = $message->hasHTMLBody() ? $message->getHTMLBody() : $message->getTextBody();
        $this->renderAttachments($message);
    }
    
    protected function renderAttachments($message): void {
        $attachments = $message->getAttachments();
        $contentArray = [];
        foreach ($attachments as $attachment) {
            $contentArray[] = $attachment->name;
        }
        $this->content['attachments'] = implode('<br>', $contentArray);
    }
}
