#!/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";
// translator
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 translator_email $language
 *
 * @return string
 */
function createStatus(&$language)
{
    $_filter = (AS_ERROR | AS_WARNING);
    $s = new airStatus();
    $s->Read();

    return "    <table style='margin-top:10px; margin-bottom:20px;'>
        <tr>
            <td colspan='2' style='font-weight:bold; font-size:12pt;'>" . $language->translate('StatusStatisticsCurrent') . ":</td>
        </tr>
        <tr>
            <td style='padding-right:30px; font-size:10pt;'>" . $language->translate('TotalFailures') . ":</td>
            <td style='color:red;font-weight:bold; font-size:10pt;'>" . ($_filter && !($_filter & AS_ERROR) ? $language->translate('filtered') : $s->CountFailures()) . "</td>
        </tr>
        <tr>
            <td style='padding-right:30px; font-size:10pt;'>" . $language->translate('TotalWarnings') . ":</td>
            <td style='font-weight:bold; font-size:10pt;'>" . ($_filter && !($_filter & AS_WARNING) ? $language->translate('filtered') : $s->CountWarnings()) . "</td>
        </tr>
    </table>";
}

/**
 * @param $t
 *
 * @return bool|string
 */
function _cvTime($t)
{
    if ($t > 0)
    {
        return date("M jS, H:i", $t);
    } else
    {
        return "-";
    }
}

/**
 * @param translator_email $language
 * @param $period
 *
 * @return string
 */
function createHistoryStatus(&$language, $period)
{
    $body = "";
    $i = 0;
    $_filter = (AS_ERROR | AS_WARNING);
    $te = time();
    $ts = $te - (60 * 60 * $period);

    $eol = "<br />";
    $nl = "\n";
    $space = "&nbsp;";
    $ok = "<strong>ok</strong>";
    $par_s = "<tr>" . $nl;
    $par_e = "        </tr>" . $nl;
    $head_s = "           <td style='font-weight: bold; padding-left:2px; font-size:10pt;'>";
    $head_ps = "           <td style='width:40%; font-weight: bold; padding-left:2px; font-size:10pt;'>";
    //$item_s = "<td  style='color: ".$col.";' >";
    $item_e = "           </td>" . $nl;

    $s = new airStatus();
    $s->ReadHistory($ts, $te, 0, $_filter, 1, false);

    $body .= "
    " . date("r", $ts) . " - " . date("r", $te) . $eol . $eol . "
    " . "<table style='background-color:#e0e0e0; margin-top:10px; margin-bottom:20px; width: 100%;'>" . "
        " . $par_s
        . $head_s . "F" . $item_e
        . $head_s . "W" . $item_e
        . $head_ps . $language->translate('Parameter') . $item_e
        . $head_s . $language->translate('Value') . $item_e
        . $head_s . $language->translate('Unit') . $item_e
        . $head_s . $language->translate('Coming') . $item_e
        . $par_e;
    /** @var airStateCollection $c */
    while (($c = $s->GetCondition($i)))
    {
        $e = $c->GetMaxStatus();
        $col = $e == AS_ERROR ? "red" : "black";
        $item_s = "<td style='color: " . $col . "; padding-left:2px; font-size:10pt;' >";
        $body .=
            $par_s
            . $item_s . ($e == AS_ERROR ? "&#x2714;" : ($e < AS_WARNING ? $ok : $space)) . $item_e
            . $item_s . ($e == AS_WARNING ? "&#x2714;" : $space) . $item_e
            . $item_s . $c->GetName() . $item_e
            . $item_s . $c->GetFirstVal() . $item_e
            . $item_s . $c->GetUnit() . $item_e
            . $item_s . _cvTime($c->GetStart()) . $item_e
            . $par_e;
        $i++;
    }
    $body .= "        <tr>
            <td colspan='6'>
                <table style='margin-top:10px;'>
                    <tr>
                        <td colspan='2' style='font-weight:bold; font-size:12pt;'>" . $language->translate('StatusStatistics') . ":</td>
                    </tr>
                    <tr>
                        <td style='padding-right:30px; font-size:10pt;'>" . $language->translate('TotalFailures') . ":</td>
                        <td style='color:red;font-weight:bold; font-size:10pt;'>" . ($_filter && !($_filter & AS_ERROR) ? $language->translate('filtered') : $s->CountFailures()) . "</td>
                    </tr>
                    <tr>
                        <td style='padding-right:30px; font-size:10pt;'>" . $language->translate('TotalWarnings') . ":</td>
                        <td style='font-weight:bold; font-size:10pt;'>" . ($_filter && !($_filter & AS_WARNING) ? $language->translate('filtered') : $s->CountWarnings()) . "</td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>";

    return $body;
}

/**
 * @param $id
 * @param $period
 * @param $format
 *
 * @return bool|string
 */
function createReport($id, $period, $format)
{
    $nl = "\n";
    $report_file = '';

    $oReport = new ReportsCreator();
    $oReport->setLanguage();

    if ($oReport->Init($id))
    {
        $tNow = getdate();
        $tEnd = mktime(0, 0, 0, $tNow["mon"], $tNow["mday"], $tNow["year"]);
        switch ($period)
        {
            case 1:
                { // day
                    $tStart = $tEnd - (60 * 60 * 24);
                }
                break;
            case 2:
                { // week
                    $tStart = $tEnd - (60 * 60 * 24 * 7);
                }
                break;
            case 3:
                { // month
                    $tNow["mon"] = $tNow["mon"] <= 1 ? 12 : $tNow["mon"];
                    $tNow["year"] -= $tNow["mon"] == 12 ? 1 : 0;
                    $tStart = mktime(0, 0, 0, $tNow["mon"], $tNow["mday"], $tNow["year"]);
                }
                break;
            default:
            {
                $tStart = $tEnd - (60 * 60 * 24);
            }
        }
        $oReport->SetStartEnd($tStart, $tEnd);
        $oReport->ReadValues();
        if (!$oReport->getLastError())
        {
            $oReport->CreateDoc($format, "file");
            if (!$oReport->getLastError())
            {
                $report_file = $oReport->GetDocFilename();
                if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
                {
                    echo $nl . 'Report file: ' . $report_file . $nl;
                }
            } else
            {
                if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
                {
                    echo $nl . "Error report create: " . $oReport->getLastError() . $nl;
                }
            }
        } else
        {
            if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
            {
                echo $nl . "Error report read: " . $oReport->getLastError() . $nl;
            }
        }
    }

    return $report_file;
}

/**
 * @param Swift_Message $message
 * @param translator_email $language
 * @param string $msg_text
 * @param string $path
 * @param string $status_msg
 * @param string $status_history
 */
function composeMessage(&$message, &$language, $msg_text, $path = '', $status_msg = '', $status_history = '')
{
    $eol = "<br />";
    $nl = "\n";
    $head = "<head>
    <meta charset=\"utf-8\">
    <title>r&a email channel</title>
    <style>
        th, td {
            padding: 0;
        }
        table {
            font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
            border-collapse: collapse;
            border-spacing: 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;
    $body .= "    <div style=\"width: 655px; font-family: Verdana, Geneva, Arial, Helvetica, sans-serif; font-size: 12px;\">" . $nl;
    // add graph
    if ($path)
    {
        // attach graph inline
        $cid = $message->embed(Swift_Image::fromPath($path));
        $body .= "    " . $language->translate('Graph') . $eol . $nl;
        // inline graph
        $body .= "    <div style=\"text-align: center;\"><img src=\"" . $cid . "\" alt=\"Graph\" style=\"height: 400px; width: 650px\" ></div>" . $eol . $nl;
    }
    // airXXX history status
    if ($status_history)
    {
        $body .= $status_history . $nl;
    }
    // airXXX current status
    if ($status_msg)
    {
        $body .= $status_msg . $nl;
    }
    // seed text
    $body .= "    <div>" . $msg_text . "</div>" . $nl;
    // close up
    $body .= "    </div>" . $nl;
    $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"] = "";
    }

    $inline_graph = false;
    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);
            }

            $status_msg = '';
            if ($settings["airx_status"] > 0)
            {
                // airXXX status
                require_once "src/class/class.airStatus.php";
                $status_msg = createStatus($language);
            }
            $status_history = '';
            if ($settings["airx_history_status"] > 0)
            {
                require_once "src/class/class.airStatus.php";
                $status_history = createHistoryStatus($language, intval($settings["design_period"]));
            }
            // reports visible when the feature is enabled
            $report_file = '';
            if ($settings["ref_report"] > 0)
            {
                require_once "src/class/class.reports.php";
                $report_file = createReport(intval($settings["ref_report"]), intval($settings["report_period"]), $settings["report_format"]);
            }
            // download and export are both missing and hidden from the user
            // $settings["ref_download"] and $settings["ref_export"]

            // 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(80); // max: 1000
            $message->setPriority(3); // 1 to 5: Highest, High, Normal, Low, Lowest

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

            // build graph and new message
            if ($settings["ref_design"] > 0)
            {
                $sub_id = mt_rand();
                $name = 'graph_' . $sub_id . '.png';
                $path = '/var/www/public/display/Cache/';
                //$cmd = '/usr/bin/wget --quiet --output-document="' . $path . $name . '" "http://localhost/display/FetchGraph.php?te=0&ts=' . $settings["design_period"] . '&leg=1&h=400&w=650&design=' . $settings["ref_design"] . '"';
                $cmd = '/usr/bin/curl --fail --silent --connect-timeout 5 --max-time 40 "http://localhost/display/FetchGraph.php?avg=' . $settings["design_avg"] . '&te=0&ts=' . $settings["design_period"] . '&h=400&w=650&design=' . $settings["ref_design"] . '" --output "' . $path . $name . '"';
                $err = array();
                exec($cmd, $err, $rc);
                if (is_file($path . $name) && filesize($path . $name) > 0)
                {
                    if (SCRIPTDEBUG || $GLOBALS['IS_DEBUG'])
                    {
                        echo 'Graph [' . $path . $name . '] has been created.';
                    }
                    if (touch($path . $name))
                    {
                        chmod($path . $name, 0666);
                    }
                    composeMessage($message, $language, $msg_text, $path . $name, $status_msg, $status_history);
                    $inline_graph = true;
                } else
                {
                    writeError(3, "Error creating graph: " . implode("\n", $err));
                    exit(3);
                }
            }

            $alt_text = $language->translate('AlternativeText');
            if (!$inline_graph)
            {
                composeMessage($message, $language, $msg_text, '', $status_msg, $status_history);
            }
            $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);
    }
}

/** @noinspection DuplicatedCode */
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);
