<?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;
    }

    // ===================
    // 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);
    }

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

    public function goToSubscription($subscription_serial = 0) {

        $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__);
        }

        switch ($subscription_serial) {

            case 5:

                $_SESSION['subscription_serial'] = $subscription_serial;

                (new PermitsByBuilder())->searchPermits($subscription_serial);

                break;

            case 7:

                $_SESSION['subscription_serial'] = $subscription_serial;

                (new PermitsBySubdivision())->searchPermits($subscription_serial);

                break;

            case 9:

                $project_type = "SingleFamily";
                $area = "South";

                (new PermitsByBuilder())->searchPermits($project_type, $area);

                break;

            case 10:

                $project_type = "SingleFamily";
                $area = "South";

                (new PermitsBySubdivision())->searchPermits($project_type, $area);

                break;

            case 11:

                $project_type = "SingleFamily";
                $area = "All";

                (new PermitsByBuilder())->searchPermits($project_type, $area);

                break;

            case 12:

                $project_type = "SingleFamily";
                $area = "All";

                (new PermitsBySubdivision())->searchPermits($project_type, $area);

                break;

            case 13:

                $project_type = "MultiFamily";
                $area = "South";

                (new PermitsByBuilder())->searchPermits($project_type, $area);

                break;

            case 14:

                $project_type = "MultiFamily";
                $area = "South";

                (new PermitsBySubdivision())->searchPermits($project_type, $area);

                break;

            case 15:

                $project_type = "MultiFamily";
                $area = "North";

                (new PermitsByBuilder())->searchPermits($project_type, $area);

                break;

            case 16:

                $project_type = "MultiFamily";
                $area = "North";

                (new PermitsBySubdivision())->searchPermits($project_type, $area);

                break;
        }
    }

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

    public function addSubscription() {

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

        switch ($step) {

            case "prompt":

                $constants = $this->getConstants();

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

                $this->displayContent($content);

                break;

            case "add":

                $subscription_title = filter_input(INPUT_POST, "subscription_title") ?: "";
                $subscription_description = filter_input(INPUT_POST, "subscription_description") ?: "";
                $subscription_projecttype = filter_input(INPUT_POST, "subscription_projecttype") ?: "";
                $subscription_area = filter_input(INPUT_POST, "subscription_area") ?: "";

                $SQL = "insert into subscriptions
          
                         (  subscription_title,
                            subscription_description,
                            subscription_projecttype,
                            subscription_area,
                            subscription_creator,
                            subscription_created )
                               
                  VALUES ( :subscription_title,
                           :subscription_description,
                           :subscription_projecttype,
                           :subscription_area,
                           :subscription_creator,
                           :subscription_created )";

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

                $statement->bindValue(":subscription_title", $subscription_title);
                $statement->bindValue(":subscription_description", $subscription_description);
                $statement->bindValue(":subscription_projecttype", $subscription_projecttype);
                $statement->bindValue(":subscription_area", $subscription_area);
                $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__);
                }

                $constants = $this->getConstants();

                $XML = $this->mergeXML($constants, "<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_description = filter_input(INPUT_POST, "subscription_description") ?: "";
                $subscription_projecttype = filter_input(INPUT_POST, "subscription_projecttype") ?: "";
                $subscription_area = filter_input(INPUT_POST, "subscription_area") ?: "";

                $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_description = :subscription_description,
                               subscription_projecttype = :subscription_projecttype,
                               subscription_area        = :subscription_area
                         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_description", $subscription_description);
                $statement->bindValue(":subscription_projecttype", $subscription_projecttype);
                $statement->bindValue(":subscription_area", $subscription_area);

                $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_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_end_date" => date("Y-m-d", strtotime($subscription_end_dates[$index] ?? ""))
                    );
                }

                $SQL = "insert into usersubscriptions
                    
                         (  usersubscription_user_serial,
                            usersubscription_subscription_serial,
                            usersubscription_stop_date,
                            usersubscription_origin,
                            usersubscription_timestamp )
                               
                  VALUES ( :usersubscription_user_serial,
                           :usersubscription_subscription_serial,
                           :usersubscription_stop_date,
                           :usersubscription_origin,
                           :usersubscription_timestamp )";

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

                $statement->bindValue(":usersubscription_user_serial", $user_serial);
                $statement->bindValue(":usersubscription_timestamp", $this->getTimestamp());
                $statement->bindValue(":usersubscription_origin", $this->current_user_name);

                foreach ($subscriptions as $subscription) {

                    $subscription_serial = $subscription['usersubscription_subscription'];
                    $subscription_stop_date = $subscription['usersubscription_end_date'];

                    $statement->bindValue(":usersubscription_subscription_serial", $subscription_serial);
                    $statement->bindValue(":usersubscription_stop_date", $subscription_stop_date);

                    $statement->execute();
                }

                break;

            default:

                $this->displayHome();
        }
    }

    // =========================
    // 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->getSubscriptions();

                $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":

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

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

                $SQL = "update usersubscriptions
                           set usersubscription_stop_date           = :usersubscription_stop_date,
                               usersubscription_subscription_serial = :usersubscription_subscription_serial,
                               usersubscription_origin              = :usersubscription_origin,
                               usersubscription_timestamp           = :usersubscription_timestamp
                         where usersubscription_serial              = :usersubscription_serial";

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

                $statement->bindValue(":usersubscription_stop_date", $subscription_stop_date);
                $statement->bindValue(":usersubscription_subscription_serial", $subscription_serial);
                $statement->bindValue(":usersubscription_origin", $this->current_user_name);
                $statement->bindValue(":usersubscription_timestamp", $this->getTimestamp());
                $statement->bindValue(":usersubscription_serial", $usersubscription_serial);

                $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_description  regexp :subscription_description
                    or subscription_projecttype  regexp :subscription_projecttype
                    or subscription_area         regexp :subscription_area";

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

        $statement->bindValue(":subscription_title", $find_words);
        $statement->bindValue(":subscription_description", $find_words);
        $statement->bindValue(":subscription_projecttype", $find_words);
        $statement->bindValue(":subscription_area", $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_description  regexp :subscription_description
                    or subscription_projecttype  regexp :subscription_projecttype
                    or subscription_area         regexp :subscription_area
          order by subscription_title
             limit {$this->pagination_size}
            offset {$offset}";

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

        $statement->bindValue(":subscription_title", $find_words);
        $statement->bindValue(":subscription_description", $find_words);
        $statement->bindValue(":subscription_projecttype", $find_words);
        $statement->bindValue(":subscription_area", $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;
    }

    // ==================
    // User Subscriptions
    // ==================

    public function userSubscriptions() {

        $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);
    }

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

    public function getUsersActiveSubscriptions($user_serial) {

        $SQL = "SELECT view_usersubscriptions.*
                  FROM view_usersubscriptions
                 WHERE usersubscription_user_serial = '{$user_serial}'
                   AND view_usersubscriptions.usersubscription_status = 'ACTIVE'
                   AND view_usersubscriptions.usersubscription_stop_date >= NOW()
              ORDER BY 
                  CASE 
                    WHEN view_usersubscriptions.subscription_area = 'All' THEN 0
                    ELSE 1
                   END,
                      view_usersubscriptions.subscription_title, 
                      view_usersubscriptions.usersubscription_status";

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

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

    public function getAllUsersSubscriptions($user_serial) {

        $SQL = "select view_usersubscriptions.*
                  from view_usersubscriptions
                 where usersubscription_user_serial = {$user_serial}
              order by  view_usersubscriptions.usersubscription_status, view_usersubscriptions.subscription_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);
    }
}

?>
