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

class Emailinbox extends Renderer {
    private string $folder = 'INBOX';
    
    public function __construct(?string $templateName = null) {
        parent::__construct();
        $folder = utf8_encode(urldecode(filter_input(INPUT_GET, 'folder'))) ?? 'INBOX';
        if (!$this->connectToImap($folder)) {
            $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)  {
            return [];
        }
        $headers = $this->mbox->getMailsInfo($mailsIds);
        foreach ($headers as $header) {
            try {
                $date = \DateTime::createFromFormat('D, d M Y H:i:s O', str_replace([' (CET)', ' (CEST)', ' (UTC)'], '' , $header->date));
                // if (!$date) {
                //     var_dump($header->date);
                // }
                $date = $date ? $date->setTimezone(new DateTimeZone('Europe/Berlin')) : new DateTime();
                $cleanedHeaders[trim($header->msgno)] = [
                    'title' => $header->subject,
                    'date' => $date,
                    'from' => $header->from,
                    'unread' => !$header->seen,
                ];
            } catch (\exception $err) {
            }
        }
        return $cleanedHeaders;
    }

    protected function generateContent(): void {
        $this->generateHeaders();
        $this->generateFolders();
    }
    
    protected function generateHeaders(): 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'];
    }
    
    protected function generateFolders(): void {
        $this->connectToImap();
        $folders = $this->mbox->getMailboxes("*");
        $folderItems = [];
        foreach ($folders as $folder) {
            $folderItems[] = '<li><a href="/emailinbox?folder=' . urlencode($folder['shortpath']) . '">' . utf8_encode($folder['shortpath']) . '</a></li>';
        }
        $this->content['folders'] = implode('', $folderItems);
    }
}
