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

class Savemail extends Mailhandling {
    // protected $mbox = null;
    protected $uid = 0;
    
    public function __construct(?string $templateName = null) {
        parent::__construct();
        if (!$this->connectToImap()) {
            $this->templateName = 'imaperror';
            return;
        }
        $this->uid = $this->getUriParams()['uid'];
        $this->type = $this->getUriParams()['type'];
        $this->content['uid'] = $this->uid;
        if ($this->type === 'content') {
            $this->saveEmailBody();
        }
    }
    
    protected function saveEmailBody(): void {
        $messageStructure = imap_fetchstructure($this->mbox, $this->uid);
        $this->fetchEmailHeader($this->content);
        $this->fetchEmailBody($messageStructure, $this->content);
        $content = $this->generateBodyContent();
        $newFileName = $this->generateRandomString(64);
        $salt = $this->generateRandomString();
        $breaks = array("<br />","<br>","<br/>");  
        $rerenderedContent = str_ireplace($breaks, "\r\n", $content);  
        $this->saveFileLocal($newFileName, $rerenderedContent, $salt);
        $this->generateDocumentTitle();
        $query = sprintf('INSERT INTO ffajs.document
                (title, original_filename, local_filename, salt)
                VALUES("%s", "%s", "%s", "%s")', $this->content['saved-title'],
                $this->content['saved-title'],
                $newFileName, $salt);
        mysqli_query($this->dbConnection, $query);
    }
    
    protected function generateBodyContent(): string {
        return 'Von: ' . $this->content['sender'] . "\n"
            . 'An: ' . $this->content['receiver'] . "\n"
            . 'Datum: ' . $this->content['senddate'] . "\n"
            . 'Betreff: ' . $this->content['subject'] . "\n\n"
            . $this->content['emailbody'];
    }
    
    protected function generateDocumentTitle(): void {
        $originalSubject = $this->content['subject'];
        $count = 0;
        $found = false;
        do {
            $query = sprintf('SELECT id
                FROM document d 
                WHERE lower(trim(d.title)) = lower(trim("%s"))', $originalSubject);
            $dbResult = mysqli_query($this->dbConnection, $query);
            if (mysqli_num_rows($dbResult) > 0) {
                $found = true;
                $counter = 0;
                if (preg_match('/(.*):(\d+)$/', trim($originalSubject))) {
                    $counter = preg_split('/(.*):(\d+)$/', trim($originalSubject));
                    $originalSubject = preg_replace('/(.*):(\d+)$/', '{1}', $originalSubject);
                }
                $originalSubject .= ':' . (++$counter);
            }
        } while ($found === true && ($count++ < 10));
        $this->content['saved-title'] = $originalSubject;
    }
}
