<?php
/**
 * @package     Sven.Bluege
 * @subpackage  com_eventgallery
 *
 * @copyright   Copyright (C) 2005 - 2019 Sven Bluege All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */
// no direct access
defined('_JEXEC') or die('Restricted access');

jimport( 'joomla.application.component.controlleradmin' );

class EventgalleryControllerDownloadlog extends \Joomla\CMS\MVC\Controller\AdminController
{

    protected $default_view = 'downloadlog';

    public function export() {
        /**
         * @var EventgalleryLibraryFactoryOrder $orderFactory
         */
        $orderFactory = EventgalleryLibraryFactoryOrder::getInstance();

        $model = $this->getModel();
        $state = $model->getState();
        $items = $model->getItems();

        $filenameParts = ["downloadlog_export"];
        $filenameParts[] = "type_".$model->getState('filter.type');
        $filenameParts[] = "usertype_".$model->getState('filter.usertype');
        $filenameParts[] = "year_".$model->getState('filter.year');
        $filenameParts[] = "month_".$model->getState('filter.month');
        $filenameParts[] = "start_".$model->getState('list.start');
        $filenameParts[] = "limit_".$model->getState('list.limit');

        $filename = implode('-', $filenameParts).".csv";

        header("Cache-Control: no-cache, must-revalidate"); //HTTP 1.1
        header("Pragma: no-cache"); //HTTP 1.0
        header('Content-Type: text/csv');
        header('Content-Disposition: attachment; filename="'.$filename.'"');

        $fp = fopen('php://output', 'wb');
        fputcsv($fp, CSVEntry::getCSVHeadline());

        /**
         * @var CSVEntry[] $entries;
         */
        $entries = [];

        foreach($items as $item) {
            $joomlaUserId = "";
            $joomlaUserEmail = "";

            if (is_numeric($item->juserid)) {
                $user = \Joomla\CMS\Factory::getUser($item->juserid);
                $joomlaUserId = $user->id;
                $joomlaUserEmail = $user->email;
            }

            $orderId = "";
            $orderEmail = "";
            if ($item->type == EventgalleryLibraryCommonDownloadlog::TYPE_PURCHASE_FILE) {
                try {
                    $order = $orderFactory->getOrderById($item->reference);
                    $orderEmail = $order->getEMail();
                    $orderId = $order->getDocumentNumber();
                } catch (Exception $e) {
                }
            }

            $entry = new CSVEntry(
                $item->folder,
                $item->file,
                $item->type,
                $item->isbot,
                $item->created,
                $joomlaUserId,
                $joomlaUserEmail,
                $orderId,
                $orderEmail
            );
            $entries[] = $entry;
        }

        foreach($entries as $key=>$entry) {
            fputcsv($fp, $entry->getCSVLine());
        }

        fclose($fp);

        die();
    }
    /**
     * Proxy for getModel.
     * @param string $name
     * @param string $prefix
     * @param array $config
     * @return EventgalleryModelDownloadlog
     */
    public function getModel($name = 'Downloadlog', $prefix ='EventgalleryModel', $config = [])
    {
        return parent::getModel($name, $prefix, $config);
    }
}

class CSVEntry {
    private $folder;
    private $file;
    private $type;
    private $created;
    private $joomlaUserId;
    private $joomlaUserEmail;
    private $orderId;
    private $orderEmail;

    public function __construct($folder, $file, $type, $created, $joomlaUserId, $joomlaUserEmail, $orderId, $orderEmail)
    {
        $this->folder = $folder;
        $this->file = $file;
        $this->type = $type;
        $this->created = $created;
        $this->joomlaUserId = $joomlaUserId;
        $this->joomlaUserEmail = $joomlaUserEmail;
        $this->orderId = $orderId;
        $this->orderEmail = $orderEmail;
    }

    public static function getCSVHeadline() {
       return [
           "Folder",
           "File",
           "Type",
           "Is Bot",
           "Created",
           "Joomla User Id",
           "Joomla User",
           "Order DocumentNo",
           "Order Email"
       ];
    }

    public function getCSVLine() {
        return [
            $this->folder,
            $this->file,
            $this->type,
            $this->created,
            $this->joomlaUserId,
            $this->joomlaUserEmail,
            $this->orderId,
            $this->orderEmail
        ];
    }
}
