<?php

class Cities 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 City
    // ========

    public function addCity() {

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

        switch ($step) {

            case "prompt":

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

                $this->displayContent($content);

                break;

            case "add":

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

                $SQL = "insert into cities
          
                         (  city_name,
                            city_creator,
                            city_created )
                               
                  VALUES ( :city_name,
                           :city_creator,
                           :city_created )";

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

                $statement->bindValue(":city_name", $city_name);
                $statement->bindValue(":city_creator", $this->current_user_name);
                $statement->bindValue(":city_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // =============
    // Delete City
    // =============

    public function deleteCity() {

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

        $city = $this->getCity($city_serial);

        if ($city->count() == 0) {
            $this->logError("Invalid City ({$city_serial}). " . __METHOD__);
        }

        $SQL = "delete from cities
                  where city_serial = {$city_serial}";

        $this->executeSQL($SQL);
    }

    // ============================
    // Determine if a City exists
    // ============================

    public function cityExists() {

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

        $SQL = "select city_serial
                  from view_cities
                 where city_serial      != :city_serial
                   and lower(city_name)  = :city_name";

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

        $statement->bindValue(":city_serial", $city_serial);
        $statement->bindValue(":city_name", strtolower($city_name));

        $statement->execute();

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

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

        echo json_encode($exists);
    }

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

    public function cityActive() {

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

        $active = false;

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

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

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

        echo json_encode($active);
    }

    // =============
    // Edit a City
    // =============

    public function editCity() {

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

        switch ($step) {

            case "prompt":

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

                $city = $this->getCity($city_serial);

                if ($city->count() == 0) {
                    $this->logError("Invalid City ({$city_serial}). " . __METHOD__);
                }

                $constants = $this->getConstants();

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

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

                $this->displayContent($content);

                break;

            case "update":

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

                // Verify the City

                $city = $this->getCity($city_serial);

                if ($city->count() == 0) {
                    $this->logError("Invalid City ({$city_serial}). " . __METHOD__);
                }

                $SQL = "update cities 
                           set city_name    = :city_name,
                               city_creator = :city_creator,
                               city_created = :city_created
                         where city_serial  = :city_serial";

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

                $statement->bindValue(":city_serial", $city_serial);
                $statement->bindValue(":city_name", $city_name);
                $statement->bindValue(":city_creator", $this->current_user_name);
                $statement->bindValue(":city_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ================================
    // Return an Active Cities Object
    // ================================

    public function getActiveCities() {

        $SQL = "select view_cities.*
                  from view_cities
                 where city_active is true";

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

    // =======================
    // Return an City Object
    // =======================

    public function getCity($city_serial = 0) {

        $SQL = "select view_cities.*
                  from view_cities
                 where city_serial = {$city_serial}";

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

    // ========================
    // Return a Cities Object
    // ========================

    public function getCities() {

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

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

    // ========================
    // Return a Cities Object
    // ========================

    public function getCitiesByArea($area) {

        $SQL = "select view_cities.*
                  from view_cities
                 where view_cities.city_area = '{$area}'";

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

    // ========================
    // Return a Cities Object
    // ========================

    public function getCitiesByName($city_name) {

        $SQL = "select view_cities.*
                  from view_cities
                 where view_cities.city_name = '{$city_name}'";

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

    // =============================
    // Return a Cities Page Object
    // =============================

    public function getCitiesPage() {

        // Find Criteria

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

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

        // Record Count

        $connection = $this->connect();

        $SQL = "select count(*) as count
              from view_cities
             where city_name    regexp :city_name";

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

        $statement->bindValue(":city_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_cities.*
              from view_cities
             where city_name    regexp :city_name
          order by city_name
             limit {$this->pagination_size}
            offset {$offset}";

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

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

        $statement->execute();

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

        // Insert Pagination Attributes

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

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

        return $cities;
    }

    // ==============
    // Setup Cities
    // ==============

    public function setupCities() {

        $cities = $this->getCitiesPage();
        $popovers = (new Popovers())->getPopovers();

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

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

        $this->displayContent($content);
    }

    // ======================
    // Return a Cities Object
    // ======================

    public function getSubscriptionCities($subscription_serial) {

        $SQL = "select view_subscriptioncities.*
                  from view_subscriptioncities
                 where view_subscriptioncities.subscriptioncity_subscription = '{$subscription_serial}'";
        
        return $this->getTable("subscriptioncities", $SQL);
    }
}

?>
