<?php

// =====================
// Support Tickets Class
// =====================

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

    // ====================
    // View Support Tickets
    // ====================

    public function viewSupportTickets() {

        $supporttickets = $this->getSupportTicketsPage();
        $popovers = (new Popovers())->getPopovers();

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

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

        $this->displayContent($content);
    }

    // ======================
    // Support Ticket Summary
    // ======================

    public function viewSupportTicketSummary() {

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

        $supportticket = $this->getSupportTicket($supportticket_serial);

        if ($supportticket->count() == 0) {
            $this->logError("Invalid Support Ticket ({$supportticket_serial}). " . __METHOD__);
        }

        $user_name = $supportticket->record->supportticket_creator;

        $user = (new Users())->getUserByUserName($user_name);

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

//        echo $XML;
//        die();

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

        $this->displayContent($content);
    }

    // ====================================
    // Return a Support Tickets Page Object
    // ====================================

    public function getSupportTicketsPage() {

        // Find Criteria

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

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

        $supporttickets_order_by = filter_input(INPUT_POST, "supporttickets_order_by") ?: "";
        $supporttickets_order_direction = filter_input(INPUT_POST, "supporttickets_order_direction") ?: "";

        if ($supporttickets_order_by === "") {
            $orderby = "supportticket_serial desc";
        } else {
            $orderby = $supporttickets_order_by . " " . $supporttickets_order_direction;
        }

        // Record Count

        $connection = $this->connect();

        $SQL = "select count(*) as count
                  from view_supporttickets
                 where supportticket_creator            regexp :supportticket_creator 
                    or supportticket_catagory_verbose   regexp :supportticket_catagory_verbose 
                    or supportticket_message            regexp :supportticket_message
                    or supportticket_status            regexp :supportticket_status
                    or supportticket_subject            regexp :supportticket_subject";

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

        $statement->bindValue(":supportticket_creator", $find_supportticket);
        $statement->bindValue(":supportticket_catagory_verbose", $find_supportticket);
        $statement->bindValue(":supportticket_message", $find_supportticket);
        $statement->bindValue(":supportticket_status", $find_supportticket);
        $statement->bindValue(":supportticket_subject", $find_supportticket);

        $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_supporttickets.*
                  from view_supporttickets
                 where supportticket_creator            regexp :supportticket_creator 
                    or supportticket_catagory_verbose   regexp :supportticket_catagory_verbose 
                    or supportticket_message            regexp :supportticket_message
                    or supportticket_status             regexp :supportticket_status
                    or supportticket_subject            regexp :supportticket_subject
              order by {$orderby}
                 limit {$this->pagination_size}
                offset {$offset}";

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

        $statement->bindValue(":supportticket_creator", $find_supportticket);
        $statement->bindValue(":supportticket_catagory_verbose", $find_supportticket);
        $statement->bindValue(":supportticket_message", $find_supportticket);
        $statement->bindValue(":supportticket_status", $find_supportticket);
        $statement->bindValue(":supportticket_subject", $find_supportticket);

        $statement->execute();

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

        foreach ($supporttickets as $supportticket) {
            $html_message = trim(strip_tags($supportticket->supportticket_message));
            $supportticket->supportticket_message_raw = $html_message;
        }


        // Insert Pagination Attributes
        $supporttickets->addAttribute("count", $count);
        $supporttickets->addAttribute("start", $start);
        $supporttickets->addAttribute("end", $end);
        $supporttickets->addAttribute("page", $this->pagination_page);

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

        return $supporttickets;
    }

    // ====================
    // Start Support Ticket
    // ====================

    public function startSupportTicket() {

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

        switch ($step) {

            case "prompt":

                $user = (new Users())->getUser($this->current_user_serial);
                $dropdowns = (new Dropdowns())->getDropdowns();

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

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

                break;

            case "send":

                $supportticket_subject = filter_input(INPUT_POST, "supportticket_subject") ?: "";
                $supportticket_category = filter_input(INPUT_POST, "supportticket_category") ?: "";
                $supportticket_category_other = filter_input(INPUT_POST, "supportticket_category_other") ?: "";
                $supportticket_message = filter_input(INPUT_POST, "supportticket_message") ?: "";

                $SQL = "insert into supporttickets
          
                         (  supportticket_subject,
                            supportticket_category,
                            supportticket_category_other,
                            supportticket_message,
                            supportticket_status,
                            supportticket_creator,
                            supportticket_created )
                               
                  VALUES ( :supportticket_subject,
                           :supportticket_category,
                           :supportticket_category_other,
                           :supportticket_message,
                           :supportticket_status,
                           :supportticket_creator,
                           :supportticket_created )";

                $connection = $this->connect();

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

                $statement->bindValue(":supportticket_subject", $supportticket_subject);
                $statement->bindValue(":supportticket_category", $supportticket_category);
                $statement->bindValue(":supportticket_category_other", $supportticket_category_other);
                $statement->bindValue(":supportticket_message", $supportticket_message);
                $statement->bindValue(":supportticket_status", 5);  // Dropdown value of the dropdown type 2 for ticket statuses
                $statement->bindValue(":supportticket_creator", $this->current_user_name);
                $statement->bindValue(":supportticket_created", $this->getTimestamp());

                $statement->execute();

                $supportticket_serial = $connection->lastInsertId();

                // Send Email to Support Center
                $this->sendNotifications($supportticket_serial);

                $this->displayNotice("Support ticket submitted successfully. The Support team will respond as soon as possible.");

                break;

            default:

                $this->displayHome();
        }
    }

    // =============================================
    // Send Support Center Ticket Notification Email
    // =============================================

    public function sendNotifications($supportticket_serial = 0) {

        if (empty($supportticket_serial)) {
            return;
        }

        $settings = $this->getSettings();

        $Environment = (string) $settings->Environment;
        $SupportEmail = (string) $settings->SupportEmail;

        if ($Environment == "Development") {
            return;
        }

        $supportticket = $this->getSupportTicket($supportticket_serial);

        $to = $SupportEmail;
        $subject = "Georgia Housing Report - Support Ticket Submittal";
        $message = $this->applyXSL($supportticket, $this->getXSL("emailSupportTicket"));

        // Send the Email
        (new Email())->sendEmail($to, $subject, $message);
    }

    // ===============================
    // Return an Support Ticket Object
    // ===============================

    public function getSupportTicket($supportticket_serial = 0) {

        $SQL = "select view_supporttickets.*
                  from view_supporttickets
                 where view_supporttickets.supportticket_serial = {$supportticket_serial}";

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

?>
