<?php

class Counties 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 County
    // ==========

    public function addCounty() {

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

        switch ($step) {

            case "prompt":

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

                $this->displayContent($content);

                break;

            case "add":

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

                $SQL = "insert into counties
          
                         (  county_name,
                            county_area,
                            county_creator,
                            county_created )
                               
                  VALUES ( :county_name,
                           :county_area,
                           :county_creator,
                           :county_created )";

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

                $statement->bindValue(":county_name", $county_name);
                $statement->bindValue(":county_area", $county_name);
                $statement->bindValue(":county_creator", $this->current_user_name);
                $statement->bindValue(":county_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // =============
    // Delete County
    // =============

    public function deleteCounty() {

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

        $county = $this->getCounty($county_serial);

        if ($county->count() == 0) {
            $this->logError("Invalid County ({$county_serial}). " . __METHOD__);
        }

        $SQL = "delete from counties
                  where county_serial = {$county_serial}";

        $this->executeSQL($SQL);
    }

    // ============================
    // Determine if a County exists
    // ============================

    public function countyExists() {

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

        $SQL = "select county_serial
                  from view_counties
                 where county_serial      != :county_serial
                   and lower(county_name)  = :county_name";

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

        $statement->bindValue(":county_serial", $county_serial);
        $statement->bindValue(":county_name", strtolower($county_name));

        $statement->execute();

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

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

        echo json_encode($exists);
    }

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

    public function countyActive() {

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

        $active = false;

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

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

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

        echo json_encode($active);
    }

    // =============
    // Edit a County
    // =============

    public function editCounty() {

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

        switch ($step) {

            case "prompt":

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

                $county = $this->getCounty($county_serial);

                if ($county->count() == 0) {
                    $this->logError("Invalid County ({$county_serial}). " . __METHOD__);
                }

                $constants = $this->getConstants();

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

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

                $this->displayContent($content);

                break;

            case "update":

                $county_serial = filter_input(INPUT_POST, "county_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
                $county_name = filter_input(INPUT_POST, "county_name") ?: "";
                $county_area = filter_input(INPUT_POST, "county_area") ?: "";

                // Verify the County

                $county = $this->getCounty($county_serial);

                if ($county->count() == 0) {
                    $this->logError("Invalid County ({$county_serial}). " . __METHOD__);
                }

                $SQL = "update counties 
                           set county_name    = :county_name,
                               county_area    = :county_area,
                               county_creator = :county_creator,
                               county_created = :county_created
                         where county_serial  = :county_serial";

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

                $statement->bindValue(":county_serial", $county_serial);
                $statement->bindValue(":county_name", $county_name);
                $statement->bindValue(":county_area", $county_area);
                $statement->bindValue(":county_creator", $this->current_user_name);
                $statement->bindValue(":county_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ================================
    // Return an Active Counties Object
    // ================================

    public function getActiveCounties() {

        $SQL = "select view_counties.*
                  from view_counties
                 where county_active is true";

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

    // =======================
    // Return an County Object
    // =======================

    public function getCounty($county_serial = 0) {

        $SQL = "select view_counties.*
                  from view_counties
                 where county_serial = {$county_serial}";
        
        return $this->getTable("counties", $SQL);
    }

    // ========================
    // Return a Counties Object
    // ========================

    public function getCounties() {

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

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

    // ========================
    // Return a Counties Object
    // ========================

    public function getCountiesByArea($area) {

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

        if ($area != "All") {
            $SQL .= " where view_counties.county_area = '{$area}'";
        }

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

    // ========================
    // Return a Counties Object
    // ========================

    public function getCountiesByName($county_name) {

        $SQL = "select view_counties.*
                  from view_counties
                 where view_counties.county_name = '{$county_name}'";

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

    // =============================
    // Return a Counties Page Object
    // =============================

    public function getCountiesPage() {

        // Find Criteria

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

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

        // Record Count

        $connection = $this->connect();

        $SQL = "select count(*) as count
              from view_counties
             where county_name    regexp :county_name";

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

        $statement->bindValue(":county_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_counties.*
              from view_counties
             where county_name    regexp :county_name
          order by county_name
             limit {$this->pagination_size}
            offset {$offset}";

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

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

        $statement->execute();

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

        // Insert Pagination Attributes

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

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

        return $counties;
    }

    // ==============
    // Setup Counties
    // ==============

    public function setupCounties() {

        $counties = $this->getCountiesPage();
        $popovers = (new Popovers())->getPopovers();

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

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

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

?>
