<?php

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

    // =========================
    // Go To Subscription Driver
    // =========================

    public function goToSubscription() {

        $subscription_serial = (integer) filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
        $usersubscription_serial = (integer) filter_input(INPUT_POST, "usersubscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;

        $subscription = $this->getSubscription($subscription_serial);

        if ($subscription->count() === 0) {
            $this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
        }

        switch ($subscription_serial) {

            case 1:
            case 2:
            case 3:
            case 4:

                $_SESSION['subscription_serial'] = $subscription_serial;
                $_SESSION['usersubscription_serial'] = $usersubscription_serial;

                (new PermitFacts())->searchPermitFacts();

                break;

            case 5:

                $_SESSION['subscription_serial'] = $subscription_serial;
                $_SESSION['usersubscription_serial'] = $usersubscription_serial;

                (new PlanningAndZoningFacts())->searchPlanningAndZoningFacts();

                break;

            case 12:

                $_SESSION['subscription_serial'] = $subscription_serial;
                $_SESSION['usersubscription_serial'] = $usersubscription_serial;

                (new PlanningAndZoningFacts())->planningAndZoningFactsBasic();

                break;

            case 7:
            case 10:

                $_SESSION['subscription_serial'] = $subscription_serial;
                $_SESSION['usersubscription_serial'] = $usersubscription_serial;

                (new BusinessFacts())->searchBusinessFacts();

                break;
            case 11:

                $_SESSION['subscription_serial'] = $subscription_serial;
                $_SESSION['usersubscription_serial'] = $usersubscription_serial;

                (new BusinessFacts())->businessFactsBasic();

                break;
        }
    }

    // ===================
    // Setup Subscriptions
    // ===================

    public function setupSubscriptions() {

        $subscriptions = $this->getSubscriptionsPage();
        $popovers = (new Popovers())->getPopovers();

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

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

        $this->displayContent($content);
    }

    // ====================
    // Subscription Summary
    // ====================

    public function subscriptionSummary() {

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

        $subscription = $this->getSubscription($subscription_serial);

        if ($subscription->count() == 0) {
            $this->logError("Invalid Subscription ({$subscription_serial}). " . __METHOD__);
        }

        $counties = $this->getSubscriptionCountiesByMarket($subscription->record->subscription_serial);
        $cities = $this->getSubscriptionCitiesByMarket($subscription->record->subscription_serial);

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

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

    // ===================
    // Users Subscriptions
    // ===================

    public function usersSubscriptions() {

        $subscriptions = $this->getUsersActiveSubscriptions($this->current_user_serial);
        $alerts = (new Alerts())->getActiveAlerts();
        $popovers = (new Popovers())->getPopovers();

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

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

        $this->displayContent($content);
    }

    // ================
    // Add Subscription
    // ================

    public function addSubscription() {

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

        switch ($step) {

            case "prompt":

                $dropdowns = (new Dropdowns())->getDropdowns();

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

                $this->displayContent($content);

                break;

            case "add":

                $subscription_title = filter_input(INPUT_POST, "subscription_title") ?: "";
                $subscription_service_level = filter_input(INPUT_POST, "subscription_service_level", FILTER_SANITIZE_NUMBER_INT) ?: "";
                $subscription_market = filter_input(INPUT_POST, "subscription_market", FILTER_SANITIZE_NUMBER_INT) ?: 0;

                $SQL = "insert into subscriptions
          
                         (  subscription_title,
                            subscription_service_level,
                            subscription_market,
                            subscription_creator,
                            subscription_created )
                               
                  VALUES ( :subscription_title,
                           :subscription_service_level,
                           :subscription_market,
                           :subscription_creator,
                           :subscription_created )";

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

                $statement->bindValue(":subscription_title", $subscription_title);
                $statement->bindValue(":subscription_service_level", $subscription_service_level);
                $statement->bindValue(":subscription_market", $subscription_market);
                $statement->bindValue(":subscription_creator", $this->current_user_name);
                $statement->bindValue(":subscription_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // =================
    // Edit Subscription
    // =================

    public function editSubscription() {

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

        switch ($step) {

            case "prompt":

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

                $subscription = $this->getSubscription($subscription_serial);

                if ($subscription->count() === 0) {
                    $this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
                }

                $dropdowns = (new Dropdowns())->getDropdowns();

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

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

                $this->displayContent($content);

                break;

            case "update":

                $subscription_serial = filter_input(INPUT_POST, "subscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
                $subscription_title = filter_input(INPUT_POST, "subscription_title") ?: "";
                $subscription_service_level = filter_input(INPUT_POST, "subscription_service_level", FILTER_SANITIZE_NUMBER_INT) ?: 0;
                $subscription_market = filter_input(INPUT_POST, "subscription_market", FILTER_SANITIZE_NUMBER_INT) ?: 0;

                $subscriptions = $this->getSubscription($subscription_serial);

                if ($subscriptions->count() == 0) {
                    $this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
                }

                // Update the Subscription

                $SQL = "update subscriptions 
                           set subscription_title         = :subscription_title,
                               subscription_service_level = :subscription_service_level,
                               subscription_market        = :subscription_market
                         where subscription_serial        = :subscription_serial";

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

                $statement->bindValue(":subscription_serial", $subscription_serial);
                $statement->bindValue(":subscription_title", $subscription_title);
                $statement->bindValue(":subscription_service_level", $subscription_service_level);
                $statement->bindValue(":subscription_market", $subscription_market);

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // ===================
    // Delete Subscription
    // ===================

    public function deleteSubscription() {

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

        $subscription = $this->getSubscription($subscription_serial);

        if ($subscription->count() == 0) {
            $this->logError("Invalid Subscription ({$subscription_serial}). " . __METHOD__);
        }

        $SQL = "delete from subscriptions
                 where subscription_serial = {$subscription_serial}";

        $this->executeSQL($SQL);
    }

    // ========================
    // Add Subscription to User
    // ========================

    public function addSubscriptionToUser() {

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

        switch ($step) {

            case "prompt":

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

                $user = (new Users())->getUser($user_serial);
                $usersubscriptions = $this->getUsersActiveSubscriptions($user_serial);
                $subscriptions = $this->getSubscriptions();

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

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

                $this->displayContent($content);

                break;

            case "add":

                $user_serial = filter_input(INPUT_POST, "user_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
                $subscription_serials = filter_input(INPUT_POST, "subscriptions", FILTER_SANITIZE_NUMBER_INT, FILTER_REQUIRE_ARRAY) ?: array();
                $subscription_start_dates = filter_input(INPUT_POST, "subscription_start_date", FILTER_DEFAULT, FILTER_REQUIRE_ARRAY) ?: array();
                $subscription_end_dates = filter_input(INPUT_POST, "subscription_end_date", FILTER_DEFAULT, FILTER_REQUIRE_ARRAY) ?: array();
                $subscriptions = array();

                foreach ($subscription_serials as $index => $subscription_serial) {

                    $subscriptions[] = array(
                        "usersubscription_subscription" => $subscription_serial,
                        "usersubscription_start_date" => date("Y-m-d", strtotime($subscription_start_dates[$index] ?? "")),
                        "usersubscription_end_date" => date("Y-m-d", strtotime($subscription_end_dates[$index] ?? ""))
                    );
                }

                $SQL = "insert into usersubscriptions
                    
                         (  usersubscription_user,
                            usersubscription_subscription,
                            usersubscription_start_date,
                            usersubscription_end_date,
                            usersubscription_creator,
                            usersubscription_created )
                               
                  VALUES ( :usersubscription_user,
                           :usersubscription_subscription,
                           :usersubscription_start_date,
                           :usersubscription_end_date,
                           :usersubscription_creator,
                           :usersubscription_created )";

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

                $statement->bindValue(":usersubscription_user", $user_serial);
                $statement->bindValue(":usersubscription_creator", $this->current_user_name);
                $statement->bindValue(":usersubscription_created", $this->getTimestamp());

                foreach ($subscriptions as $subscription) {

                    $subscription_serial = $subscription['usersubscription_subscription'];
                    $start_date = $subscription['usersubscription_start_date'];
                    $end_date = $subscription['usersubscription_end_date'];

                    $statement->bindValue(":usersubscription_subscription", $subscription_serial);
                    $statement->bindValue(":usersubscription_start_date", $start_date);
                    $statement->bindValue(":usersubscription_end_date", $end_date);

                    $statement->execute();
                }

                break;

            default:

                $this->displayHome();
        }
    }

    // ==========================
    // Add County To Subscription
    // ==========================

    public function addCountyToSubscription() {

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

        switch ($step) {

            case "prompt":

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

                $subscription = $this->getSubscription($subscription_serial);

                if ($subscription->count() === 0) {
                    $this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
                }

                $counties = (new Counties())->getCounties();

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

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

                break;

            case "add":

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

                $SQL = "insert into subscriptioncounties
                    
                         ( subscriptioncounty_subscription,
                           subscriptioncounty_county,
                           subscriptioncounty_creator,
                           subscriptioncounty_created )
                               
                  VALUES ( :subscriptioncounty_subscription,
                           :subscriptioncounty_county,
                           :subscriptioncounty_creator,
                           :subscriptioncounty_created )";

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

                $statement->bindValue(":subscriptioncounty_subscription", $subscription_serial);
                $statement->bindValue(":subscriptioncounty_county", $county_serial);
                $statement->bindValue(":subscriptioncounty_creator", $this->current_user_name);
                $statement->bindValue(":subscriptioncounty_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

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

    public function editSubscriptionCounty() {

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

        switch ($step) {

            case "prompt":

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

                $subscriptioncounty = $this->getSubscriptionCounty($subscriptioncounty_serial);

                if ($subscriptioncounty->count() === 0) {
                    $this->logError("Invalid Subscription County ({$subscriptioncounty_serial}): " . __METHOD__);
                }

                $counties = (new Counties())->getCounties();

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

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

                break;

            case "update":

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

                $SQL = "update subscriptioncounties
                           set subscriptioncounty_county  = :subscriptioncounty_county,
                               subscriptioncounty_changer = :subscriptioncounty_changer,
                               subscriptioncounty_changed = :subscriptioncounty_changed
                         where subscriptioncounty_serial  = :subscriptioncounty_serial";

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

                $statement->bindValue(":subscriptioncounty_serial", $subscriptioncounty_serial);
                $statement->bindValue(":subscriptioncounty_county", $county_serial);
                $statement->bindValue(":subscriptioncounty_changer", $this->current_user_name);
                $statement->bindValue(":subscriptioncounty_changed", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

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

    public function deleteSubscriptionCounty() {

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

        $subscriptioncounty = $this->getSubscriptionCounty($subscriptioncounty_serial);

        if ($subscriptioncounty->count() == 0) {
            $this->logError("Invalid Subscription County ({$subscriptioncounty_serial}). " . __METHOD__);
        }

        $SQL = "delete from subscriptioncounties where subscriptioncounty_serial = {$subscriptioncounty_serial}";

        $this->executeSQL($SQL);
    }

    // ===================================
    // Return a Subscription County Object
    // ===================================

    public function getSubscriptionCounty($subscriptioncounty_serial = 0) {

        $SQL = "select view_subscriptioncounties.*
                  from view_subscriptioncounties
                 where subscriptioncounty_serial = {$subscriptioncounty_serial}";

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

    // ========================
    // Add City To Subscription
    // ========================

    public function addCityToSubscription() {

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

        switch ($step) {

            case "prompt":

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

                $subscription = $this->getSubscription($subscription_serial);

                if ($subscription->count() === 0) {
                    $this->logError("Invalid Subscription ({$subscription_serial}): " . __METHOD__);
                }

                $cities = (new Cities())->getCities();

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

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

                break;

            case "add":

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

                $SQL = "insert into subscriptioncities
                    
                         ( subscriptioncity_subscription,
                           subscriptioncity_city,
                           subscriptioncity_creator,
                           subscriptioncity_created )
                               
                  VALUES ( :subscriptioncity_subscription,
                           :subscriptioncity_city,
                           :subscriptioncity_creator,
                           :subscriptioncity_created )";

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

                $statement->bindValue(":subscriptioncity_subscription", $subscription_serial);
                $statement->bindValue(":subscriptioncity_city", $city_serial);
                $statement->bindValue(":subscriptioncity_creator", $this->current_user_name);
                $statement->bindValue(":subscriptioncity_created", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

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

    public function editSubscriptionCity() {

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

        switch ($step) {

            case "prompt":

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

                $subscriptioncity = $this->getSubscriptionCity($subscriptioncity_serial);

                if ($subscriptioncity->count() === 0) {
                    $this->logError("Invalid Subscription City ({$subscriptioncity_serial}): " . __METHOD__);
                }

                $cities = (new Cities())->getCities();

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

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

                break;

            case "update":

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

                $SQL = "update subscriptioncities
                           set subscriptioncity_city  = :subscriptioncity_city,
                               subscriptioncity_changer = :subscriptioncity_changer,
                               subscriptioncity_changed = :subscriptioncity_changed
                         where subscriptioncity_serial  = :subscriptioncity_serial";

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

                $statement->bindValue(":subscriptioncity_serial", $subscriptioncity_serial);
                $statement->bindValue(":subscriptioncity_city", $city_serial);
                $statement->bindValue(":subscriptioncity_changer", $this->current_user_name);
                $statement->bindValue(":subscriptioncity_changed", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

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

    public function deleteSubscriptionCity() {

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

        $subscriptioncity = $this->getSubscriptionCity($subscriptioncity_serial);

        if ($subscriptioncity->count() == 0) {
            $this->logError("Invalid Subscription City ({$subscriptioncity_serial}). " . __METHOD__);
        }

        $SQL = "delete from subscriptioncities where subscriptioncity_serial = {$subscriptioncity_serial}";

        $this->executeSQL($SQL);
    }

    // ===================================
    // Return a Subscription City Object
    // ===================================

    public function getSubscriptionCity($subscriptioncity_serial = 0) {

        $SQL = "select view_subscriptioncities.*
                  from view_subscriptioncities
                 where subscriptioncity_serial = {$subscriptioncity_serial}";

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

    // =========================
    // Edit a Users Subscription
    // =========================

    public function editUsersSubscription() {

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

        switch ($step) {

            case "prompt":

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

                $user = (new Users())->getUser($user_serial);
                $usersubscription = $this->getUsersSubscription($usersubscription_serial);
                $subscriptions = $this->getSubscriptionsPage();

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

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

                $this->displayContent($content);

                break;

            case "update":

                $usersubscription_serial = filter_input(INPUT_POST, "usersubscription_serial", FILTER_SANITIZE_NUMBER_INT) ?: 0;
                $subscription_start_date = filter_input(INPUT_POST, "subscription_start_date") ?: "";
                $subscription_end_date = filter_input(INPUT_POST, "subscription_end_date") ?: "";

                $subscription_start_date = date("Y-m-d", strtotime($subscription_start_date));
                $subscription_end_date = date("Y-m-d", strtotime($subscription_end_date));

                $SQL = "update usersubscriptions
                           set usersubscription_start_date = :usersubscription_start_date,
                               usersubscription_end_date   = :usersubscription_end_date,
                               usersubscription_changer    = :usersubscription_changer,
                               usersubscription_changed    = :usersubscription_changed
                         where usersubscription_serial     = :usersubscription_serial";

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

                $statement->bindValue(":usersubscription_start_date", $subscription_start_date);
                $statement->bindValue(":usersubscription_end_date", $subscription_end_date);
                $statement->bindValue(":usersubscription_serial", $usersubscription_serial);
                $statement->bindValue(":usersubscription_changer", $this->current_user_name);
                $statement->bindValue(":usersubscription_changed", $this->getTimestamp());

                $statement->execute();

                break;

            default:

                $this->displayHome();
        }
    }

    // =========================
    // Delete Users Subscription
    // =========================

    public function deleteUsersSubscription() {

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

        $subscription = $this->getUsersSubscription($usersubscription_serial);

        if ($subscription->count() == 0) {
            $this->logError("Invalid Subscription ({$usersubscription_serial}). " . __METHOD__);
        }

        $SQL = "delete from usersubscriptions
                 where usersubscription_serial = {$usersubscription_serial}";

        $this->executeSQL($SQL);
    }

    // ============================
    // Return a Subscription Object
    // ============================

    public function getSubscription($subscription_serial = 0) {

        $SQL = "select view_subscriptions.*
                  from view_subscriptions
                 where subscription_serial = {$subscription_serial}";

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

    // ============================
    // Return a Subscription Object
    // ============================

    public function getSubscriptions() {

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

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

    // ==================================
    // Return a Subscriptions Page Object
    // ==================================

    public function getSubscriptionsPage() {

        // Find Criteria

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

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

        // Record Count

        $connection = $this->connect();

        $SQL = "select count(*) as count
                  from view_subscriptions
                 where subscription_title          regexp :subscription_title
                    or subscription_service_level  regexp :subscription_service_level
                    or subscription_market         regexp :subscription_market";

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

        $statement->bindValue(":subscription_title", $find_words);
        $statement->bindValue(":subscription_service_level", $find_words);
        $statement->bindValue(":subscription_market", $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_subscriptions.*
                  from view_subscriptions
                 where subscription_title          regexp :subscription_title
                    or subscription_service_level  regexp :subscription_service_level
                    or subscription_market         regexp :subscription_market
              order by subscription_title
                 limit {$this->pagination_size}
                offset {$offset}";

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

        $statement->bindValue(":subscription_title", $find_words);
        $statement->bindValue(":subscription_service_level", $find_words);
        $statement->bindValue(":subscription_market", $find_words);

        $statement->execute();

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

        // Insert Pagination Attributes

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

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

        return $subscriptions;
    }

    // ============================
    // Return a Users Subscriptions
    // ============================

    public function getUsersActiveSubscriptions($user_serial) {

        $SQL = "select view_usersubscriptions.*
                  from view_usersubscriptions
                 where usersubscription_user = {$user_serial}
              order by view_usersubscriptions.subscription_full_title";

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

    // ===========================
    // Return a Users Subscription
    // ===========================

    public function getUsersSubscription($usersubscription_serial) {

        $SQL = "select view_usersubscriptions.*
                  from view_usersubscriptions
                 where usersubscription_serial = {$usersubscription_serial}";

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

    // ==================================
    // Determine if a Subscription exists
    // ==================================

    public function subscriptionExists() {

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

        $SQL = "select subscription_serial
                  from view_subscriptions
                 where subscription_serial      != :subscription_serial
                   and lower(subscription_title)  = :subscription_title";

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

        $statement->bindValue(":subscription_serial", $subscription_serial);
        $statement->bindValue(":subscription_title", strtolower($subscription_title));

        $statement->execute();

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

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

        echo json_encode($exists);
    }

    // ========================================
    // Return a Subscriptions Assigned Counties
    // ========================================

    public function getSubscriptionCountiesByMarket($subscription_serial) {

        $SQL = "select view_subscriptioncounties.*
                  from view_subscriptioncounties
                 where subscriptioncounty_subscription = {$subscription_serial}";

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

    // ======================================
    // Return a Subscriptions Assigned Cities
    // ======================================

    public function getSubscriptionCitiesByMarket($subscription_serial) {

        $SQL = "select view_subscriptioncities.*
                  from view_subscriptioncities
                 where subscriptioncity_subscription = {$subscription_serial}";

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

?>
