<?php
/**
 * Controller for mail
 *
 * This file is part of Zoph.
 *
 * Zoph is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * Zoph is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with Zoph; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 * @package Zoph
 * @author Jeroen Roos
 */

namespace mail;

use album;
use conf\conf;
use generic\controller as genericController;
use file;
use photo;
use template\block;
use web\request;
use web\url;
use user;

/**
 * Controller for mail
 */
class controller extends genericController {
    protected static $viewCompose       = view\compose::class;
    protected static $viewNotify        = view\notify::class;
    protected static $viewNotifyUser    = view\notifyuser::class;
    protected static $viewNotFound      = view\notfound::class;
    protected static $viewResult        = view\result::class;

    /** @var array Actions that can be used in this controller */
    protected   $actions    = array(
        "compose", "mail", "mailnotify", "notfound", "notify", "notifyuser"
    );

    /**
     * Create a controller using a web request
     * @param request request
     */
    public function __construct(request $request) {
        parent::__construct($request);

        if (in_array($this->request["_action"], array("mail", "compose"))) {
            $this->object = new photo($request["photo_id"]);
            if ($this->object->lookup()) {
                $this->doAction();
            } else {
                // @todo
                $this->view = new static::$viewNotFound($this->request);

            }
        } else {
            $this->doAction();
        }
    }

    /**
     * Do action 'mailnotify'
     */
    protected function actionMailnotify() {
        $this->view = new static::$viewResult($this->request);
        try {
            $mail = new mime();

            $message = $this->request["message"];
            $mail->setTXTBody(e($message));


            $result = $this->sendMail($mail);

            if ($result && $this->request["setlastmodified"]) {
                $user = $this->getUser();
                if ($user instanceof user) {
                    $user->set("lastnotify", "now()");
                    $user->update();
                }
            }
        } catch (exception $e) {
            $this->view->setMessage(error: $e->getMessage());
        }
    }

    /**
     * Do action 'notify'
     * This action notifies the user of new albums he or she has gained access to.
     */
    protected function actionNotify() {
        $this->view = new static::$viewNotify($this->request);
        $user = $this->getUser();
        $this->view->setUser($user);
        if ($this->request["shownewalbums"]) {
            $this->view->setAlbums(album::getNewer($user, $user->getLastNotify()));
        }
    }

    /**
     * Do action 'notifyuser'
     * This action notifies the user of a new account that has been created for him or her.
     */
    protected function actionNotifyUser() {
        $this->view = new static::$viewNotifyUser($this->request);
        $this->view->setUser($this->getUser());
    }

    /**
     * Do action 'display'
     */
    protected function actionDisplay() {
        $this->view = new static::$viewCompose($this->request, $this->object);
    }

    /**
     * Do action 'compose'
     */
    protected function actionCompose() {
        $this->view = new static::$viewCompose($this->request, $this->object);
    }

    /**
     * Do action 'mail'
     */
    protected function actionMail() {
        $this->view = new static::$viewResult($this->request);

        try {
            $mail = new mime();

            if ($this->request["_size"] == "full") {
                $filename = $this->object->get("name");
                $dir = conf::get("path.images") . "/" . $this->object->get("path") . "/";
            } else {
                $filename = MID_PREFIX . "_" . $this->object->get("name");
                $dir = conf::get("path.images") . "/" . $this->object->get("path") . "/" .  MID_PREFIX . "/";
            }
            $file=new file($dir . DIRECTORY_SEPARATOR . $filename);
            if ($this->request["html"]) {
                if ($this->request["includeurl"]) {
                    $url = url::get() . "photo.php?photo_id=" . $this->object->getId();
                    $link_msg = sprintf(translate("See this photo in %s"), conf::get("interface.title"));
                } else {
                    $url = null;
                    $link_msg = null;
                }
               $html = new block("mail", array(
                    "filename"  => $filename,
                    "msg"       => str_replace("\n", "<br>\n", $this->request["message"]),
                    "url"       => $url,
                    "link_msg"  => $link_msg
                ));

                $mail->addHTMLImageFromFile($dir . "/" . $filename, $file->getMime());
                $mail->setHTMLBody($html);
                $mail->setTXTBody($this->request["message"]);
            } else {
                if ($this->request["includeurl"]) {
                    $message = $this->request["message"];
                    $message .= "\n";
                    $message .= sprintf(translate("See this photo in %s"),
                        conf::get("interface.title"));
                    $message .= ": " . url::get() . "/photo.php?photo_id=" . $this->object->getId();
                }
                $mail->setTXTBody($message);
                $mail->addAttachmentFromFile($dir . "/" . $filename, $file->getMime());
            }

            $this->sendMail($mail);
        } catch (exception $e) {
            $this->view->setMessage(error: $e->getMessage());
        }
    }

    private function sendMail(mime $mail) {
        $hdrs = array (
            "X-Mailer" => "Html Mime Mail Class",
            "X-Zoph-Version" => VERSION
        );

        $mail->setFrom($this->request["from_name"] . " <" . $this->request["from_email"] . ">");

        if (strlen(conf::get("feature.mail.bcc")) > 0) {
            $mail->addBcc(conf::get("feature.mail.bcc"));
        }

        $body = $mail->get();

        $headers="";
        foreach ($mail->headers($hdrs) as $header => $content) {
            $headers .= $header . ": " . $content . "\n";
        }
        if (mail($this->request["to_email"],$this->request["subject"], $body,$headers)) {
            $this->view->setMessage(success: translate("Your mail has been sent."));
            return true;
        } else {
            $this->view->setMessage(error: translate("Could not send mail."));
            return false;
        }
    }

    private function getUser() {
        $user_id = $this->request["user_id"];
        if ($user_id > 0) {
            $user=new user($user_id);
            $user->lookup();
            $user->lookupPerson();
            return $user;
        }
    }
}
