<?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\Component\ComponentHelper;
use Joomla\CMS\Client\ClientHelper;
use Joomla\CMS\Helper\MediaHelper;
use Joomla\CMS\Filesystem\File;
use Joomla\Filesystem\Path;
use Joomla\CMS\Log\Log;
use BlackSheepResearch\Component\UserPoints\Administrator\AdminController;
use BlackSheepResearch\Component\UserPoints\Site\Problems\SQL;

class UploadControl extends AdminController {
    /*     *
     * upload image
     */

    public function upload() {
        $app = Factory::getApplication();

        // load language fo component media
        $lang = Factory::getLanguage();
        $lang->load('com_media');
        $params = ComponentHelper::getParams('com_media');

        require_once( JPATH_ADMINISTRATOR . '/components/com_media/helpers/media.php' );

        define('COM_AUP_MEDIA_BASE', JPATH_ROOT . '/components/com_userpoints/assets/images/awards');

        // Check for request forgeries
        $this->checkToken('request', true);

        $files = Factory::getApplication()->input->files->get('Filedata', '', 'array');
        $file = $files[0];
        $folder = Factory::getApplication()->input->get('folder', 'icon', 'path');
        $format = Factory::getApplication()->input->get('format', 'html', 'cmd');
        $return = Factory::getApplication()->input->get('return-url', null, 'base64');
        $err = null;

        // Set FTP credentials, if given
        jimport('joomla.client.helper');
        ClientHelper::setCredentialsFromRequest('ftp');

        // Make the filename safe
        jimport('joomla.filesystem.file');
        $file['name'] = File::makeSafe($file['name']);

        if (isset($file['name'])) {
            $filepath = Path::clean(COM_AUP_MEDIA_BASE . '/' . $folder . '/' . strtolower($file['name']));

            if (!(new MediaHelper())->canUpload($file, $err)) {
                if ($format == 'json') {
                    jimport('joomla.error.log');
                    $log = Log::getInstance('upload.error.php');
                    $log->addEntry(array('comment' => 'Invalid: ' . $filepath . ': ' . $err));
                    header('HTTP/1.0 415 Unsupported Media Type');
                    jexit('Error. Unsupported Media Type!');
                } else {
                    $app->enqueueMessage(Text::_($err), 'notice');
                    // REDIRECT
                    if ($return) {
                        $this->redirect(base64_decode($return));
                    }
                    return;
                }
            }

            if (file_exists($filepath)) {
                if ($format == 'json') {
                    jimport('joomla.error.log');
                    $log = Log::getInstance('upload.error.php');
                    $log->addEntry(array('comment' => 'File already exists: ' . $filepath));
                    header('HTTP/1.0 409 Conflict');
                    jexit('Error. File already exists');
                } else {
                    $app->enqueueMessage(Text::_('Error. File already exists'), 'notice');
                    // REDIRECT
                    if ($return) {
                        $this->redirect(base64_decode($return));
                    }
                    return;
                }
            }

            if (!File::upload($file['tmp_name'], $filepath)) {
                if ($format == 'json') {
                    jimport('joomla.error.log');
                    $log = Log::getInstance('upload.error.php');
                    $log->addEntry(array('comment' => 'Cannot upload: ' . $filepath));
                    header('HTTP/1.0 400 Bad Request');
                    jexit('Error. Unable to upload file');
                } else {
                    Factory::getApplication()->enqueueMessage(Text::_('Error. Unable to upload file'), 'warning');
                    // REDIRECT
                    if ($return) {
                        $this->redirect(base64_decode($return));
                    }
                    return;
                }
            } else {
                if ($format == 'json') {
                    jimport('joomla.error.log');
                    $log = Log::getInstance();
                    $log->addEntry(array('comment' => $folder));
                    jexit('Upload complete');
                } else {
                    $app->enqueueMessage(Text::_('Upload complete'));
                    // REDIRECT
                    if ($return) {
                        $this->redirect(base64_decode($return));
                    }
                    return;
                }
            }
        } else {
            $this->redirect('/index.php', 'Invalid Request', 'error');
        }
    }

    public function uploadImportFile() {

        $view = $this->getView('ExportHTML', 'html');

        $error = "";
        $msg = "";

        if (@is_uploaded_file($_FILES["userfile"]["tmp_name"])) {

            $datafile = $_FILES["userfile"];

            //  TODO traitement pour import data
            $db = SQL::getInstance();
            $q = "LOAD DATA INFILE '" . $datafile . "' REPLACE INTO TABLE #__alpha_userpoints_details
						FIELDS TERMINATED BY ';' ENCLOSED BY '\"'
						LINES TERMINATED BY '\r\n'
						IGNORE 1 LINES;";
            $db->setQuery($q);
            $db->execute();

            $view->show();
        } else {
            $error = Text::_('AUP_FILEUPLOAD_ERROR');
            Factory::getApplication()->enqueueMessage($error, 'warning');
            $view->show();
        }
    }

}
