<?PHP
#
#   FILE:  EditMessageTemplate.php (Mailer plugin)
#
#   Copyright 2012 Edward Almasy and Internet Scout
#   http://scout.wisc.edu
#

# check that user should be on this page
CheckAuthorization(PRIV_COLLECTIONADMIN, PRIV_SYSADMIN);

# load up current templates
$Plugin = $GLOBALS["G_PluginManager"]->GetPluginForCurrentPage();
$G_Templates = $Plugin->ConfigSetting("Templates");

# take action based on which button was pushed or which action was requested
$Action = isset($_POST["Submit"]) ? $_POST["Submit"]
        : (isset($_GET["AC"]) ? $_GET["AC"] : NULL);
$TemplateId = isset($_POST["F_Id"]) ? $_POST["F_Id"]
        : (isset($_GET["ID"]) ? $_GET["ID"] : NULL);
$G_TestSeed = isset($_POST["F_TestSeed"]) ? $_POST["F_TestSeed"]
        : (isset($_GET["TS"]) ? $_GET["TS"] : floor(time()/(60*60*24)));
$G_TestIds = isset($_POST["F_TestIds"]) ? $_POST["F_TestIds"]
        : (isset($_GET["TI"]) ? $_GET["TI"]
                : ($Plugin->ConfigSetting("TestResourceIds")
                        ? $Plugin->ConfigSetting("TestResourceIds") : ""));
$Plugin->ConfigSetting("TestResourceIds", $G_TestIds);
switch ($Action)
{
    case "Add Template":
        # set up blank template
        $TemplateId = "NEW";
        $G_Templates[$TemplateId]["Name"] = "";
        $G_Templates[$TemplateId]["From"] = "X-PORTALNAME-X <X-ADMINEMAIL-X>";
        $G_Templates[$TemplateId]["Subject"] = "";
        $G_Templates[$TemplateId]["Body"] = "";
        $G_Templates[$TemplateId]["ItemBody"] = "";
        $G_Templates[$TemplateId]["PlainTextBody"] = "";
        $G_Templates[$TemplateId]["PlainTextItemBody"] = "";
        $G_Templates[$TemplateId]["Headers"] = "";
        $G_Templates[$TemplateId]["CollapseBodyMargins"] = FALSE;

        # set flag to display template editing form
        $G_DisplayMode = "Adding";
        break;

    case "Edit":
    case "Delete":
        # set display mode flag to editing or deletion confirmation as appropriate
        $G_DisplayMode = ($Action == "Delete") ? "Confirm" : "Editing";
        break;

    case "Confirm":
        # delete template
        unset($G_Templates[$TemplateId]);
        $Plugin->ConfigSetting("Templates", $G_Templates);

        # set flag to display template list
        $G_DisplayMode = "Listing";
        break;

    case "Save":
    case "Test":
        # if new template
        if ($TemplateId == "NEW")
        {
            # get next template ID
            $TemplateId = (($G_Templates === NULL) || !count($G_Templates)) ? 0
                    : (max(array_keys($G_Templates)) + 1);
        }

        # save template
        $G_Templates[$TemplateId] = array(
                "Name" => $_POST["F_Name"],
                "From" => $_POST["F_From"],
                "Subject" => $_POST["F_Subject"],
                "Body" => $_POST["F_Body"],
                "CollapseBodyMargins" => !!$_POST["F_CollapseBodyMargins"],
                "ItemBody" => $_POST["F_ItemBody"],
                "PlainTextBody" => $_POST["F_PlainTextBody"],
                "PlainTextItemBody" => $_POST["F_PlainTextItemBody"],
                "Headers" => $_POST["F_Headers"],
                );
        $Plugin->ConfigSetting("Templates", $G_Templates);
        $G_Msgs[] = "<i>".htmlspecialchars($G_Templates[$TemplateId]["Name"])
                ."</i> template saved.";

        # if we are to send a test email
        if ($Action == "Test")
        {
            # if we have resources specified to use for testing
            $Resources = array();
            if (strlen(trim($G_TestIds)))
            {
                # split list of resource IDs
                $Ids = explode(" ", trim(
                        preg_replace("/[^0-9]+/", " ", $G_TestIds)));

                # attempt to retrieve resources
                foreach ($Ids as $Id)
                {
                    $Resource = new Resource($Id);
                    if ($Resource->Status() > 0)
                    {
                        $Resources[$Id] = $Resource;
                    }
                }
            }

            # if we don't yet have resources to use for test email
            if (!count($Resources))
            {
                # retrieve random resources to use for test email
                $RFactory = new ResourceFactory();
                $Ids = $RFactory->GetItemIds();
                srand($G_TestSeed);
                $ResourceCount = rand(1, 20);
                $Resources = array();
                for ($Index = 0;  $Index < $ResourceCount;  $Index++)
                {
                    $Id = $Ids[rand(0, count($Ids) - 1)];
                    $Resources[$Id] = new Resource($Id);
                }
            }

            # send out test email to current user
            $Plugin->SendEmail($TemplateId,
                    $GLOBALS["G_User"]->Id(), $Resources);
            $G_Msgs[] = "Test email sent for <i>"
                    .htmlspecialchars($G_Templates[$TemplateId]["Name"])
                    ."</i> template.";
        }

        # set display mode flag to editin or template list depending on actiong
        $G_DisplayMode = ($Action == "Test") ? "Editing" : "Listing";
        break;

    case "Cancel":
    default:
        # set flag to display template list
        $G_DisplayMode = "Listing";
        break;
}

# load values for selected template if needed
if (in_array($G_DisplayMode, array("Editing", "Adding", "Confirm")))
{
        $G_Id = $TemplateId;
        $G_Name = $G_Templates[$TemplateId]["Name"];
        $G_From = $G_Templates[$TemplateId]["From"];
        $G_Subject = $G_Templates[$TemplateId]["Subject"];
        $G_Body = $G_Templates[$TemplateId]["Body"];
        $G_CollapseBodyMargins =
                $G_Templates[$TemplateId]["CollapseBodyMargins"];
        $G_ItemBody = $G_Templates[$TemplateId]["ItemBody"];
        $G_PlainTextBody = $G_Templates[$TemplateId]["PlainTextBody"];
        $G_PlainTextItemBody = $G_Templates[$TemplateId]["PlainTextItemBody"];
        $G_Headers = $G_Templates[$TemplateId]["Headers"];
}
