<?php

// ==============
// Popovers Class
// ==============

class Popovers 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 Popover
    // ===========

    public function addPopover() {

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

        switch ($step) {

            case "prompt":

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

                $this->displayContent($content);

                break;

            case "add":

                $popover_name = filter_input(INPUT_POST, "popover_name") ?: "";
                $popover_title = filter_input(INPUT_POST, "popover_title") ?: "";
                $popover_placeholder = filter_input(INPUT_POST, "popover_placeholder") ?: "";
                $popover_text = filter_input(INPUT_POST, "popover_text") ?: "";

                $SQL = "insert into popovers
          
                         (  popover_name,
                            popover_title,
                            popover_placeholder,
                            popover_text,
                            popover_creator,
                            popover_created )
                               
                  VALUES ( :popover_name,
                           :popover_title,
                           :popover_placeholder,
                           :popover_text,
                           :popover_creator,
                           :popover_created)";

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

                $statement->bindValue(":popover_name", $popover_name);
                $statement->bindValue(":popover_title", $popover_title);
                $statement->bindValue(":popover_placeholder", $popover_placeholder);
                $statement->bindValue(":popover_text", $popover_text);
                $statement->bindValue(":popover_creator", $this->current_user_name);
                $statement->bindValue(":popover_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ==============
    // Delete Popover
    // ==============

    public function deletePopover() {

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

        $popover = $this->getPopover($popover_serial);

        if ($popover->count() == 0) {
            $this->logError("Invalid Popover ({$popover_serial}). " . __METHOD__);
        }

        $SQL = "delete from popovers
                  where popover_serial = {$popover_serial}";

        $this->executeSQL($SQL);
    }

    // ============
    // Edit Popover
    // ============

    public function editPopover() {

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

        switch ($step) {

            case "prompt":

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

                $popover = $this->getPopover($popover_serial);

                if ($popover->count() == 0) {
                    $this->logError("Invalid Popover ({$popover_serial}): " . __METHOD__);
                }

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

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

                $this->displayContent($content);

                break;

            case "update":

                $popover_serial = filter_input(INPUT_POST, "popover_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
                $popover_name = filter_input(INPUT_POST, "popover_name") ?: "";
                $popover_title = filter_input(INPUT_POST, "popover_title") ?: "";
                $popover_placeholder = filter_input(INPUT_POST, "popover_placeholder") ?: "";
                $popover_text = filter_input(INPUT_POST, "popover_text") ?: "";

                $popover = $this->getPopover($popover_serial);

                if ($popover->count() == 0) {
                    $this->logError("Invalid Popover ({$popover_serial}): " . __METHOD__);
                }

                $SQL = "update popovers
                   set popover_name        = :popover_name,
                       popover_title       = :popover_title,
                       popover_placeholder = :popover_placeholder,
                       popover_text        = :popover_text,
                       popover_changer     = :popover_changer,
                       popover_changed     = :popover_changed
                 where popover_serial      = :popover_serial";

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

                $statement->bindValue(":popover_serial", $popover_serial);
                $statement->bindValue(":popover_name", $popover_name);
                $statement->bindValue(":popover_title", $popover_title);
                $statement->bindValue(":popover_placeholder", $popover_placeholder);
                $statement->bindValue(":popover_text", $popover_text);
                $statement->bindValue(":popover_changer", $this->current_user_name);
                $statement->bindValue(":popover_changed", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // =======================
    // Return a Popover Object
    // =======================

    public function getPopover($popover_serial = 0) {

        $SQL = "select view_popovers.*
              from view_popovers
             where popover_serial = {$popover_serial}";

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

    // =======================
    // Return a Popover Object
    // =======================

    public function getPopoverByName($popover_name = "") {

        $SQL = "select view_popovers.*
              from view_popovers
             where popover_name = '{$popover_name}'";

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

    // ========================
    // Return a Popovers Object
    // ========================

    public function getPopovers() {

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

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

    // =============================
    // Return a Popovers Page Object
    // =============================

    public function getPopoversPage() {

        // Find Criteria

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

        // Show Per Page

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

        // Record Count

        $connection = $this->connect();

        $SQL = "select count(*) as count
              from view_popovers
             where popover_name  regexp :popover_name
                or popover_title regexp :popover_title";

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

        $statement->bindValue(":popover_name", $find_words);
        $statement->bindValue(":popover_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_popovers.*
              from view_popovers
             where popover_name  regexp :popover_name
                or popover_title regexp :popover_title
             limit {$this->pagination_size}
            offset {$offset}";

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

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

        $statement->execute();

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

        // Insert Pagination Attributes

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

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

        return $popovers;
    }

    // =============================
    // Determine if a Popover exists
    // =============================

    public function popoverExists() {

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

        $popover_name = strtolower($popover_name);

        $SQL = "select popover_serial
              from view_popovers
             where popover_serial      != :popover_serial
               and lower(popover_name)  = :popover_name";

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

        $statement->bindValue(":popover_serial", $popover_serial);
        $statement->bindValue(":popover_name", $popover_name);

        $statement->execute();

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

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

        echo json_encode($exists);
    }

    // ==============
    // Setup Popovers
    // ==============

    public function setupPopovers() {

        $popovers = $this->getPopoversPage();
        $XML = $this->mergeXML($popovers, "<XML/>");
        $content = $this->applyXSL($XML, $this->getXSL("setupPopovers"));

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

?>
