<?php

/**
 * @version        1.9.7
 * @package        Joomla
 * @subpackage     Edocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2011 - 2024 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */

// No direct access
defined('_JEXEC') or die();
use Joomla\CMS\Factory;
use Joomla\Filesystem\Path;
use Joomla\Filesystem\File;
use Joomla\CMS\Plugin\PluginHelper;
use Joomla\CMS\Language\Text;

class EDocmanControllerUpload extends EDocmanController
{
	/**
	 * Upload files and store it to the correct folder
	 */
	public function upload()
	{
		$config     = EDocmanHelper::loadConfig();
		$rootDir    = $config->get('documents_path');
		$categoryId = $this->input->getInt('category_id', 0);
		$file       = $this->input->files->get('file',null,'raw');
		$fileName   = $file['name'];
		if($config->get('make_filename_safely'))
		{
			$fileName = File::makeSafe($fileName);
		}
		$uploadPath = $rootDir;

		if (($categoryId > 0) && $config->get('activate_herachical_folder_structure'))
		{
			$db    = Factory::getContainer()->get('db');
			$query = $db->getQuery(true);
			$query->select('`path`')
				->from('#__edocman_categories')
				->where('id=' . (int) $categoryId);
			$db->setQuery($query);
			$path = $db->loadResult();
			if ($path)
			{
				$uploadPath .= '/' . $path;
			}
		}
		else
		{
            $path = "";
        }

		if (is_file(Path::clean($uploadPath . '/' . $fileName)) && !$config->get('overwrite_existing_file'))
		{
            if(!EDocmanHelper::isDropBoxTurnedOn() && !EDocmanHelper::isGdriveTurnedOn() && !EDocmanHelper::isAmazonS3TurnedOn())
            {
                if($config->get('position_of_unique_number') == 0)
				{
					$savedFilename  = uniqid('file_') . '_' . $fileName;
				}
				elseif($config->get('position_of_unique_number') == 1)
				{
					$fileNameArr	= explode(".", $fileName);
					$fileNameRaw	= "";
					for($i = 0;$i < count($fileNameArr) - 1;$i++)
					{
						$fileNameRaw .= $fileNameArr[$i].".";
					}
					$fileNameRaw    = substr($fileNameRaw, 0, strlen($fileNameRaw) - 1);
					$fileNameRaw    .= '_'.uniqid('file_');
					$savedFilename  = $fileNameRaw.'.'.$fileNameArr[count($fileNameArr) - 1];
				}
            }
            else
            {
                $savedFilename = $fileName;
            }
		}
		else
		{
			$savedFilename = $fileName;
		}

        // Give plugin a change to upload the file
        $app = Factory::getApplication();

        PluginHelper::importPlugin('edocman');
        $results = array();
        $results = $app->triggerEvent('onDocumentBatchUpload', array($savedFilename, $file, $path, $categoryId));
        $return  = $results[0][0];

        if ($return != true)
        {
            if (version_compare(JVERSION, '3.4.4', 'ge'))
            {
                File::upload($file['tmp_name'], $uploadPath . '/' . $savedFilename, false, false);
                $results[0][1] = @filesize($uploadPath . '/' . $savedFilename);
            }
            else
            {
                File::upload($file['tmp_name'], $uploadPath . '/' . $savedFilename);
                $results[0][1] = @filesize($uploadPath . '/' . $savedFilename);
            }
        }
        else
        {
			if($savedFilename == "")
			{
				$savedFilename = Factory::getApplication()->input->getString('fileName','');
			}
        }


		$session         = Factory::getApplication()->getSession();
		$files           = $session->get('files', array());
        $filesize        = $session->get('filesize', array());
		$originalFiles   = $session->get('originalFiles', array());
		$files           = (array) $files;
		$originalFiles   = (array) $originalFiles;
		$files[]         = empty($path) ? $savedFilename : $path . '/' . $savedFilename;
		$originalFiles[] = $savedFilename;
        $filesize[]      = $results[0][1];
        //for google drive
        $fileid[]        = $results[0][2];

		$session->set('files', $files);
        $session->set('filesize', $filesize);
		$session->set('originalFiles', $originalFiles);
        $session->set('fileid', $fileid);

		// Xác định có lỗi hay không
		$error = '';
		if (empty($savedFilename)) {
			$error = 'File name is empty!';
		} elseif (!file_exists($uploadPath . '/' . $savedFilename)) {
			$error = 'Upload failed!';
		}

		// Trả về JSON cho JS
		header('Content-Type: application/json');
		echo json_encode([
			'error' => $error,
			'filename' => $savedFilename,
			'filesize' => $results[0][1] ?? 0,
			'path' => $path ?? '',
		]);
		exit; // Đảm bảo dừng xử lý tiếp

	}

	/**
	 * Display form which allows batch editing the uploaded documents
	 */
	public function edit_documents()
	{
		$session = Factory::getApplication()->getSession();
		$files   = $session->get('files', array());
		if (!count($files))
		{
			//Redirect back to upload page, display error message
			$this->setRedirect('index.php?option=com_edocman&view=upload', Text::_('EDOCMAN_NO_FILES_UPLOADED'), 'warning');

			return;
		}
		$this->input->set('view', 'upload');
		$this->input->set('layout', 'edit');
		$this->display();
	}

	/**
	 * Store title, description of the documents which were entered in batch-edit screen
	 */
	public function store_documents()
	{
		$model = $this->getModel();
		$data  = $this->input->getData();
		$model->store($data);
		$session = Factory::getApplication()->getSession();
		$session->clear('files');
		$session->clear('originalFiles');
        $session->clear('filesize');
        $session->clear('fileid');
		$this->setRedirect('index.php?option=com_edocman&view=documents', Text::_('Documents successfully uploaded'));
	}

	/**
	 * Cancel Bulk upload action, redirect user to documents management page
	 */
	public function cancel()
	{
		$this->setRedirect('index.php?option=com_edocman&view=documents');
	}
}
