<?php

/*
 * @component UserPoints
 * @copyright Copyright (C) 2015-2022 Bernard Gilly - Adrien Roussel - Martin Brampton
 * @license : GNU/GPL
 * @Website : https://remository.com
 */

namespace BlackSheepResearch\Component\UserPoints\Administrator\Controllers;

// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();

use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\HTML\HTMLHelper;
use Joomla\CMS\Mail\MailHelper;
use BlackSheepResearch\Component\UserPoints\Administrator\AdminController;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;

class ExportsControl extends AdminController {

    /**
     * Export 50 most active users in CSV
     */
    public function exportactiveusers() {

        $model = $this->getModel('exports');
        $_row = $model->_export_most_active_users();

        if ($_row) {
            $totalRecords = 0;
            $fileName = "mostactiveusers_" . uniqid(rand(), true) . ".csv";
            $filepath = JPATH_COMPONENT_ADMINISTRATOR . '/assets/csv/' . $fileName;

            $handler = fopen($filepath, "a");
            fwrite($handler, "#;USER ID;NAME;USERNAME;POINTS;USERPOINTS ID" . "\n");

            $total = count($_row);
            $j = 0;
            for ($i = 0; $i < $total; $i++) {
                if ($_row[$i]->referreid != 'GUEST') {
                    $j++;
                    fwrite($handler, $j . ";" . $_row[$i]->userid . ";" . $_row[$i]->name . ";" . $_row[$i]->username . ";" . $_row[$i]->points . ";" . $_row[$i]->referreid . "\n");
                }
            }

            header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
            header("Last-Modified: " . gmdate('D,d M Y H:i:s') . ' GMT');
            header("Cache-Control: no-cache, must-revalidate");
            header("Pragma: no-cache");
            header("Content-Type: text/x-comma-separated-values");
            header("Content-Disposition: attachment; filename=$fileName");

            readfile($filepath);

            exit;
        } else {
            $error = Text::_('AUP_NO_DATA');
            Factory::getApplication()->enqueueMessage($error, 'warning');
            return $this->cpanel();
        }
    }

    /**
     * Export all e-mails addresses sent in CSV
     */
    public function exportemails() {

        jimport('joomla.mail.helper');

        $model = $this->getModel('exports');
        $_row = $model->_export_emails();

        if ($_row) {
            $totalRecords = 0;
            $fileName = "export_emails_" . uniqid(rand(), true) . ".csv";
            $filepath = JPATH_COMPONENT_ADMINISTRATOR . '/assets/csv/' . $fileName;

            $handler = fopen($filepath, "a");
            fwrite($handler, "EMAIL" . "\n");

            $total = count($_row);
            for ($i = 0; $i < $total; $i++) {
                $_row[$i]->datareference = str_replace(" [at] ", "@", $_row[$i]->datareference);
                $aEmails = $this->extractEmailsFromString($_row[$i]->datareference);
                if (count($aEmails) AND MailHelper::isEmailAddress($aEmails[0])) {
                    fwrite($handler, $aEmails[0] . "\n");
                }
            }

            header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
            header("Last-Modified: " . gmdate('D,d M Y H:i:s') . ' GMT');
            header("Cache-Control: no-cache, must-revalidate");
            header("Pragma: no-cache");
            header("Content-Type: text/x-comma-separated-values");
            header("Content-Disposition: attachment; filename=$fileName");

            readfile($filepath);

            exit;
        } else {
            $error = Text::_('AUP_NO_DATA');
            Factory::getApplication()->enqueueMessage($error, 'warning');
            return $this->cpanel();
        }
    }

    // export activities of a specific user to CSV
    public function exportallactivitiesuser() {
        $model = $this->getModel('exports');
        $lastpoints = $model->_exportallactivitiesuser();

        $fileName = $referrerid . "_activities_" . uniqid(rand(), true) . ".csv";
        $filepath = JPATH_SITE . '/tmp/' . $fileName;

        $handler = fopen($filepath, "a");
        $header = Text::_('AUP_USERNAME') . ";" . Text::_('AUP_DATE') . ";" . Text::_('AUP_ACTIVITY') . ";" . Text::_('AUP_POINTS') . ";" . Text::_('AUP_EXPIRE') . ";" . Text::_('AUP_DETAILS') . ";" . Text::_('AUP_APPROVED') . "\n";
        fwrite($handler, $header . "\n");

        $total = count($lastpoints);
        for ($i = 0; $i < $total; $i++) {

            $date_insert = $this->presentDate('date', $lastpoints[$i]->insert_date, Text::_('DATE_FORMAT_LC2'));

            if ($lastpoints[$i]->expire_date == SQL::nulldatetimeSQL()) {
                $date_expire = '';
            } else {
                $date_expire = $this->presentDate('date', $lastpoints[$i]->expire_date, Text::_('DATE_FORMAT_LC'));
            }

            $approved = ( $lastpoints[$i]->approved ) ? Text::_('AUP_APPROVED') : Text::_('AUP_PENDING_APPROVAL');

            fwrite($handler, $lastpoints[$i]->username . ";" . $date_insert . ";" . Text::_($lastpoints[$i]->rule_name) . ";" . $lastpoints[$i]->points . ";" . $date_expire . ";" . $lastpoints[$i]->datareference . ";" . $approved . "\n");
        }

        header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
        header("Last-Modified: " . gmdate('D,d M Y H:i:s') . ' GMT');
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-Type: text/x-comma-separated-values");
        header("Content-Disposition: attachment; filename=$fileName");

        readfile($filepath);

        exit;
    }

    // Export all activities for all members to CSV
    public function exportallactivitiesallusers() {
        $model = $this->getModel('exports');
        $lastpoints = $model->_exportallactivitiesallusers();

        $fileName = "all_activities_" . uniqid(rand(), true) . ".csv";
        $filepath = JPATH_SITE . '/tmp/' . $fileName;

        $handler = fopen($filepath, "a");
        $header = Text::_('AUP_USERNAME') . ";" . Text::_('AUP_DATE') . ";" . Text::_('AUP_ACTIVITY') . ";" . Text::_('AUP_POINTS') . ";" . Text::_('AUP_EXPIRE') . ";" . Text::_('AUP_DETAILS') . ";" . Text::_('AUP_APPROVED') . "\n";
        fwrite($handler, $header . "\n");

        $total = count($lastpoints);
        for ($i = 0; $i < $total; $i++) {

            $date_insert = $this->presentDate('date', $lastpoints[$i]->insert_date, Text::_('DATE_FORMAT_LC2'));

            if ($lastpoints[$i]->expire_date == SQL::nulldatetimeSQL()) {
                $date_expire = '';
            } else {
                $date_expire = $this->presentDate('date', $lastpoints[$i]->expire_date, Text::_('DATE_FORMAT_LC'));
            }

            $approved = ( $lastpoints[$i]->approved ) ? Text::_('AUP_APPROVED') : Text::_('AUP_PENDING_APPROVAL');

            fwrite($handler, $lastpoints[$i]->username . ";" . $date_insert . ";" . Text::_($lastpoints[$i]->rule_name) . ";" . $lastpoints[$i]->points . ";" . $date_expire . ";" . $lastpoints[$i]->datareference . ";" . $approved . "\n");
        }

        header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
        header("Last-Modified: " . gmdate('D,d M Y H:i:s') . ' GMT');
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-Type: text/x-comma-separated-values");
        header("Content-Disposition: attachment; filename=$fileName");

        readfile($filepath);

        exit;
    }

    public function exportcoupons() {
        $model = $this->getModel('exports');
        $_row = $model->_export_coupons();

        $fileName = "coupons_" . uniqid(rand(), true) . ".csv";
        $filepath = JPATH_COMPONENT_ADMINISTRATOR . '/assets/csv/' . $fileName;

        $handler = fopen($filepath, "a");
        fwrite($handler, "#;ID;DESCRIPTION;COUPON CODE;POINTS;EXPIRE DATE;PUBLIC\n");
        $j = 0;
        $total = count($_row);

        for ($i = 0; $i < $total; $i++) {
            $j++;
            fwrite($handler, $j . ";" . $_row[$i]->id . ";" . $_row[$i]->description . ";" . $_row[$i]->couponcode . ";" . $_row[$i]->points . ";" . $_row[$i]->expires . ";" . $_row[$i]->public . "\n");
        }

        header("Expires: Mon, 26 Nov 1962 00:00:00 GMT");
        header("Last-Modified: " . gmdate('D,d M Y H:i:s') . ' GMT');
        header("Cache-Control: no-cache, must-revalidate");
        header("Pragma: no-cache");
        header("Content-Type: text/x-comma-separated-values");
        header("Content-Disposition: attachment; filename=$fileName");

        readfile($filepath);

        exit;
    }

    private function presentDate ($type, $date, $format) : string {
        if ('date' == $type) {
            return date($format, strtotime($date));
        }
    }
}
