<?php

class ProjectTypes 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 ProjectType
    // ========

    public function addProjectType() {

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

        switch ($step) {

            case "prompt":

                $constants = $this->getConstants();
                $content = $this->applyXSL($constants, $this->getXSL("addProjectType"));

                $this->displayContent($content);

                break;

            case "add":

                $projecttype_name = filter_input(INPUT_POST, "projecttype_name") ?: "";

                $SQL = "insert into projecttypes
          
                         (  projecttype_name,
                            projecttype_creator,
                            projecttype_created )
                               
                  VALUES ( :projecttype_name,
                           :projecttype_creator,
                           :projecttype_created )";

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

                $statement->bindValue(":projecttype_name", $projecttype_name);
                $statement->bindValue(":projecttype_creator", $this->current_user_name);
                $statement->bindValue(":projecttype_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // =============
    // Delete Project Type
    // =============

    public function deleteProjectType() {

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

        $projecttype = $this->getProjectType($projecttype_serial);

        if ($projecttype->count() == 0) {
            $this->logError("Invalid ProjectType ({$projecttype_serial}). " . __METHOD__);
        }

        $SQL = "delete from projecttypes
                  where projecttype_serial = {$projecttype_serial}";

        $this->executeSQL($SQL);
    }

    // ============================
    // Determine if a ProjectType exists
    // ============================

    public function projecttypeExists() {

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

        $SQL = "select projecttype_serial
                  from view_projecttypes
                 where projecttype_serial      != :projecttype_serial
                   and lower(projecttype_name)  = :projecttype_name";

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

        $statement->bindValue(":projecttype_serial", $projecttype_serial);
        $statement->bindValue(":projecttype_name", strtolower($projecttype_name));

        $statement->execute();

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

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

        echo json_encode($exists);
    }

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

    public function projecttypeActive() {

        $rdi_projecttype = filter_input(INPUT_POST, "rdi_projecttype") ?: "";

        $active = false;

        $SQL = "select rdi_projecttype
                  from rdis
                 where rdi_projecttype = {$rdi_projecttype}
                 limit 1";

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

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

        echo json_encode($active);
    }

    // =============
    // Edit a ProjectType
    // =============

    public function editProjectType() {

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

        switch ($step) {

            case "prompt":

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

                $projecttype = $this->getProjectType($projecttype_serial);

                if ($projecttype->count() == 0) {
                    $this->logError("Invalid ProjectType ({$projecttype_serial}). " . __METHOD__);
                }

                $constants = $this->getConstants();

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

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

                $this->displayContent($content);

                break;

            case "update":

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

                // Verify the ProjectType

                $projecttype = $this->getProjectType($projecttype_serial);

                if ($projecttype->count() == 0) {
                    $this->logError("Invalid ProjectType ({$projecttype_serial}). " . __METHOD__);
                }

                $SQL = "update projecttypes 
                           set projecttype_name    = :projecttype_name,
                               projecttype_creator = :projecttype_creator,
                               projecttype_created = :projecttype_created
                         where projecttype_serial  = :projecttype_serial";

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

                $statement->bindValue(":projecttype_serial", $projecttype_serial);
                $statement->bindValue(":projecttype_name", $projecttype_name);
                $statement->bindValue(":projecttype_creator", $this->current_user_name);
                $statement->bindValue(":projecttype_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ================================
    // Return an Active ProjectTypes Object
    // ================================

    public function getActiveProjectTypes() {

        $SQL = "select view_projecttypes.*
                  from view_projecttypes
                 where projecttype_active is true";

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

    // =======================
    // Return an ProjectType Object
    // =======================

    public function getProjectType($projecttype_serial = 0) {

        $SQL = "select view_projecttypes.*
                  from view_projecttypes
                 where projecttype_serial = {$projecttype_serial}";

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

    // ========================
    // Return a ProjectTypes Object
    // ========================

    public function getProjectTypes() {

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

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

    // ========================
    // Return a ProjectTypes Object
    // ========================

    public function getProjectTypesByArea($area) {

        $SQL = "select view_projecttypes.*
                  from view_projecttypes
                 where view_projecttypes.projecttype_area = '{$area}'";

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

    // ========================
    // Return a ProjectTypes Object
    // ========================

    public function getProjectTypesByName($projecttype_name) {

        $SQL = "select view_projecttypes.*
                  from view_projecttypes
                 where view_projecttypes.projecttype_name = '{$projecttype_name}'";

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

    // =============================
    // Return a ProjectTypes Page Object
    // =============================

    public function getProjectTypesPage() {

        // Find Criteria

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

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

        // Record Count

        $connection = $this->connect();

        $SQL = "select count(*) as count
              from view_projecttypes
             where projecttype_name    regexp :projecttype_name";

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

        $statement->bindValue(":projecttype_name", $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_projecttypes.*
              from view_projecttypes
             where projecttype_name    regexp :projecttype_name
          order by projecttype_name
             limit {$this->pagination_size}
            offset {$offset}";

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

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

        $statement->execute();

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

        // Insert Pagination Attributes

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

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

        return $projecttypes;
    }

    // ==============
    // Setup ProjectTypes
    // ==============

    public function setupProjectTypes() {

        $projecttypes = $this->getProjectTypesPage();
        $popovers = (new Popovers())->getPopovers();

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

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

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

?>
