<?php
/**
 * @license GNU General Public License, version 2
 */


if (!defined('DOKU_INC')) die();


/**
 * Class action_plugin_publish_mail
 *
 * @author Michael Große <grosse@cosmocode.de>
 */
class action_plugin_publish_mail extends DokuWiki_Action_Plugin {

    /**
     * @var helper_plugin_publish
     */
    private $hlp;

    function __construct() {
        $this->hlp = plugin_load('helper','publish');
    }

    public function register(Doku_Event_Handler $controller) {

        $controller->register_hook('IO_WIKIPAGE_WRITE', 'AFTER', $this, 'send_change_mail', array());
    }

    /**
     * send an email to inform about a changed page
     *
     * @param $event
     * @param $param
     * @return bool false if the receiver is invalid or there was an error passing the mail to the MTA
     */
    function send_change_mail(&$event, $param) {
        global $ID;
        global $ACT;
        global $INFO;
        global $conf;

        if ($ACT != 'save') {
            return true;
        }

        // IO_WIKIPAGE_WRITE is always called twice when saving a page. This makes sure to only send the mail once.
        if (!$event->data[3]) {
            return true;
        }

        // Does the publish plugin apply to this page?
        if (!$this->hlp->isActive($ID)) {
            return true;
        }

        //are we supposed to send change-mails at all?
        if ($this->getConf('apr_mail_receiver') === '') {
            return true;
        }

        // get mail receiver
        $receiver = $this->getConf('apr_mail_receiver');
        if(!mail_isvalid($receiver)) {
            dbglog(sprintf($this->getLang('mail_invalid'), htmlspecialchars($receiver)));
            return false;
        }

        // get mail sender
        $ReplyTo = $INFO['userinfo']['mail'];

        if ($ReplyTo == $receiver) {
            return true;
        }

        if ($INFO['isadmin'] == '1') {
            return true;
        }

        // get mail subject
        $timestamp = dformat(filemtime(wikiFN($ID)), $conf['dformat']);
        $subject = $this->getLang('apr_mail_subject') . ': ' . $ID . ' - ' . $timestamp;

        $body = $this->create_mail_body('change');

        // Build HTML version
        $rev = filemtime(wikiFN($ID));
        if($this->hlp->hasApprovals($INFO['meta'])) {
            $oldrev = $this->hlp->getLatestApprovedRevision($ID);
        } else {
            $changelog2 = new PageChangelog($ID);
            $oldrev = $changelog2->getRelativeRevision($rev, -1);
        }
        $difflink = $this->hlp->getDifflink($ID, $oldrev, $rev);
        $summary = $INFO['meta']['last_change']['sum'];
        $user = $INFO['userinfo']['name'];
        $oldlink = ($oldrev === false) ? '---' : $this->revlink($ID, $oldrev);
        $newlink = $this->revlink($ID, $rev);

        $changeHtml = $this->_buildChangeHtml($body, $difflink, $summary, $user, $oldlink, $newlink);
        $htmlBody = $this->_buildNiccHtml('Revision', $changeHtml, $conf['title']);

        $mail = new Mailer();
        $mail->to($receiver);
        $mail->subject($subject);
        $mail->setBody($body, null, null, $htmlBody);
        $mail->setHeader("Reply-To", $ReplyTo);
        $returnStatus = $mail->send();
        return $returnStatus;
    }

    /**
     * Create the body of mails to inform about a changed or an approved page
     *
     * @param string $action Must either be "change" or "approve"
     * @return bool|string
     *
     */
    public function create_mail_body($action) {
        global $ID;
        global $conf;
        global $INFO;

        // get mail text
        $rev = filemtime(wikiFN($ID));

        if ($action === 'change') {
            $body = io_readFile($this->localFN('mailchangetext'));

            //If there is no approved revision show the diff to the revision before. Otherwise show the diff to the last approved revision.
            if($this->hlp->hasApprovals($INFO['meta'])) {
                $aprpre = 'Aproved';
                $oldrev = $this->hlp->getLatestApprovedRevision($ID);
                $difflink = $this->hlp->getDifflink($ID, $oldrev, $rev);
            } else {
                $aprpre = 'Previous';
                $changelog = new PageChangelog($ID);
                $oldrev = $changelog->getRelativeRevision($rev, -1);
                $difflink = $this->hlp->getDifflink($ID, $oldrev, $rev);
            }

            $body = str_replace('@DIFF@', $difflink, $body);
            $body = str_replace('@APRPRE@', $aprpre, $body);
            $summary = $INFO['meta']['last_change']['sum'];
            $body = str_replace('@SUMMARY@', $summary, $body);
            if ($oldrev === false ) {
                $oldlink = '---';
            } else {
                $oldlink = $this->revlink($ID, $oldrev);
            }
            $body = str_replace('@OLDPAGE@', $oldlink, $body);
            $newlink = $this->revlink($ID, $rev);
            $body = str_replace('@NEWPAGE@', $newlink, $body);
        } elseif ($action === 'approve') {
            $body = io_readFile($this->localFN('mailapprovetext'));
            $newlink = $this->revlink($ID, $rev);
            $body = str_replace('@URL@', $newlink, $body);

            $changelog = new PageChangelog($ID);
            $revinfo = $changelog->getRevisionInfo($rev);
            /** @var DokuWiki_Auth_Plugin $auth */
            global $auth;
            $userinfo = $auth->getUserData($revinfo['user']);
            $body = str_replace('@FULLNAME@', $userinfo['name'], $body);
        } else {
            return false;
        }

        $body = str_replace('@DOKUWIKIURL@', DOKU_URL, $body);
        $body = str_replace('@TITLE@', $conf['title'], $body);

        return $body;
    }



    /**
     * Send approve-mail to editor of the now approved revision
     *
     * @return bool false if there was an error passing the mail to the MTA
     */
    public function send_approve_mail() {
        global $ID;
        global $REV;

        /** @var DokuWiki_Auth_Plugin $auth */
        global $auth;
        $data = pageinfo();

        // get mail receiver
        if (!$REV) {
            $rev = $data['lastmod'];
        } else {
            $rev=$REV;
        }
        $changelog = new PageChangelog($ID);
        $revinfo = $changelog->getRevisionInfo($rev);
        $userinfo = $auth->getUserData($revinfo['user']);
        $receiver = $userinfo['mail'];

        // get mail sender
        $ReplyTo = $data['userinfo']['mail'];

        if ($ReplyTo == $receiver) {
            return true;
        }

        // get mail subject
        $subject = $this->getLang('apr_mail_app_subject');

        // get mail text
        $body = $this->create_mail_body('approve');

        // Build HTML version
        global $conf;
        $rev2 = $rev;
        $changelog2 = new PageChangelog($ID);
        $revinfo2 = $changelog2->getRevisionInfo($rev2);
        $userinfo2 = $auth->getUserData($revinfo2['user']);
        $fullname = $userinfo2['name'];
        $pageUrl = wl($ID, '', true, '&');

        $approveHtml = $this->_buildApproveHtml($fullname, $ID, $pageUrl);
        $htmlBody = $this->_buildNiccHtml('Aprobado', $approveHtml, $conf['title']);

        $mail = new Mailer();
        $mail->to($receiver);
        $mail->subject($subject);
        $mail->setBody($body, null, null, $htmlBody);
        $mail->setHeader("Reply-To", $ReplyTo);
        $returnStatus = $mail->send();

        return $returnStatus;
    }

    /**
     * create link to the specified revision
     *
     * @param string $id
     * @param string $rev The timestamp of the revision
     * @return string
     */
    function revlink($id, $rev) {

        $options = array(
             'rev'=> $rev,
        );
        $revlink = wl($id, $options, true, '&');

        return $revlink;
    }

    /**
     * Build the NICC-styled HTML wrapper for emails
     *
     * @param string $badge       Badge text (e.g. "Revision", "Aprobado")
     * @param string $bodyContent Inner HTML content
     * @param string $wikiTitle   Wiki title for the header
     * @return string Full HTML email
     */
    private function _buildNiccHtml($badge, $bodyContent, $wikiTitle) {
        $year = date('Y');
        $wikiTitleEsc = htmlspecialchars($wikiTitle);
        $badgeEsc = htmlspecialchars($badge);

        return '<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>
<body style="margin:0; padding:0; background-color:#f0eeea; font-family:Arial,sans-serif;">
<table width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#f0eeea; padding:20px 0;">
<tr><td align="center">
<table width="600" cellpadding="0" cellspacing="0" border="0" style="max-width:600px; background:#ffffff;">
    <tr><td style="height:4px; background:#e94560; font-size:0; line-height:0;">&nbsp;</td></tr>
    <tr><td style="background:#1a1a2e; padding:18px 30px;">
        <table width="100%" cellpadding="0" cellspacing="0" border="0"><tr>
            <td><table cellpadding="0" cellspacing="0" border="0"><tr>
                <td style="width:36px; height:36px; background:#e94560; text-align:center; vertical-align:middle;">
                    <span style="font-family:Georgia,serif; font-size:18px; font-weight:bold; color:#ffffff;">N</span>
                </td>
                <td style="padding-left:12px;">
                    <span style="font-family:Georgia,serif; font-size:17px; font-weight:bold; color:#f8f7f4; letter-spacing:1px;">NICC</span><br>
                    <span style="font-family:Arial,sans-serif; font-size:10px; color:#a0a0b8; letter-spacing:1px; text-transform:uppercase;">' . $wikiTitleEsc . '</span>
                </td>
            </tr></table></td>
            <td align="right" valign="middle">
                <span style="font-family:Arial,sans-serif; font-size:10px; font-weight:bold; color:#f59e0b; letter-spacing:1px; text-transform:uppercase; border:1px solid rgba(245,158,11,0.4); padding:4px 10px;">' . $badgeEsc . '</span>
            </td>
        </tr></table>
    </td></tr>
    <tr><td style="background:#f8f7f4; padding:28px 30px;">
        ' . $bodyContent . '
    </td></tr>
</table>
<!-- SIE Footer -->
<table width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:600px; margin:0 auto;">
    <tr><td style="background:#1a1a2e; padding:20px 30px;">
        <table width="100%" cellpadding="0" cellspacing="0" border="0">
            <tr><td style="padding-bottom:12px; border-bottom:1px solid rgba(255,255,255,0.08);">
                <table width="100%" cellpadding="0" cellspacing="0" border="0"><tr>
                    <td valign="top" style="font-family:Georgia,serif; font-size:14px; font-weight:bold; color:#f8f7f4;">SIE Asesorias<br><span style="font-family:Arial,sans-serif; font-size:10px; font-weight:normal; color:#6a6a82;">Sistemas de Gestion Integrados</span></td>
                    <td valign="top" align="right">
                        <a href="mailto:proyectos@sieasesorias.com" style="font-family:Arial,sans-serif; font-size:11px; color:#a0a0b8; text-decoration:none; display:block; margin-bottom:2px;">proyectos@sieasesorias.com</a>
                        <a href="https://sieasesorias.com" style="font-family:Arial,sans-serif; font-size:11px; color:#a0a0b8; text-decoration:none; display:block;">sieasesorias.com</a>
                    </td>
                </tr></table>
            </td></tr>
            <tr><td style="padding-top:12px; text-align:center; font-family:Arial,sans-serif; font-size:10px; color:#4a4a62; line-height:1.6;">&copy; ' . $year . ' SIE Asesorias &middot; Todos los derechos reservados<br><span style="color:#e94560;">NICC</span> &mdash; Plataforma de Gestion Empresarial</td></tr>
        </table>
    </td></tr>
    <tr><td style="height:3px; background:#e94560; font-size:0; line-height:0;">&nbsp;</td></tr>
</table>
</td></tr></table>
</body></html>';
    }

    /**
     * Build HTML content for change notification emails
     *
     * @param string $body     Plain text body (for reference)
     * @param string $difflink URL to the diff view
     * @param string $summary  Edit summary
     * @param string $user     Username who made the change
     * @param string $oldlink  URL to old revision
     * @param string $newlink  URL to new revision
     * @return string HTML body content
     */
    private function _buildChangeHtml($body, $difflink, $summary, $user, $oldlink, $newlink) {
        global $ID, $conf;

        $pageEsc = htmlspecialchars($ID);
        $userEsc = htmlspecialchars($user);
        $summaryEsc = htmlspecialchars($summary ?: '(sin resumen)');
        $fecha = dformat(time(), $conf['dformat']);
        $diffEsc = htmlspecialchars($difflink);
        $oldEsc = htmlspecialchars($oldlink);
        $newEsc = htmlspecialchars($newlink);

        return '
        <!-- Info band -->
        <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:20px;">
            <tr>
                <td style="border-left:4px solid #f59e0b; background:#fffbeb; padding:14px 18px;">
                    <span style="font-family:Arial,sans-serif; font-size:14px; color:#92400e; font-weight:bold;">Hay una nueva sugerencia que requiere su revision</span>
                </td>
            </tr>
        </table>

        <!-- Info table -->
        <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:20px; font-family:Arial,sans-serif; font-size:13px; color:#333;">
            <tr>
                <td style="padding:8px 12px; background:#f0eeea; font-weight:bold; width:100px; border-bottom:1px solid #e0ddd8;">Pagina</td>
                <td style="padding:8px 12px; background:#f8f7f4; border-bottom:1px solid #e0ddd8;">' . $pageEsc . '</td>
            </tr>
            <tr>
                <td style="padding:8px 12px; background:#f0eeea; font-weight:bold; border-bottom:1px solid #e0ddd8;">Usuario</td>
                <td style="padding:8px 12px; background:#f8f7f4; border-bottom:1px solid #e0ddd8;">' . $userEsc . '</td>
            </tr>
            <tr>
                <td style="padding:8px 12px; background:#f0eeea; font-weight:bold; border-bottom:1px solid #e0ddd8;">Resumen</td>
                <td style="padding:8px 12px; background:#f8f7f4; border-bottom:1px solid #e0ddd8;">' . $summaryEsc . '</td>
            </tr>
            <tr>
                <td style="padding:8px 12px; background:#f0eeea; font-weight:bold;">Fecha</td>
                <td style="padding:8px 12px; background:#f8f7f4;">' . htmlspecialchars($fecha) . '</td>
            </tr>
        </table>

        <!-- Revision links -->
        <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:20px; font-family:Arial,sans-serif; font-size:12px;">
            <tr>
                <td style="padding:6px 0;">
                    <span style="color:#666;">Revision anterior:</span>
                    <a href="' . $oldEsc . '" style="color:#e94560; text-decoration:none;">' . $oldEsc . '</a>
                </td>
            </tr>
            <tr>
                <td style="padding:6px 0;">
                    <span style="color:#666;">Revision nueva:</span>
                    <a href="' . $newEsc . '" style="color:#e94560; text-decoration:none;">' . $newEsc . '</a>
                </td>
            </tr>
        </table>

        <!-- CTA Button -->
        <table width="100%" cellpadding="0" cellspacing="0" border="0">
            <tr>
                <td align="center" style="padding:10px 0 5px;">
                    <a href="' . $diffEsc . '" style="display:inline-block; background:#e94560; color:#ffffff; font-family:Arial,sans-serif; font-size:14px; font-weight:bold; text-decoration:none; padding:12px 32px; letter-spacing:0.5px;">Revisar Cambios</a>
                </td>
            </tr>
        </table>';
    }

    /**
     * Build HTML content for approval notification emails
     *
     * @param string $fullname Full name of the editor
     * @param string $title    Page ID/title
     * @param string $url      URL to the approved page
     * @return string HTML body content
     */
    private function _buildApproveHtml($fullname, $title, $url) {
        $fullnameEsc = htmlspecialchars($fullname);
        $titleEsc = htmlspecialchars($title);
        $urlEsc = htmlspecialchars($url);

        return '
        <!-- Info band -->
        <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:20px;">
            <tr>
                <td style="border-left:4px solid #27ae60; background:#eafaf1; padding:14px 18px;">
                    <span style="font-family:Arial,sans-serif; font-size:14px; color:#1e7e34; font-weight:bold;">Su sugerencia ha sido aprobada</span>
                </td>
            </tr>
        </table>

        <!-- Message -->
        <table width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:20px;">
            <tr>
                <td style="font-family:Arial,sans-serif; font-size:14px; color:#333; line-height:1.7; padding:0 0 10px;">
                    Hola <strong>' . $fullnameEsc . '</strong>,<br><br>
                    Su revision de la pagina <strong>' . $titleEsc . '</strong> ha sido revisada y aprobada por un administrador. Los cambios ya se encuentran publicados.
                </td>
            </tr>
        </table>

        <!-- CTA Button -->
        <table width="100%" cellpadding="0" cellspacing="0" border="0">
            <tr>
                <td align="center" style="padding:10px 0 5px;">
                    <a href="' . $urlEsc . '" style="display:inline-block; background:#27ae60; color:#ffffff; font-family:Arial,sans-serif; font-size:14px; font-weight:bold; text-decoration:none; padding:12px 32px; letter-spacing:0.5px;">Ver Pagina</a>
                </td>
            </tr>
        </table>';
    }

}
