<?php
// AJAX handling

// Includes
require('includes/config.inc.php');
require('includes/database.inc.php');
require('includes/functions.inc.php');
require('includes/document.inc.php');
require('includes/label.inc.php');
require('includes/mailbox.inc.php');
require('includes/mailboxfolder.inc.php');
require('includes/documenthandler.inc.php');
require('includes/call.inc.php');
require('includes/reminder.inc.php');
require('includes/mail.inc.php');

$db = new Database($CONFIG['dbHost'], $CONFIG['dbUser'], $CONFIG['dbPassword'], $CONFIG['dbDatabase']);

switch($_REQUEST['action']) {
    case 'updateMailaccounts':
        switch($_POST['name']) {
            case 'hostname':
                header("Status: 200 OK");
                $db->updateQuery("UPDATE `mailboxes` SET `server`='" . $_POST['value'] . "' WHERE id=" . $_POST['pk'] . ";");
                break;
            case 'port':
                header("Status: 200 OK");
                $db->updateQuery("UPDATE `mailboxes` SET `port`='" . $_POST['value'] . "' WHERE id=" . $_POST['pk'] . ";");
                break;
            case 'protocol':
                header("Status: 200 OK");
                $db->updateQuery("UPDATE `mailboxes` SET `protocol`='" . $_POST['value'] . "' WHERE id=" . $_POST['pk'] . ";");
                break;
            case 'use-ssl':
                header("Status: 200 OK");
                $db->updateQuery("UPDATE `mailboxes` SET `use_ssl`='" . $_POST['value'] . "' WHERE id=" . $_POST['pk'] . ";");
                break;
            case 'no-valid-cert':
                header("Status: 200 OK");
                $db->updateQuery("UPDATE `mailboxes` SET `valid_ssl`='" . $_POST['value'] . "' WHERE id=" . $_POST['pk'] . ";");
                break;
            case 'username':
                header("Status: 200 OK");
                $db->updateQuery("UPDATE `mailboxes` SET `username`='" . $_POST['value'] . "' WHERE id=" . $_POST['pk'] . ";");
                break;
            case 'password':
                header("Status: 200 OK");
                $db->updateQuery("UPDATE `mailboxes` SET `password`='" . $_POST['value'] . "' WHERE id=" . $_POST['pk'] . ";");
                break;
            default:
                header("Status: 400 Wrong Field");
                echo 'error';
                break;

        }
        break;
    case 'updateMailfolder':
        switch($_POST['name']) {
            case 'mailaccount':
                header("Status: 200 OK");
                $db->updateQuery("UPDATE `mailbox-folders` SET `mailbox_id`='" . $_POST['value'] . "' WHERE id=" . $_POST['pk'] . ";");
                break;
            case 'mailfolder':
                header("Status: 200 OK");
                $db->updateQuery("UPDATE `mailbox-folders` SET `folder_name`='" . $_POST['value'] . "' WHERE id=" . $_POST['pk'] . ";");
                break;
            default:
                header("Status: 400 Wrong Field");
                echo 'error';
                break;
        }
        break;
    case 'addDefaultMailaccount':
        header("Status: 200 OK");
        $db->insertQuery("INSERT INTO `mailboxes` (`user_id`) VALUES (" . $_POST['user-id'] . ");");
        break;
    case 'addDefaultMailfolder':
        header("Status: 200 OK");
        $db->insertQuery("INSERT INTO `mailbox-folders` (`label_id`) VALUES (" . $_POST['label-id'] . ");");
        break;
    case 'removeMailaccount':
        header("Status: 200 OK");
        $db->removeQuery("DELETE FROM `mailboxes` WHERE `id` = " . $_POST['id'] . ";");
        break;
    case 'removeMailboxFolder':
        header("Status: 200 OK");
        $db->removeQuery("DELETE FROM `mailbox-folders` WHERE `id` = " . $_POST['id'] . ";");
        break;
    case 'manageMailboxFolder':
        header("Status: 200 OK");

        $allMailBoxes = Mailbox::getAllMailboxes(false);

        $editBox = array(
            "options"   => array(
                array(
                    "type"      => "select",
                    "name"      => "account",
                    "value"     => Mailbox::getMailboxNameFromMailaccountId($_GET['mbId']),
                    "values"    => array()
                ),
                array(
                    "type"  => "text",
                    "name"  => "folder",
                    "value" => MailboxFolder::getMailboxFolderNameFromId($_GET['mfId'])
                )
            ),
            "title"     => "Mailkonto bearbeiten",
            "mailboxFolderID"   => $_GET['mfId']
        );

        foreach($allMailBoxes as $mailBox) {
            $editBox['options'][0]['values'][] = $mailBox->getUsername();
        }

        echo json_encode($editBox);

        break;
    case 'getMailAccountsByUid':
        header("Status: 200 OK");
        $mailboxes = Mailbox::getMailboxesByUserId($_REQUEST['uId']);
        $mbArray = array();
        foreach($mailboxes as $mailbox) {
            $mbArray[$mailbox->getId()] = $mailbox->getUsername();
        }
        echo json_encode($mbArray);
        break;
    case 'getNewDocumentBox':
        header("Status: 200 OK");

        $editBox = array(
            "options"   => array(
                array(
                    "type"      => "select",
                    "name"      => "vorlage",
                    "value"     => Document::getDefaultDraft()->filename,
                    "values"    => Document::getAllDrafts()
                ),
                array(
                    "type"  => "text",
                    "name"  => "filename",
                    "value" => str_replace(".docx", "", Document::getDefaultDraft()->filename) . "_" . date("d_m_Y") . ".docx"
                )
            ),
            "title" => "Neues Dokument"
        );

        echo json_encode($editBox);
        break;
    case 'getDraftVars':
        header("Status: 200 OK");
        $documentHandle = new \PhpOffice\PhpWord\TemplateProcessor('drafts/' . $_REQUEST['draft']);
        $templateVars = $documentHandle->getVariables();
        echo json_encode(array_values($templateVars));
        break;
    case 'getMailboxStatus':
        header("Status: 200 OK");
        $mailbox = Mailbox::getMailboxById($_REQUEST['mailboxId'], true);
        $mailboxStatus = array(
            "connected" => $mailbox->getConnected()
        );
        echo json_encode($mailboxStatus);
        break;
    case 'saveNewDocument':
        header("Status: 200 OK");

        $newDocument = new DocumentHandler(Label::getLabelById($_REQUEST['labelId'])->getPath() . '/' . $_REQUEST['filename'], $_REQUEST['draft']);

        foreach($_REQUEST['draftVars'] as $key => $draftVar) {
            $newDocument->setVal($key, htmlspecialchars($draftVar));
        }

        $newDocument->saveFile();

        echo json_encode($_REQUEST);

        break;
    case 'getNewLabelBox':
        header("Status: 200 OK");
        $editBox = array(
            "options"   => array(
                array(
                    "type"  => "text",
                    "name"  => "name",
                    "value" => ""

                ),
                array(
                    "type"  => "text",
                    "name"  => "path",
                    "value" => ""
                )
            ),
            "title"     => "Neues Label"
        );

        echo json_encode($editBox);
        break;
    case 'saveNewLabel':
        header("Status: 200 OK");
        Label::addLabel($_REQUEST['name'], $_REQUEST['path']);

        $return = array(
            "status"   => "OK"
        );

        echo json_encode($return);
        break;
    case 'removeLabel':
        header("Status: 200 OK");
        Label::removeLabel($_REQUEST['labelId']);

        $return = array(
            "status"    => "OK"
        );

        echo json_encode($return);
        break;
    case 'saveMailFolder':
        header("Status: 200 OK");
        MailboxFolder::updateMailboxFolder($_REQUEST['mailboxFolderID'], $_REQUEST['folder'], Mailbox::getMailboxByUsername($_REQUEST['account'])->getId(), $_REQUEST['labelID']);

        $return = array(
            "status"    => "OK"
        );

        echo json_encode($return);
        break;
    case 'saveNewMailFolder':
        header("Status: 200 OK");
        MailboxFolder::addMailboxFolder($_REQUEST['folder'], Mailbox::getMailboxByUsername($_REQUEST['account'])->getId(), $_REQUEST['labelID']);

        $return = array(
            "status"    => "OK"
        );

        echo json_encode($return);
        break;
    case 'getNewCallBox':
        header("Status: 200 OK");

        $allLabels = Label::getAllLabels();

        $editBox = array(
            "options"   => array(
                array(
                    "type"  => "datetime",
                    "name"  => "call-date",
                    "value" => ""
                ),
                array(
                    "type"  => "text",
                    "name"  => "caller-telnr",
                    "value"  => ""
                ),
                array(
                    "type"      => "select",
                    "name"      => "label-id",
                    "value"     => Label::getLabelById($_REQUEST['labelID'])->getName(),
                    "values"    => array()
                ),
                array(
                    "type"  => "textarea",
                    "name"  => "call-notes",
                    "value" => ""
                ),
                array(
                    "type"  => "checkbox",
                    "name"  => "call-set-reminder",
                    "value" => ""
                )
            ),
            "title" => "Neuer Anruf"
        );

        foreach($allLabels as $label) {
            $editBox['options'][2]['values'][] = $label->getName();
        }

        echo json_encode($editBox);
        break;
    case 'saveNewCall':
        header("Status: 200 OK");
        Call::addCall($_REQUEST['userID'], $_REQUEST['callDate'], $_REQUEST['callerTelNr'], Label::getLabelByName($_REQUEST['labelID'])->getId(), $_REQUEST['callNotes']);

        $return = array(
            "status"    => "OK"
        );
        echo json_encode($return);
        break;
    case 'getEvents':
        header("Status: 200 OK");

        $upcomingReminders = getObjectsAsArray(Reminder::getUpcomingRemindersByUserID($_REQUEST['userID']), array("id", "userID", "reminderDate", "remindedYet"));

        $return = array(
            "type"      => $upcomingReminders == "" ? "ping" : "reminder",
            "reminders" => $upcomingReminders
        );

        echo json_encode($return);

        break;
    case 'setReminderReminded':
        header("Status: 200 OK");
        $reminder = Reminder::getReminderByID($_REQUEST['reminderID']);
        $reminder->setRemindedYet(1);
        $reminder->save();

        $return = array(
            "status"    => "OK"
        );

        echo json_encode($return);
        break;
    case 'setReminderSnooze':
        header("Status: 200 OK");
        $reminder = Reminder::getReminderByID($_REQUEST['reminderID']);
        $reminder->setReminderDate(date("Y-m-d H:i:s", strtotime("+30 minutes")));
        $reminder->save();

        $return = array(
            "status"    => "OK"
        );

        echo json_encode($return);
        break;
    case 'scanDocuments':
        header("Status: 200 OK");

        $return = scanDocuments($CONFIG['documentPath']);
        $return['status'] = "OK";
        echo json_encode($return);
        break;
    case 'getMailContent':
        header("Status: 200 OK");

        $mail = Mail::getMailByMailID($_REQUEST['mailID']);
        $mailboxFolder = Mailboxfolder::getMailboxfolderByID($mail->getMailboxFolderID());
        $mailbox = Mailbox::getMailboxById($mailboxFolder->getMailboxId(), true);

        $mailbox->changeFolder($mailboxFolder->getFolderName());
        $bodyLines =  explode(PHP_EOL, imap_fetchbody($mailbox->getMailbox(), $mail->getMailUID(), 1));
        $body = "%0D%0A"; // newline on top

        foreach($bodyLines as $line) {
            $body .= ">" . $line . '%0D%0A';
        }

        $return = array(
            "to"        => $mail->getMailSender(),
            "subject"   => $mail->getSubject(),
            "body"      => $body
        );

        echo json_encode($return);
    case 'debugTest': // for testing single methods etc.

        break;
    default:
        header("Status: 400 No Action Defined");
        echo 'error';
        break;
}

//pa($_POST); // Debug

?>
