<?php

class Statuses extends Base {

    // Variables.

    private $current_user_serial = 0;
    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_serial = $_SESSION[self::USER_SERIAL] ?? 0;
        $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;
    }

    // ==========
    // Add Status
    // ==========

    public function addStatus() {

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

        switch ($step) {

            case "prompt":

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

                $this->displayContent($content);

                break;

            case "add":

                $status_name = filter_input(INPUT_POST, "status_name") ?: "";
                $status_classes = filter_input(INPUT_POST, "status_classes") ?: "";
                $status_active = filter_input(INPUT_POST, "status_active", FILTER_VALIDATE_BOOLEAN) ?: false;

                $SQL = "insert into statuses
          
                         (  status_name,
                            status_classes,
                            status_active,
                            status_creator,
                            status_created )
                               
                  VALUES ( :status_name,
                           :status_classes,
                           :status_active,
                           :status_creator,
                           :status_created )";

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

                $statement->bindValue(":status_name", $status_name);
                $statement->bindValue(":status_classes", $status_classes);
                $statement->bindValue(":status_active", $status_active, PDO::PARAM_BOOL);
                $statement->bindValue(":status_creator", $this->current_user_name);
                $statement->bindValue(":status_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // =============
    // Delete Status
    // =============

    public function deleteStatus() {

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

        $status = $this->getStatus($status_serial);

        if ($status->count() == 0) {
            $this->logError("Invalid Status ({$status_serial}). " . __METHOD__);
        }

        $SQL = "delete from statuses
                  where status_serial = {$status_serial}";

        $this->executeSQL($SQL);
    }

    // ============================
    // Determine if a Status exists
    // ============================

    public function statusExists() {

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

        $SQL = "select status_serial
              from view_statuses
             where status_serial      != :status_serial
               and lower(status_name)  = :status_name";

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

        $statement->bindValue(":status_serial", $status_serial);
        $statement->bindValue(":status_name", strtolower($status_name));

        $statement->execute();

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

        $exists = (count($recordset) > 0) ? true : false;

        echo json_encode($exists);
    }

    // ======================================
    // Determine if a Status is Active (AJAX)
    // ======================================

    public function statusActive() {

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

        $active = false;

        $SQL = "select workorder_status
              from workorders
             where workorder_status = {$status_serial}
             limit 1";

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

        $active = ($workorders->count() > 0) ? true : false;

        echo json_encode($active);
    }

    // =============
    // Edit a Status
    // =============

    public function editStatus() {

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

        switch ($step) {

            case "prompt":

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

                $status = $this->getStatus($status_serial);

                if ($status->count() == 0) {
                    $this->logError("Invalid Status ({$status_serial}). " . __METHOD__);
                }

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

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

                $this->displayContent($content);

                break;

            case "update":

                $status_serial = filter_input(INPUT_POST, "status_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
                $status_name = filter_input(INPUT_POST, "status_name") ?: "";
                $status_classes = filter_input(INPUT_POST, "status_classes") ?: "";
                $status_active = filter_input(INPUT_POST, "status_active", FILTER_VALIDATE_BOOLEAN) ?: false;
                $status_default = filter_input(INPUT_POST, "status_default", FILTER_VALIDATE_BOOLEAN) ?: false;

                // Verify the Status

                $status = $this->getStatus($status_serial);

                if ($status->count() == 0) {
                    $this->logError("Invalid Status ({$status_serial}). " . __METHOD__);
                }

                $SQL = "update statuses 
                   set status_name    = :status_name,
                       status_classes = :status_classes,
                       status_active  = :status_active,
                       status_default = :status_default,
                       status_changer = :status_changer,
                       status_changed = :status_changed
                 where status_serial  = :status_serial";

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

                $statement->bindValue(":status_serial", $status_serial);
                $statement->bindValue(":status_name", $status_name);
                $statement->bindValue(":status_classes", $status_classes);
                $statement->bindValue(":status_active", $status_active, PDO::PARAM_BOOL);
                $statement->bindValue(":status_default", $status_default, PDO::PARAM_BOOL);
                $statement->bindValue(":status_changer", $this->current_user_name);
                $statement->bindValue(":status_changed", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ================================
    // Return an Active Statuses Object
    // ================================

    public function getActiveStatuses() {

        $SQL = "select view_statuses.*
              from view_statuses
             where status_active is true";

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

    // -------------------------
    // Return the Default Status
    // -------------------------

    public function getDefaultStatus() {

        $SQL = "select status_serial
              from view_statuses
             where status_default is true";

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

    // =======================
    // Return an Status Object
    // =======================

    public function getStatus($status_serial = 0) {

        $SQL = "select view_statuses.*
              from view_statuses
             where status_serial = {$status_serial}";

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

    // ===========================
    // Return a Statuss Object
    // ===========================

    public function getStatuses() {

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

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

    // ============================
    // Return a Statuss Page Object
    // ============================

    public function getStatusesPage() {

        // Find Criteria

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

        $find_words = implode("|", explode(" ", $find_status));

        // Record Count

        $connection = $this->connect();

        $SQL = "select count(*) as count
              from view_statuses
             where status_name    regexp :status_name
                or status_classes regexp :status_classes";

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

        $statement->bindValue(":status_name", $find_words);
        $statement->bindValue(":status_classes", $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_statuses.*
              from view_statuses
             where status_name    regexp :status_name
                or status_classes regexp :status_classes
          order by status_name
             limit {$this->pagination_size}
            offset {$offset}";

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

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

        $statement->execute();

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

        // Insert Pagination Attributes

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

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

        return $statuses;
    }

    // ==============
    // Setup Statuses
    // ==============

    public function setupStatuses() {

        $statuses = $this->getStatusesPage();
        $popovers = (new Popovers())->getPopovers();

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

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

        $this->displayContent($content);
    }
}

?>
