<?php

// ============
// Export Class
// ============

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

    // =====================
    // Create Export Request
    // =====================

    public function createExportRequest($subscription_serial = 0, $export_type = "", $report_type = "") {

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

        $subscription = (new Subscriptions())->getSubscription($subscription_serial);

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

        $export_type = filter_input(INPUT_POST, "export_type") ?: "";
        $report_type = filter_input(INPUT_POST, "report_type") ?: "";

        $exportjob_export_type = str_replace(' ', '', $subscription->record->subscription_full_title) . "$export_type";
        $exportjob_file_name   = str_replace(' ', '_', $subscription->record->subscription_full_title) . "_all_records.{$report_type}";
//        $exportjob_file_name = str_replace('&', 'And', $subscription->record->subscription_full_title) . "_all_records.{$report_type}";

        $SQL = "insert into exportjobs
          
                         (  exportjob_subscription,
                            exportjob_export_type,
                            exportjob_file_name,
                            exportjob_file_type,
                            exportjob_creator,
                            exportjob_created )
                               
                  VALUES ( :exportjob_subscription,
                           :exportjob_export_type,
                           :exportjob_file_name,
                           :exportjob_file_type,
                           :exportjob_creator,
                           :exportjob_created )";

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

        $statement->bindValue(":exportjob_subscription", $subscription_serial);
        $statement->bindValue(":exportjob_export_type", $exportjob_export_type);
        $statement->bindValue(":exportjob_file_name", $exportjob_file_name);
        $statement->bindValue(":exportjob_file_type", strtoupper($report_type));
        $statement->bindValue(":exportjob_creator", $this->current_user_serial);
        $statement->bindValue(":exportjob_created", $this->getTimestamp());

        $statement->execute();

        $this->displayNotice("Your export has been queued. You will receive an notification when it is ready.");
    }

    // ============
    // User Exports
    // ============

    public function usersExports() {

        $exports = $this->getUsersExports();
        $popovers = (new Popovers())->getPopovers();

        $this->markExportsAsSeen();

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

        $html = $this->applyXSL($XML, $this->getXSL("viewExports"));

        $this->displayContent($html);
    }

    // =========================
    // Mark User Exports as Seen
    // =========================

    public function markExportsAsSeen() {

        $SQL = "update exportjobs
                   set exportjob_notified           = true
                 where exportjobs.exportjob_creator = {$this->current_user_serial}";

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

        $statement->execute();
    }

    // =======================
    // Return a Exports Object
    // =======================

    public function getUsersExports() {

        // Find Criteria

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

        // Show Per Page
        $this->pagination_size = filter_input(INPUT_POST, "exportjobs_per_page", FILTER_SANITIZE_NUMBER_INT) ?: $this->pagination_size;

        // Record Count

        $connection = $this->connect();

        $SQL = "select count(*) as count
                  from view_exportjobs
                 where view_exportjobs.exportjob_creator = {$this->current_user_serial}
                   and view_exportjobs.subscription_full_title regexp :subscription_full_title";

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

        $statement->bindValue(":subscription_full_title", $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_exportjobs.* 
                  from view_exportjobs
                 where view_exportjobs.exportjob_creator = {$this->current_user_serial}
                   and view_exportjobs.subscription_full_title regexp :subscription_full_title
                 limit {$this->pagination_size}
                offset {$offset}";

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

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

        $statement->execute();

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

        // Insert Pagination Attributes

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

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

        return $exportjobs;
    }

    // =====================================
    // Return if users exports are completed
    // =====================================

    public function checkUsersCompletedExports_AJAX() {

        $SQL = "select count(*) as notify
                  from view_exportjobs
                 where view_exportjobs.exportjob_creator = :current_user_serial
                   and view_exportjobs.exportjob_status = 'complete'
                   and view_exportjobs.exportjob_notified = 0";

        $exportjobs = $this->getTable("exportjobs", $SQL, array('current_user_serial' => $this->current_user_serial));

        // Create the User Object.

        $users_exports = array();

        $users_exports["notify"] = ($exportjobs->record->notify == 0) ? false : true;

        if ($_SESSION[self::AJAX]) {
            echo json_encode($users_exports);
        } else {
            return $users_exports;
        }
    }

    // ===============
    // Download Export
    // ===============

    public function downloadExport() {

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

        $SQL = "select view_exportjobs.*
                  from view_exportjobs
                 where view_exportjobs.exportjob_download_token  = :export_code
                   and view_exportjobs.exportjob_status          = 'complete' limit 1";

        $exportjob = $this->getTable("exportjob", $SQL, array("export_code" => $export_code));

        $file_path = str_replace('../exports/', './exports/', $exportjob->record->exportjob_file_path);
        $file_name = $exportjob->record->exportjob_file_name;

        header('Content-Type: application/octet-stream');
        header("Content-Disposition: attachment; filename=\"$file_name\"");

        readfile($file_path);
    }
}

?>
