<?php /*

 Composr
 Copyright (c) ocProducts, 2004-2016

 See text/EN/licence.txt for full licencing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
 * @license    http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright  ocProducts Ltd
 * @package    welcome_emails
 */

/**
 * Hook class.
 */
class Hook_preview_cns_welcome_email
{
    /**
     * Find whether this preview hook applies.
     *
     * @return array A pair: The preview, the updated post Comcode
     */
    public function applies()
    {
        $member_id = get_param_integer('id', get_member());

        $applies = (get_page_name() == 'admin_cns_welcome_emails');

        if ($applies) {
            $mail = $this->get_mail_row();

            require_code('cns_welcome_emails');
            list($subject, $message, $is_html, $name) = cns_prepare_welcome_email($mail);
            if ($is_html) {
                $applies = false;

                // Send e-mail instead, as we cannot display raw HTML in the preview...

                require_code('mail');
                $to = $GLOBALS['FORUM_DRIVER']->get_member_email_address(get_member());
                if ($to == '') {
                    $to = get_option('staff_address');
                }
                mail_wrap($subject, $message, array($to), $name, '', '', 3, null, false, get_member(), true);
            }
        }

        return array($applies, null);
    }

    /**
     * Run function for preview hooks.
     *
     * @return array A pair: The preview, the updated post Comcode
     */
    public function run()
    {
        $mail = $this->get_mail_row();

        require_code('cns_welcome_emails');
        list($subject, $message, $is_html, $name) = cns_prepare_welcome_email($mail);

        $preview = comcode_to_tempcode($message);

        return array($preview, null);
    }

    /**
     * Get a simulated row for the welcome e-mail being previewed.
     *
     * @return array Row
     */
    protected function get_mail_row()
    {
        $name = post_param_string('name');
        $subject = post_param_string('subject');
        $text = post_param_string('text');
        $send_time = post_param_integer('send_time');
        $newsletter = post_param_integer('newsletter', null);
        $usergroup = post_param_integer('usergroup', null);
        $usergroup_type = post_param_string('usergroup_type', '');

        return array(
            'w_name' => $name,
            'w_subject' => $subject,
            'w_text' => $text,
            'w_send_time' => $send_time,
            'w_newsletter' => $newsletter,
            'w_usergroup' => $usergroup,
            'w_usergroup_type' => $usergroup_type,
        );
    }
}
