<?php
    include dirname(__FILE__) . '/../php_only_scripts/global_after_session.php';
    include dirname(__FILE__) . '/../php_only_scripts/database.php';
    
    // Create and Setup the database
    $db = new Database();
    $db->setupTmsDB();

    // Let's create and get the users to inform
    $sql='SELECT * 
          FROM users 
          WHERE CompanyID = 1 
          AND UserTemplateOnly=0 
          AND AccountStatus="Active" 
          AND SUEmployee=1;';
    $usersToNotify = $db->queryDB($sql, $userRow, "checkemails cron job 1");

    // Loop through the returned results
    while ($userToNofity=mysqli_fetch_array($usersToNotify)){
        // Init the message
        $messageToSend='This is an automated test from the TMS to check the status ' .
                       'of the e-mail sending system.  If ever you do not get this ' .
                       'e-mail in the morning, then please report it to EES technical ' .
                       'support. <br><br> To report a problem, you can ' .
                       'reply to a previous e-mail or call us at (720)552-7997.<br><br>' .
                       'Regards, <br><br>Evolve Engineering and Software Support Team<br>' .
                       '(720)552-7997';

        // First determine if they care about any changes
        if ($messageToSend!="" && 
            preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $userToNofity["EMail"])){

            // Decode the quotes to be shown as quotes.  Not weirdness
            $messageToSend = htmlspecialchars_decode ($messageToSend, ENT_COMPAT | ENT_HTML401);

            // Create the subject
            $subject = htmlspecialchars_decode ("E-Mail System Check");
            $headers = "From: EES Mail Admin"." <admin@eestms.com>\r\n"; 
            $headers .= "MIME-Version: 1.0\r\n";
            $headers .= "Content-type: text/html; charset=iso-8859-1\r\n";

            try {
                // Attempt to mail it
                mail($userToNofity["EMail"],$subject,$messageToSend,$headers);
            } 
            catch (Exception $e) {
                // Make an error log on the server first in case the e-mail system is down
                error_log("E-mail not sent to " . $userToNofity["EMail"] . ".", 0);
                
                // Try to send the same error to tech support e-mail
                error_log("E-mail not sent to " . $userToNofity["EMail"] . ".", 1, "admin@eestms.com");
            }
        }
    }
?>       

