<?php

// ===============
// Dropdowns Class
// ===============

class Dropdowns 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;
    }

    // ============
    // Add Dropdown
    // ============

    public function addDropdown() {

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

        switch ($step) {

            case "prompt":

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

                $dropdowntype = $this->getDropdowntype($dropdowntype_serial);

                if ($dropdowntype->count() == 0) {
                    $this->logError("Invalid Dropdowntype ({$dropdowntype_serial}). " . __METHOD__);
                }

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

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

                $this->displayContent($content);

                break;

            case "add":

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

                $SQL = "insert into dropdowns
          
                         (  dropdown_dropdowntype,
                            dropdown_value,
                            dropdown_creator,
                            dropdown_created )
                               
                  VALUES ( :dropdown_dropdowntype,
                           :dropdown_value,
                           :dropdown_creator,
                           :dropdown_created )";

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

                $statement->bindValue(":dropdown_dropdowntype", $dropdowntype_serial);
                $statement->bindValue(":dropdown_value", $dropdown_value);
                $statement->bindValue(":dropdown_creator", $this->current_user_name);
                $statement->bindValue(":dropdown_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ================
    // Add Dropdowntype
    // ================

    public function addDropdowntype() {

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

        switch ($step) {

            case "prompt":

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

                $this->displayContent($content);

                break;

            case "add":

                $dropdowntype_name = filter_input(INPUT_POST, "dropdowntype_name") ?: "";
                $dropdowntype_title = filter_input(INPUT_POST, "dropdowntype_title") ?: "";
                $dropdowntype_table = filter_input(INPUT_POST, "dropdowntype_table") ?: "";
                $dropdowntype_column = filter_input(INPUT_POST, "dropdowntype_column") ?: "";

                $SQL = "insert into dropdowntypes
          
                         (  dropdowntype_name,
                            dropdowntype_title,
                            dropdowntype_table,
                            dropdowntype_column,
                            dropdowntype_creator,
                            dropdowntype_created )
                               
                  VALUES ( :dropdowntype_name,
                           :dropdowntype_title,
                           :dropdowntype_table,
                           :dropdowntype_column,
                           :dropdowntype_creator,
                           :dropdowntype_created )";

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

                $statement->bindValue(":dropdowntype_name", $dropdowntype_name);
                $statement->bindValue(":dropdowntype_title", $dropdowntype_title);
                $statement->bindValue(":dropdowntype_table", $dropdowntype_table);
                $statement->bindValue(":dropdowntype_column", $dropdowntype_column);
                $statement->bindValue(":dropdowntype_creator", $this->current_user_name);
                $statement->bindValue(":dropdowntype_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ===============
    // Delete Dropdown
    // ===============

    public function deleteDropdown() {

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

        $dropdown = $this->getDropdown($dropdown_serial);

        if ($dropdown->count() == 0) {
            $this->logError("Invalid Dropdown ({$dropdown_serial}). " . __METHOD__);
        }

        $SQL = "delete from dropdowns
                  where dropdown_serial = {$dropdown_serial}";

        $this->executeSQL($SQL);
    }

    // ===================
    // Delete Dropdowntype
    // ===================

    public function deleteDropdowntype() {

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

        $dropdowntype = $this->getDropdowntype($dropdowntype_serial);

        if ($dropdowntype->count() == 0) {
            $this->logError("Invalid Dropdowntype ({$dropdowntype_serial}). " . __METHOD__);
        }

        $SQL = "delete from dropdowntypes
                  where dropdowntype_serial = {$dropdowntype_serial}";

        $this->executeSQL($SQL);
    }

    // ==============================
    // Determine if a Dropdown exists
    // ==============================

    public function dropdownExists() {

        $dropdowntype_serial = filter_input(INPUT_POST, "dropdowntype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
        $dropdown_serial = filter_input(INPUT_POST, "dropdown_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
        $dropdown_value = filter_input(INPUT_POST, "dropdown_value") ?: "";

        $dropdown_value = strtolower($dropdown_value);

        $SQL = "select dropdown_serial
              from view_dropdowns
             where dropdown_serial      != :dropdown_serial
               and dropdown_dropdowntype = :dropdown_dropdowntype
               and lower(dropdown_value) = :dropdown_value";

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

        $statement->bindValue(":dropdown_serial", $dropdown_serial);
        $statement->bindValue(":dropdown_dropdowntype", $dropdowntype_serial);
        $statement->bindValue(":dropdown_value", $dropdown_value);

        $statement->execute();

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

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

        echo json_encode($exists);
    }

    // ==================================
    // Determine if a Dropdowntype exists
    // ==================================

    public function dropdowntypeExists() {

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

        $dropdowntype_name = strtolower($dropdowntype_name);

        $SQL = "select dropdowntype_serial
              from view_dropdowntypes
             where dropdowntype_serial     != :dropdowntype_serial
               and lower(dropdowntype_name) = :dropdowntype_name";

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

        $statement->bindValue(":dropdowntype_serial", $dropdowntype_serial);
        $statement->bindValue(":dropdowntype_name", $dropdowntype_name);

        $statement->execute();

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

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

        echo json_encode($exists);
    }

    // ========================================
    // Determine if a Dropdowntype Title exists
    // ========================================

    public function dropdowntypetitleExists() {

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

        $dropdowntype_title = strtolower($dropdowntype_title);

        $SQL = "select dropdowntype_serial
              from view_dropdowntypes
             where dropdowntype_serial      != :dropdowntype_serial
               and lower(dropdowntype_title) = :dropdowntype_title";

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

        $statement->bindValue(":dropdowntype_serial", $dropdowntype_serial);
        $statement->bindValue(":dropdowntype_title", $dropdowntype_title);

        $statement->execute();

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

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

        echo json_encode($exists);
    }

    // =================================
    // Determine if a Dropdown is Active
    // =================================

    public function dropdownActive() {

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

        $dropdown = $this->getDropdown($dropdown_serial);

        if ($dropdown->count() == 0) {
            $this->logError("Invalid Dropdown ({$dropdown_serial}). " . __METHOD__);
        }

        $table = (string) $dropdown->record->dropdowntype_table;
        $column = (string) $dropdown->record->dropdowntype_column;

        $active = false;

        switch ($table) {

            case "*none":  // No table, never Active.

                break;

            case "*function":  // Requires it's own function to determine if Active. 

                if (method_exists(__CLASS__, $column)) {
                    $active = $this->$column($dropdown_serial);
                }

                break;

            default:  // All others, test the Column in the Table.

                $SQL = "select {$column}
                  from {$table}
                 where {$column} = {$dropdown_serial}";

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

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

                break;
        }

        echo json_encode($active);
    }

    // =====================================
    // Determine if a Dropdowntype is Active
    // =====================================

    public function dropdowntypeActive() {

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

        $SQL = "select dropdown_serial
              from view_dropdowns
             where dropdown_dropdowntype = {$dropdowntype_serial}";

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

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

        echo json_encode($active);
    }

    // ===============
    // Edit a Dropdown
    // ===============

    public function editDropdown() {

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

        switch ($step) {

            case "prompt":

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

                $dropdown = $this->getDropdown($dropdown_serial);

                if ($dropdown->count() == 0) {
                    $this->logError("Invalid Dropdown ({$dropdown_serial}). " . __METHOD__);
                }

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

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

                $this->displayContent($content);

                break;

            case "update":

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

                $dropdown = $this->getDropdown($dropdown_serial);

                if ($dropdown->count() == 0) {
                    $this->logError("Invalid Dropdown ({$dropdown_serial}). " . __METHOD__);
                }

                $SQL = "update dropdowns 
                   set dropdown_value   = :dropdown_value,
                       dropdown_changer = :dropdown_changer,
                       dropdown_changed = :dropdown_changed
                 where dropdown_serial  = :dropdown_serial";

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

                $statement->bindValue(":dropdown_serial", $dropdown_serial);
                $statement->bindValue(":dropdown_value", $dropdown_value);
                $statement->bindValue(":dropdown_changer", $this->current_user_name);
                $statement->bindValue(":dropdown_changed", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ===================
    // Edit a Dropdowntype
    // ===================

    public function editDropdowntype() {

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

        switch ($step) {

            case "prompt":

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

                $dropdowntype = $this->getDropdowntype($dropdowntype_serial);

                if ($dropdowntype->count() == 0) {
                    $this->logError("Invalid Dropdowntype ({$dropdowntype_serial}). " . __METHOD__);
                }

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

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

                $this->displayContent($content);

                break;

            case "update":

                $dropdowntype_serial = filter_input(INPUT_POST, "dropdowntype_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
                $dropdowntype_name = filter_input(INPUT_POST, "dropdowntype_name") ?: "";
                $dropdowntype_title = filter_input(INPUT_POST, "dropdowntype_title") ?: "";
                $dropdowntype_table = filter_input(INPUT_POST, "dropdowntype_table") ?: "";
                $dropdowntype_column = filter_input(INPUT_POST, "dropdowntype_column") ?: "";

                $dropdowntype = $this->getDropdowntype($dropdowntype_serial);

                if ($dropdowntype->count() == 0) {
                    $this->logError("Invalid Dropdowntype ({$dropdowntype_serial}). " . __METHOD__);
                }

                $SQL = "update dropdowntypes 
                   set dropdowntype_name    = :dropdowntype_name,
                       dropdowntype_title   = :dropdowntype_title,
                       dropdowntype_table   = :dropdowntype_table,
                       dropdowntype_column  = :dropdowntype_column,
                       dropdowntype_changer = :dropdowntype_changer,
                       dropdowntype_changed = :dropdowntype_changed
                 where dropdowntype_serial  = :dropdowntype_serial";

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

                $statement->bindValue(":dropdowntype_serial", $dropdowntype_serial);
                $statement->bindValue(":dropdowntype_name", $dropdowntype_name);
                $statement->bindValue(":dropdowntype_title", $dropdowntype_title);
                $statement->bindValue(":dropdowntype_table", $dropdowntype_table);
                $statement->bindValue(":dropdowntype_column", $dropdowntype_column);
                $statement->bindValue(":dropdowntype_changer", $this->current_user_name);
                $statement->bindValue(":dropdowntype_changed", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // =================================
    // Return an Active Dropdowns Object
    // =================================

    public function getActiveDropdowns() {

        $SQL = "select view_dropdowns.*
              from view_dropdowns
             where dropdown_active is true";

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

    // ========================
    // Return a Dropdown Object
    // ========================

    public function getDropdown($dropdown_serial = 0) {

        $SQL = "select view_dropdowns.*
              from view_dropdowns
             where dropdown_serial = {$dropdown_serial}";

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

    // =========================
    // Return a Dropdowns Object
    // =========================

    public function getDropdowns() {

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

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

    // ============================
    // Return a Dropdowntype Object
    // ============================

    public function getDropdowntype($dropdowntype_serial = 0) {

        $SQL = "select view_dropdowntypes.*
              from view_dropdowntypes
             where dropdowntype_serial = {$dropdowntype_serial}";

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

    // =============================
    // Return a Dropdowntypes Object
    // =============================

    public function getDropdowntypes() {

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

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

    // ==================================
    // Return a Dropdowntypes Page Object
    // ==================================

    public function getDropdowntypesPage() {

        // Find Criteria

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

        // Show Per Page

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

        // Record Count

        $connection = $this->connect();

        $SQL = "select count(*) as count
              from view_dropdowntypes
             where (dropdowntype_name   regexp :dropdowntype_name
                or  dropdowntype_title  regexp :dropdowntype_title
                or  dropdowntype_table  regexp :dropdowntype_table
                or  dropdowntype_column regexp :dropdowntype_column)";

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

        $statement->bindValue(":dropdowntype_name", $find_words);
        $statement->bindValue(":dropdowntype_title", $find_words);
        $statement->bindValue(":dropdowntype_table", $find_words);
        $statement->bindValue(":dropdowntype_column", $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_dropdowntypes.*
              from view_dropdowntypes
             where (dropdowntype_name   regexp :dropdowntype_name
                or  dropdowntype_title  regexp :dropdowntype_title
                or  dropdowntype_table  regexp :dropdowntype_table
                or  dropdowntype_column regexp :dropdowntype_column)
             limit {$this->pagination_size}
            offset {$offset}";

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

        $statement->bindValue(":dropdowntype_name", $find_words);
        $statement->bindValue(":dropdowntype_title", $find_words);
        $statement->bindValue(":dropdowntype_table", $find_words);
        $statement->bindValue(":dropdowntype_column", $find_words);

        $statement->execute();

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

        // Insert Pagination Attributes

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

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

        return $dropdowntypes;
    }

    // ===============
    // Setup Dropdowns
    // ===============

    public function setupDropdowns() {

        $dropdowntypes = $this->getDropdowntypes();
        $dropdowns = $this->getDropdowns();

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

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

        $this->displayContent($content);
    }

    // ===================
    // Setup Dropdowntypes
    // ===================

    public function setupDropdowntypes() {

        $dropdowntypes = $this->getDropdowntypesPage();
        $popovers = (new Popovers())->getPopovers();

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

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

        $this->displayContent($content);
    }

    // ======================
    // Update Dropdown Active
    // ======================

    public function updateDropdownActive() {

        $dropdown_serial = filter_input(INPUT_POST, "dropdown_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
        $dropdown_checked = filter_input(INPUT_POST, "dropdown_checked", FILTER_VALIDATE_BOOLEAN) ?: false;

        $SQL = "update dropdowns 
               set dropdown_active  = :dropdown_active,
                   dropdown_changer = :dropdown_changer,
                   dropdown_changed = :dropdown_changed
             where dropdown_serial  = :dropdown_serial";

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

        $statement->bindValue(":dropdown_serial", $dropdown_serial);
        $statement->bindValue(":dropdown_active", $dropdown_checked, PDO::PARAM_BOOL);
        $statement->bindValue(":dropdown_changer", $this->current_user_name);
        $statement->bindValue(":dropdown_changed", $this->getTimestamp());

        $statement->execute();
    }

    // =======================
    // Update Dropdown Default
    // =======================

    public function updateDropdownDefault() {

        $dropdown_serial = filter_input(INPUT_POST, "dropdown_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
        $dropdown_dropdowntype = filter_input(INPUT_POST, "dropdown_dropdowntype", FILTER_SANITIZE_NUMBER_INT) ?: 0;
        $dropdown_checked = filter_input(INPUT_POST, "dropdown_checked") ?: "false";

        // Unset the Default for the Dropdown Type.

        $SQL = "update dropdowns
               set dropdown_default      = false
             where dropdown_dropdowntype = {$dropdown_dropdowntype}";

        $this->executeSQL($SQL);

        // Set the Default for the clicked Dropdown.

        $SQL = "update dropdowns
               set dropdown_default = {$dropdown_checked}
             where dropdown_serial  = {$dropdown_serial}";

        $this->executeSQL($SQL);
    }
}

?>
