<?php

// ============
// Alerts Class
// ============

class Alerts extends Base {

    // Variables.

    private $current_user_id = "";
    private $current_user_name = "";
    private $current_user_email = "";
    private $pagination_size = 20;
    private $pagination_page = 1;

    // ==================
    // Class Constructor.
    // ==================

    public function __construct() {

        set_error_handler(array($this, "displayError"));

        date_default_timezone_set(self::TIMEZONE);

        $this->current_user_id = $_SESSION[self::USER_ID] ?? "";
        $this->current_user_name = $_SESSION[self::USER_NAME] ?? "";
        $this->current_user_email = $_SESSION[self::USER_EMAIL] ?? "";

        $this->pagination_page = $_SESSION[self::PAGINATION_PAGE] ?? 1;
    }

    // ============
    // Setup Alerts
    // ============

    public function setupAlerts() {

        $alerts = $this->getAlertsPage();

        $popovers = (new Popovers())->getPopovers();

        $XML = $this->mergeXML($alerts, "<XML/>");
        $XML = $this->mergeXML($popovers, $XML);

        $content = $this->applyXSL($XML, $this->getXSL("setupAlerts"));

        $this->displayContent($content);
    }

    // =========
    // Add Alert
    // =========

    public function addAlert() {

        $step = filter_input(INPUT_POST, "step") ?: "prompt";

        switch ($step) {

            case "prompt":

                $content = $this->applyXSL("", $this->getXSL("addAlert"));

                $this->displayContent($content);

                break;

            case "add":

                $alert_title = filter_input(INPUT_POST, "alert_title") ?: "";
                $alert_starts_date = filter_input(INPUT_POST, "alert_starts_date") ?: "";
                $alert_starts_time = filter_input(INPUT_POST, "alert_starts_time") ?: "";
                $alert_expires_date = filter_input(INPUT_POST, "alert_expires_date") ?: "";
                $alert_expires_time = filter_input(INPUT_POST, "alert_expires_time") ?: "";
                $alert_message = filter_input(INPUT_POST, "alert_message") ?: "";

                $alert_starts = date("Y-m-d H:i", strtotime("{$alert_starts_date} {$alert_starts_time}"));
                $alert_expires = date("Y-m-d H:i", strtotime("{$alert_expires_date} {$alert_expires_time}"));

                $SQL = "insert into alerts
          
                         (  alert_title,
                            alert_started,
                            alert_expired,
                            alert_message,
                            alert_creator,
                            alert_created )
                               
                  VALUES ( :alert_title,
                           :alert_started,
                           :alert_expired,
                           :alert_message,
                           :alert_creator,
                           :alert_created )";

                $statement = $this->connect()->prepare($SQL);

                $statement->bindValue(":alert_title", $alert_title);
                $statement->bindValue(":alert_started", $alert_starts);
                $statement->bindValue(":alert_expired", $alert_expires);
                $statement->bindValue(":alert_message", $alert_message);
                $statement->bindValue(":alert_creator", $this->current_user_name);
                $statement->bindValue(":alert_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ============
    // Delete Alert
    // ============

    public function deleteAlert() {

        $alert_serial = filter_input(INPUT_POST, "alert_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;

        $alert = $this->getAlert($alert_serial);

        if ($alert->count() == 0) {
            $this->logError("Invalid Alert ({$alert_serial}). " . __METHOD__);
        }

        $SQL = "delete from alerts
                 where alert_serial = {$alert_serial}";

        $this->executeSQL($SQL);
    }

    // ==========
    // Edit Alert
    // ==========

    public function editAlert() {

        $step = filter_input(INPUT_POST, "step") ?: "prompt";

        switch ($step) {

            case "prompt":

                $alert_serial = filter_input(INPUT_POST, "alert_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;

                $alert = $this->getAlert($alert_serial);

                if ($alert->count() == 0) {
                    $this->logError("Invalid Alert ({$alert_serial}): " . __METHOD__);
                }

                $content = $this->applyXSL($alert, $this->getXSL("editAlert"));

                $this->displayContent($content);

                break;

            case "update":

                $alert_serial = filter_input(INPUT_POST, "alert_serial") ?: 0;
                $alert_title = filter_input(INPUT_POST, "alert_title") ?: "";
                $alert_starts_date = filter_input(INPUT_POST, "alert_starts_date") ?: "";
                $alert_starts_time = filter_input(INPUT_POST, "alert_starts_time") ?: "";
                $alert_expires_date = filter_input(INPUT_POST, "alert_expires_date") ?: "";
                $alert_expires_time = filter_input(INPUT_POST, "alert_expires_time") ?: "";
                $alert_message = filter_input(INPUT_POST, "alert_message") ?: "";

                $alert_starts = date("Y-m-d H:i", strtotime("{$alert_starts_date} {$alert_starts_time}"));
                $alert_expires = date("Y-m-d H:i", strtotime("{$alert_expires_date} {$alert_expires_time}"));

                $alert = $this->getAlert($alert_serial);

                if ($alert->count() === 0) {
                    $this->logError("Invalid Alert ({$alert_serial}). " . __METHOD__);
                }

                $connection = $this->connect();

                $SQL = "update alerts
                           set alert_title   = :alert_title,
                               alert_started = :alert_started,
                               alert_expired = :alert_expired,
                               alert_message = :alert_message
                         where alert_serial  = :alert_serial";

                $statement = $connection->prepare($SQL);

                $statement->bindValue(":alert_serial", $alert_serial);
                $statement->bindValue(":alert_title", $alert_title);
                $statement->bindValue(":alert_started", $alert_starts);
                $statement->bindValue(":alert_expired", $alert_expires);
                $statement->bindValue(":alert_message", $alert_message, PDO::PARAM_STR);

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // =====================
    // Return a Alert Object
    // =====================

    public function getAlert($alert_serial = 0) {

        $SQL = "select *,
                   date_format(alert_started, '%Y')                 as alert_started_year,
                   date_format(alert_started, '%m')                 as alert_started_month,
                   date_format(alert_started, '%b')                 as alert_started_month_abbreviated,
                   date_format(alert_started, '%M')                 as alert_started_month_verbose,
                   date_format(alert_started, '%d')                 as alert_started_day,
                   date_format(alert_started, '%a')                 as alert_started_day_abbreviated,
                   date_format(alert_started, '%W')                 as alert_started_day_verbose,
                   date_format(alert_started, '%Y-%m-%d')           as alert_started_date,
                   date_format(alert_started, '%W, %M %D')          as alert_started_date_verbose,
                   date_format(alert_started, '%H:%i')              as alert_started_time,
                   date_format(alert_started, '%l:%i %p')           as alert_started_time_verbose,
                   date_format(alert_started, '%Y-%m-%d %l:%i %p')  as alert_started_verbose,

                   date_format(alert_expired, '%Y')                as alert_expired_year,
                   date_format(alert_expired, '%m')                as alert_expired_month,
                   date_format(alert_expired, '%b')                as alert_expired_month_abbreviated,
                   date_format(alert_expired, '%M')                as alert_expired_month_verbose,
                   date_format(alert_expired, '%d')                as alert_expired_day,
                   date_format(alert_expired, '%a')                as alert_expired_day_abbreviated,
                   date_format(alert_expired, '%W')                as alert_expired_day_verbose,
                   date_format(alert_expired, '%Y-%m-%d')          as alert_expired_date,
                   date_format(alert_expired, '%W, %M %D')         as alert_expired_date_verbose,
                   date_format(alert_expired, '%H:%i')             as alert_expired_time,
                   date_format(alert_expired, '%l:%i %p')          as alert_expired_time_verbose,
                   date_format(alert_expired, '%Y-%m-%d %l:%i %p') as alert_expired_verbose

              from alerts

             where alert_serial = {$alert_serial}";

        return $this->getTable("alerts", $SQL);
    }

    // ========================
    // Return a Alerts Object
    // ========================

    public function getAlerts() {

        $SQL = "select view_alerts.* 
                  from view_alerts";

        return $this->getTable("alerts", $SQL);
    }

    // ===========================
    // Return a Alerts Page Object
    // ===========================

    public function getAlertsPage() {

        // Find Criteria

        $find_alert = filter_input(INPUT_POST, "find_alert") ?: "";
        $find_words = $this->sanitizeString($find_alert);

        // Show Per Page

        $this->pagination_size = filter_input(INPUT_POST, "alerts_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;

        // Record Count

        $connection = $this->connect();

        $SQL = "select count(*) as count
                  from view_alerts
                 where alert_title regexp :alert_title";

        $statement = $connection->prepare($SQL);

        $statement->bindValue(":alert_title", $find_words);

        $statement->execute();

        $recordset = $statement->fetch(PDO::FETCH_ASSOC);

        $count = (count($recordset) > 0) ? (integer) $recordset["count"] : (integer) 0;

        // Pagination

        $pagination = filter_input(INPUT_POST, "pagination") ?: "";

        switch ($pagination) {

            case "first" : $this->pagination_page = 1;
                break;
            case "previous" : $this->pagination_page = max(($this->pagination_page - 1), 1);
                break;
            case "next" : $this->pagination_page = ($this->pagination_page + 1);
                break;
            case "last" : $this->pagination_page = ($count / $this->pagination_size);
                break;
        }

        $offset = (($this->pagination_page * $this->pagination_size) - $this->pagination_size);
        $start = ($offset + 1);
        $end = min($count, (($start + $this->pagination_size) - 1));

        // Data

        $SQL = "select view_alerts.*
                  from view_alerts
                 where alert_title regexp :alert_title
                 limit {$this->pagination_size}
                offset {$offset}";

        $statement = $connection->prepare($SQL);

        $statement->bindValue(":alert_title", $find_words);

        $statement->execute();

        $alerts = $this->getTableXML("alerts", $statement);

        // Insert Pagination Attributes

        $alerts->addAttribute("count", $count);
        $alerts->addAttribute("start", $start);
        $alerts->addAttribute("end", $end);
        $alerts->addAttribute("page", $this->pagination_page);

        $_SESSION[self::PAGINATION_PAGE] = $this->pagination_page;

        return $alerts;
    }

    // ===============================
    // Return an Active Alerts Object.
    // ===============================

    public function getActiveAlerts() {

        $SQL = "select *,

                   date_format(alert_started, '%Y')                 as alert_started_year,
                   date_format(alert_started, '%m')                 as alert_started_month,
                   date_format(alert_started, '%b')                 as alert_started_month_abbreviated,
                   date_format(alert_started, '%M')                 as alert_started_month_verbose,
                   date_format(alert_started, '%d')                 as alert_started_day,
                   date_format(alert_started, '%a')                 as alert_started_day_abbreviated,
                   date_format(alert_started, '%W')                 as alert_started_day_verbose,
                   date_format(alert_started, '%Y-%m-%d')           as alert_started_date,
                   date_format(alert_started, '%W, %M %D')          as alert_started_date_verbose,
                   date_format(alert_started, '%H:%i')              as alert_started_time,
                   date_format(alert_started, '%l:%i %p')           as alert_started_time_verbose,
                   date_format(alert_started, '%Y-%m-%d %l:%i %p')  as alert_started_verbose,

                   date_format(alert_expired, '%Y')                as alert_expired_year,
                   date_format(alert_expired, '%m')                as alert_expired_month,
                   date_format(alert_expired, '%b')                as alert_expired_month_abbreviated,
                   date_format(alert_expired, '%M')                as alert_expired_month_verbose,
                   date_format(alert_expired, '%d')                as alert_expired_day,
                   date_format(alert_expired, '%a')                as alert_expired_day_abbreviated,
                   date_format(alert_expired, '%W')                as alert_expired_day_verbose,
                   date_format(alert_expired, '%Y-%m-%d')          as alert_expired_date,
                   date_format(alert_expired, '%W, %M %D')         as alert_expired_date_verbose,
                   date_format(alert_expired, '%H:%i')             as alert_expired_time,
                   date_format(alert_expired, '%l:%i %p')          as alert_expired_time_verbose,
                   date_format(alert_expired, '%Y-%m-%d %l:%i %p') as alert_expired_verbose

              from alerts

             where (alert_started < now() and alert_expired > now())

          order by alert_expired";

        $alerts = $this->getTable("alerts", $SQL);

        foreach ($alerts as $alert) {
            $alert->alert_time_elapsed = $this->getTimeElapsed((string) $alert->alert_started);
        }

        return $alerts;
    }
}

?>
