<?php

class SICCodes 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 SIC Code
    // ============

    public function addSICCode() {



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

        switch ($step) {

            case "prompt":

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

                $this->displayContent($content);

                break;

            case "add":

                $siccode_code = filter_input(INPUT_POST, "siccode_code") ?: "";
                $siccode_description = filter_input(INPUT_POST, "siccode_description") ?: "";

                $SQL = "insert into siccodes
          
                         (  siccode_code,
                            siccode_description )
                               
                  VALUES ( :siccode_code,
                           :siccode_description )";

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

                $statement->bindValue(":siccode_code", $siccode_code);
                $statement->bindValue(":siccode_description", $siccode_description);

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ===============
    // Delete SIC Code
    // ===============

    public function deleteSICCode() {

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

        $siccode = $this->getSICCode($siccode_serial);

        if ($siccode->count() == 0) {
            $this->logError("Invalid SIC Code ({$siccode_serial}). " . __METHOD__);
        }

        $SQL = "delete from siccodes
                 where siccode_serial = {$siccode_serial}";

        $this->executeSQL($SQL);
    }

    // ============================
    // Determine if a SICCode exists
    // ============================

    public function siccodeExists() {

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

        $SQL = "select siccode_serial
                  from view_siccodes
                 where siccode_serial  != :siccode_serial
                   and siccode_code     = :siccode_code";

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

        $statement->bindValue(":siccode_serial", $siccode_serial);
        $statement->bindValue(":siccode_code", strtolower($siccode_code));

        $statement->execute();

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

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

        echo json_encode($exists);
    }

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

    public function siccodeActive() {

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

        $active = false;

        $SQL = "select workorder_siccode
                  from workorders
                 where workorder_siccode = {$siccode_serial}
                 limit 1";

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

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

        echo json_encode($active);
    }

    // ===============
    // Edit a SIC Code
    // ===============

    public function editSICCode() {

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

        switch ($step) {

            case "prompt":

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

                $siccode = $this->getSICCode($siccode_serial);

                if ($siccode->count() == 0) {
                    $this->logError("Invalid SIC Code ({$siccode_serial}). " . __METHOD__);
                }

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

                $this->displayContent($content);

                break;

            case "update":

                $siccode_serial = filter_input(INPUT_POST, "siccode_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
                $siccode_code = filter_input(INPUT_POST, "siccode_code") ?: "";
                $siccode_description = filter_input(INPUT_POST, "siccode_description") ?: "";

                // Verify the SIC Code

                $siccode = $this->getSICCode($siccode_serial);

                if ($siccode->count() == 0) {
                    $this->logError("Invalid SIC Code ({$siccode_serial}). " . __METHOD__);
                }

                $SQL = "update siccodes 
                           set siccode_code         = :siccode_code,
                               siccode_description  = :siccode_description
                         where siccode_serial       = :siccode_serial";

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

                $statement->bindValue(":siccode_serial", $siccode_serial);
                $statement->bindValue(":siccode_code", $siccode_code);
                $statement->bindValue(":siccode_description", $siccode_description);

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ================================
    // Return an Active SICCodes Object
    // ================================

    public function getActiveSICCodes() {

        $SQL = "select view_siccodes.*
                  from view_siccodes
                 where siccode_description is true";

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

    // =========================
    // Return an SIC Code Object
    // =========================

    public function getSICCode($siccode_serial = 0) {

        $SQL = "select view_siccodes.*
                  from view_siccodes
                 where siccode_serial = {$siccode_serial}";

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

    // =========================
    // Return a SIC Codes Object
    // =========================

    public function getSICCodes() {

        $SQL = "select view_siccodes.*
                  from view_siccodes order by view_siccodes.siccode_description";

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

    // =============================
    // Return a SICCodes Page Object
    // =============================

    public function getSICCodesPage() {

        // Find Criteria

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

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

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

        // Record Count

        $connection = $this->connect();

        $SQL = "select count(*) as count
                  from view_siccodes
                 where siccode_code        regexp :siccode_code
                    or siccode_description regexp :siccode_description";

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

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

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

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

        $statement->execute();

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

        // Insert Pagination Attributes

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

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

        return $siccodes;
    }

    // ===============
    // Setup SIC Codes
    // ===============

    public function setupSICCodes() {

        $siccodes = $this->getSICCodesPage();
        $popovers = (new Popovers())->getPopovers();

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

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

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

?>
