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

class Emailinbox extends Renderer {
    
    public function __construct(?string $templateName = null) {
        parent::__construct();
        if (!$this->connectToImap()) {
            $this->templateName = 'imaperror';
        }
    }

    protected function readEmailHeaders(): array {
        $cleanedHeaders = [];
        try {
            $mailsIds = $this->mbox->searchMailbox('ALL');
        } catch(PhpImap\Exceptions\ConnectionException $ex) {
            echo "IMAP connection failed: " . implode(",", $ex->getErrors('all'));
            die();
        }

        if(!$mailsIds) {
            die('Mailbox is empty');
        }
        $headers = $this->mbox->getMailsInfo($mailsIds);
        foreach ($headers as $header) {
            try {
                $cleanedHeaders[trim($header->msgno)] = [
                    'title' => $header->subject,
                    'date' => \DateTime::createFromFormat('D, d M Y H:i:s O', str_replace(' (CET)', '', $header->date))->setTimezone(new DateTimeZone('Europe/Berlin')),
                    'from' => $header->from,
                    'unread' => !$header->seen,
                ];
            } catch (\exception $err) {
            }
        }
        return $cleanedHeaders;
    }
       
    protected function getDateObjectFromString(string $dateString) {
        $date = DateTime::createFromFormat(DateTimeInterface::RFC1123, $dateString);
        if (!$date) {
            $date = DateTime::createFromFormat(DateTimeInterface::RFC1123, substr($dateString, 0, -6));
        }
        if (!$date) {
            $date = DateTime::createFromFormat('d M Y H:i:s O', $dateString);
        }
        if (!$date) {
            echo $dateString;
        }
        return $date;
    }

    protected function generateContent(): void {
        $headers = $this->readEmailHeaders();
        uasort($headers, ['Emailinbox', 'compareDateTimes']);
        array_walk($headers, function(&$item, $key) {
            $newItem = '<tr>';
            $newItem .= '<td style="white-space:nowrap">' . ($item['date'] === false ? '' : $item['date']->format('d.m.Y H:i:s')) . '</td>';
            $newItem .= '<td><a href="mail?uid=' . $key . '">' . ($item['unread'] === 'U' ? '<b>' : '') . $item['title'] . ($item['unread'] === 'u' ? '</b>' : '') . '</td>';
            $newItem .= '<td>' . $item['from'] . '</td>';
            $newItem .= '</tr>';
            $item = $newItem;
        });
        $this->content['mails'] = implode('', $headers);
    }
    
    protected function compareDateTimes($item1, $item2): int {
        return $item2['date'] <=> $item1['date'];
    }
}
