#!/usr/bin/php -q
<?php
// Debug Mode for IDE runtime debugger
const SCRIPTDEBUG = 0;
const DEFAULTVALUES = 0;
// who was the sender
$GLOBALS['SERIAL_NUMBER'] = "UNKNOWN";
// is config->debug set
$GLOBALS['IS_DEBUG'] = 0;

// change to web server root to load scripts
chdir("/var/www");
// access to config file
require_once "src/foundation/class.siteconfig.php";
// db access; uses config file
require_once "src/foundation/class.common.php";
// access global conig
require_once "src/class/class.globalconfig.php";
// transator
require_once "src/class/cli/class.translator.email.php";
// mailer
require_once "libs/mailer/swift_required.php";

function init()
{
    $oConf = new GlobalConfig('en');
    $settings = $oConf->GetParams(array(143, 179, 153, 2563));
    $GLOBALS['SERIAL_NUMBER'] = isset($settings[143]) ? $settings[143]['str_val'] : 'UNKNOWN';
    $GLOBALS['IS_DEBUG'] = isset($settings[179]) ? intval($settings[179]['str_val']) : 0;
    $GLOBALS['DISTRIBUTOR_EMAIL'] = isset($settings[2563]) ? trim($settings[2563]['str_val']) : "";
    $GLOBALS['CUSTOMER_EMAIL'] = isset($settings[153]) ? trim($settings[153]['str_val']) : "";
}

/**
 * @param $id
 * @param $msg
 */
function writeError($id, $msg)
{
    fwrite($GLOBALS['stderr'], "ERROR: (" . $id . ") " . $msg . "\n");
}

function writeUsage()
{
    fwrite($GLOBALS['stdout'], "Usage: " . $GLOBALS['argv'][0] . " action_id message attachment\n\t123\n\timportant message\n\tfull path and file name\n");
}

/**
 * @param Swift_Message $message
 * @param string $msg_text
 */
function composeMessage(&$message, $msg_text)
{
    $nl = "\n";
    $head = "<head>
    <meta charset=\"utf - 8\">
    <title>SLA Email</title>
    <style>
        body {
            font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
            font-size: 12px;
        }
        div.left {
            text-align: left;
        }
        div.centered {
            text-align: center;
        }
        div.centered table {
            text-align: left;
            width: 80%;
            margin: 0 auto;
            border-collapse: collapse;
            border-spacing: 0;
        }
        table tr:nth-child(odd) {
            background-color: #ffffcc;
        }
        table tr:nth-child(even) {
            background-color: #ccffff;
        }
        th {
            text-align: left;
            padding: 0;
        }
        td {
            padding: 0;
        }
    </style>
</head>" . $nl;

    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
    {
        echo 'Message before adding of graph. ' . $msg_text . $nl;
    }

    // lets do strict html code
    $body = "<!DOCTYPE html>" . $nl;
    $body .= "<html lang=\"en\">" . $nl;
    $body .= $head;
    $body .= "<body>" . $nl;

    // seed text
    $body .= "    <div>" . $msg_text . "</div>" . $nl;

    // close up
    $body .= "</body>" . $nl;
    $body .= "</html>";

    // assign text
    $message->setBody($body, "text/html", "utf-8");

    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
    {
        echo $nl . 'Message after adding of graph. ' . $body . $nl;
    }
}

/**
 * @noinspection DuplicatedCode
 *
 * @param $id
 * @param $msg_text
 * @param string $attachment_file
 */
function send($id, $msg_text, $attachment_file = '')
{
    $nl = "\n";
    $language = new translator_email();
    $rc = $language->init();
    if (!$rc)
    {
        writeError(1, "Error language lookup: " . $language->getLastError());
        exit(1);
    }

    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
    {
        echo $nl . "Possible attachment: [" . $attachment_file . "]" . $nl;
    }

    /** @var SqlDb2 $oSql */
    $oSql = DBAccess::getSqlObj();
    // here fetch email settings
    $sql = "SELECT";
    $sql .= " * FROM ra_actions WHERE actions_id = " . $id;
    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
    {
        echo $nl . "Lookup command: " . $sql . $nl;
    }

    $access = $oSql->query($sql);
    if (!$access)
    {
        writeError(2, "Error table lookup: " . $oSql->lastError());
        exit(2);
    }

    $settings = array();
    while (($row = $oSql->fetchRowFields($access)))
    {
        $settings = $row;
    }
    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
    {
        var_dump($settings);
    }
    $count = count($settings);
    // no tables found silent exit
    if ($count == 0)
    {
        exit(2);
    }
    if ($settings["auth_type"] == "1")
    {
        $settings["auth_type"] = "ssl";
    } elseif ($settings["auth_type"] == "2")
    {
        $settings["auth_type"] = "tls";
    } else
    {
        $settings["auth_type"] = "";
    }

    try
    {
        $to = explode(';', $settings["recipient"]);
        if ($settings["recipient_distributor_on"] == 1 &&
            !empty($GLOBALS['DISTRIBUTOR_EMAIL']))
        {
            $to[] = $GLOBALS['DISTRIBUTOR_EMAIL'];
        }
        if ($settings["recipient_customer_on"] == 1 &&
            !empty($GLOBALS['CUSTOMER_EMAIL']))
        {
            $to[] = $GLOBALS['CUSTOMER_EMAIL'];
        }
        // look for empty array entries, like the one created by a trailing delimiter a@bc;d@fg;
        $recipients = array();
        foreach ($to as $recipient)
        {
            $target = trim($recipient);
            $email = filter_var($target, FILTER_VALIDATE_EMAIL);
            if ($email !== false)
            {
                $recipients[] = $target;
            }
        }
        // only send a message when we have someone to send it to
        $c = count($recipients);
        if ($c)
        {
            if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
            {
                var_dump($recipients);
            }

            // Create the Transport
            $transport = new Swift_SmtpTransport($settings["url"], intval($settings["url_port"]));
            $transport->setUsername($settings["login_name"]);
            $transport->setPassword($settings["login_pwd"]);
            if (!(isset($settings["smtp_auth"]) && $settings["smtp_auth"] == 0))
            {
                $transport->setEncryption($settings["auth_type"]);
            }

            // Create the Mailer using your created Transport
            $mailer = new Swift_Mailer($transport);
            // Or to use the Echo Logger
            if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
            {
                $logger = new Swift_Plugins_Loggers_EchoLogger();
                $mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));
            }

            // Create a Message
            $message = new Swift_Message();
            // add the possible sender here
            $sender = 'airpointer@airpointer.tech';
            if (isset($settings["sender"]) && trim($settings["sender"]) != '')
            {
                $email = filter_var(trim($settings["sender"]), FILTER_VALIDATE_EMAIL);
                if ($email)
                {
                    $sender = $email;
                }
            }
            $message->setFrom(array($sender => $GLOBALS['SERIAL_NUMBER']));
            $message->setSender($sender);
            if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
            {
                var_dump($message->getFrom());
            }
            $message->setTo($recipients);
            $message->setSubject($settings["subject"]);
            $message->setMaxLineLength(256); // max: 1000
            $message->setPriority(3); // 1 to 5: Highest, High, Normal, Low, Lowest

            if ($attachment_file !== '')
            {
                $message->attach(Swift_Attachment::fromPath($attachment_file));
            }

            $alt_text = $language->translate('AlternativeText');
            composeMessage($message, $msg_text);
            $message->addPart($alt_text, "text/plain", "utf-8");

            // Send the message
            if ($mailer->send($message, $failures))
            {
                if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
                {
                    echo $nl . 'Message has been sent.' . $nl;
                }
            } else
            {
                writeError(7, "No message sent to: " . implode(';', $failures));
                exit(7);
            }
        } else
        {
            writeError(4, "No recipients found");
            exit(4);
        }
    } catch (Exception $e)
    {
        writeError(5, "Error sending: " . $e->getMessage());
        exit(5);
    }
}

function main($argc, $argv)
{
    if (SCRIPTDEBUG && DEFAULTVALUES)
    {
        send(14, "olla");
    } else
    {
        if ($argc < 3)
        {
            writeUsage();
            writeError(2, "Wrong or missing command line parameters");
            exit(6);
        }

        if ($argc == 3)
        {
            send($argv[1], $argv[2]);
        } else
        {
            send($argv[1], $argv[2], $argv[3]);
        }
    }
    exit(0);
}

// supported STDIN/OUT/ERR syntax for php version 4.3 till 5.3
$stderr = fopen('php://stderr', 'w');
$stdout = fopen('php://stdout', 'w');
// fetch our serial number, debug flag
init();
// $argc, $argv are filled in by the CLI engine and defined as globals
main($argc, $argv);
