<?php

/**
 * vpanel-stack
 * https://git.stack-source.com/msb/vpanel-stack
 * Copyright (c) 2022 Matthew Saunders Brown <matthewsaundersbrown@gmail.com>
 * GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
 */

namespace Panel\Vmail;

class AutorespondersAdd extends \Panel\Vmail {

  function beforeRoute($f3) {

    parent::beforeRoute($f3);

    // verify email address exists
    // verify autoresponder does *not* exist

  }

  static function get($f3) {

    /* initialize autoresponder_array */
    $autoresponder_array = array('subject' => '', 'body' => '', 'mode' => 'Vacation', 'status' => '1');
    $f3->set('autoresponder_array', $autoresponder_array);

    echo \Template::instance()->render('vmail/autoresponders-add.html');

  }

  function post($f3) {

    extract($_POST);

    /* check for validation errors */
    if ($f3->exists('SESSION.messages')) {
      $messages = $f3->get('SESSION.messages');
      $messages[] = "Please make changes and re-submit the form to try again.";
      $f3->set('SESSION.messages', $messages);
      $f3->set('autoresponder_array', $_POST);
      $f3->call('\Panel\Vmail\AutorespondersAdd::get', $f3);
    } else {
      $mbox = $f3->get('PARAMS.mbox');
      $domain = $f3->get('PARAMS.domain');
      $subject = addslashes($subject);
      $body = addslashes($body);
      $body = str_replace('\"', '\\\\\"', $body);
      $body = str_replace("\r\n", '\n', $body);
      $body = str_replace("\r", '\n', $body);
      $body = str_replace("\n", '\n', $body);
      exec("/usr/local/bin/vmail-autoresponders-add.sh -e $mbox@$domain -u \"$subject\" -b \"$body\" -o \"$mode\" -s \"$status\"", $output, $result_code);
      if ($result_code == 0) {
        $messages[] = "Success: Autoresponder for email account $mbox@$domain added.";
        $f3->set('SESSION.messages', $messages);
        $mapping = $f3->get('NAV.mapping');
        if ($mapping == 'vmail') {
          $f3->reroute("/Accounts/$mbox/Autoresponder");
        } else {
          $f3->reroute("/Email/$domain/Accounts/$mbox/Autoresponder");
        }
      } else {
        $messages[] = "Error.";
        $f3->set('SESSION.messages', $messages);
        $f3->call('\Panel\Vmail\AutorespondersAdd::get', $f3);
      }
    }
  }

}