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

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

    protected function readEmailHeaders(): array {
        $cleanedHeaders = [];
        $folder = $this->mbox->getFolderByName($this->folder);
        $messages = $folder->messages()->all()->get();
        foreach ($messages as $message) {
            $header = $message->getHeader();
            try {
                $date = $header->getDate()->toDate();
                $flags = $message->getFlags();
                $cleanedHeaders[$message->getUid()] = [
                    'title' => $message->subject,
                    'date' => $date,
                    'unread' => !isset($flags['seen']) || $flags['seen'] != 'Seen',
                    'from' => $header->decode($header->from),
                ];
            } 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?folder=' . urlencode($this->folder) . '&uid=' . $key . '">' . ($item['unread'] ? '<b>' : '') . $item['title'] . ($item['unread'] ? '</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->getFolders();
        $folderItems = [];
        foreach ($folders as $folder) {
            $item = '<li><a href="/emailinbox?folder=' . urlencode($folder->name) . '"' . 
                ($folder->name === $this->folder ? ' class="active-folder"' : '') . '>' .
                $folder->full_name . '</a></li>';
            $folderItems[] = $item;
        }
        $this->content['folders'] = implode('', $folderItems);
    }
}
