<?php

require_once 'piute_includes.php';
function extractLogins($prefix)
{
    $prefixLen = strlen($prefix);
    foreach ($_POST as $key => $value) {
        $index = strpos($key, $prefix);
        if ($index !== false) {
            $userId = substr($key, $prefixLen);
            $oneLogin = getUserById($userId);
            $loginList[] = $oneLogin;
        }
    }
    return $loginList;
}
session_start();
$fromText = $_POST['from_text'];
$subjectText = $_POST['subject_text'];
$messageText = $_POST['message_text'];
$correspondenceName = "Ad-Hoc (" . $subjectText . ")";
$loginList = extractLogins("member_id_");
$templatedCorrespondence = createCorrespondence($correspondenceName, $subjectText, $fromText, $messageText);
foreach ($loginList as $oneLogin) {
    $correspondence = correspondencePreparation($oneLogin, $templatedCorrespondence);
    sendCorrespondence($oneLogin, $correspondence);
    logTheCorrespondence($oneLogin, $corresondenceName);
}
header("Location: /php/correspondence_all.php");
//$errors = validateFields('add_hunt', $_POST, $rules);
//var_dump_j("jeff errors", $errors);
//exit;
// if there were errors, re-populate the form fields
if (!empty($errors)) {
    $fields = $_POST;
    var_dump("jeff errors");
    header("Location: /php/correspondence_user.php");
} else {
    // Send the correspondence.
    try {
        $userId = $_POST['user_id'];
        $corresondenceName = $_POST['correspondence'];
        $user = getUserById($userId);
        $correspondence = loadCorrespondence($corresondenceName);
        $correspondence = correspondencePreparation($user, $correspondence);
        //createMarkerFile();
        sendCorrespondence($user, $correspondence);
        logTheCorrespondence($user, $corresondenceName);
        header("Location: /php/correspondence_user.php");
    } catch (Exception $e) {
        // Unsuccessful login
        if ($e->getMessage() == 'no user found') {
            addError('login', 'We could not find you in our system');
            header('Location: /index.php');
        } else {
            if ($e->getMessage() == 'no results') {
                addError('login', 'Opps, looks like our system is down right now.');
                header('Location: /index.php');
            }
        }