<?php

/**
 * @version        1.9.7
 * @package        Joomla
 * @subpackage     Edocman
 * @author         Tuan Pham Ngoc
 * @copyright      Copyright (C) 2011 - 2025 Ossolution Team
 * @license        GNU/GPL, see LICENSE.php
 */
// No direct access.
defined('_JEXEC') or die;
use Joomla\CMS\Table\Table;
use Joomla\CMS\Language\Text;
use Joomla\CMS\Factory;
use Joomla\Filesystem\File;

/**
 * Edocman model.
 */
class EDocmanModelDocument extends EDocmanModelCommonDocument
{
	public function __construct(array $config = array())
	{
		parent::__construct($config);
	}

    /**
     * @param $value
     * @param $pks
     * @param $contexts
     * @return bool
     */
    public function batch($value, $pks)
    {
        $table = Table::getInstance('Document','EDocmanTable');
        // Parent exists so we let's proceed
        while (!empty($pks))
        {
            // Pop the first ID off the stack
            $pk = array_shift($pks);
            // Check that the row actually exists
            if (!$table->load($pk))
            {
                if ($error = $table->getError())
                {
                    // Fatal error
                    $this->setError($error);
                    return false;
                }
                else
                {
                    // Not fatal error
                    $this->setError(Text::sprintf('JLIB_APPLICATION_ERROR_BATCH_MOVE_ROW_NOT_FOUND', $pk));
                    continue;
                }
            }
            if($value['assetgroup_id'] != "") {
                $table->access = $value['assetgroup_id'];
            }
			if($value['language'] != "") {
                $table->language = $value['language'];
            }
            // Store the row.
            if (!$table->store())
            {
                $this->setError($table->getError());
                return false;
            }
        }
        return true;
    }

	/**
	 * Init the record data object
	 */
	public function initData()
	{
		$this->data = $this->getTable();
		$this->data->license_id = EdocmanHelper::getDefaultLicense();
		//$this->data->access = 2 ;
	}

	/**
	 * Load the record from database
	 */
	public function loadData()
	{
		$config = Factory::getApplication()->getConfig();
		$db    = $this->getDbo();
		$query = $db->getQuery(true);
		$query->select('*')
			->from($this->table)
			->where('id = ' . (int) $this->state->id);
		$db->setQuery($query);

		$this->data = $db->loadObject();
		if($this->data->license_id == 0 && (int) EdocmanHelper::getDefaultLicense() > 0)
		{
			$this->data->license_id = EdocmanHelper::getDefaultLicense();
		}
        if($this->data->id > 0) 
		{
            $groups = EDocmanHelper::getGroupLevels(1, $this->data->id);
            if($groups != '')
			{
                $this->data->groups = explode(",",$groups);
            }
        }
		
		if($this->data->modified_time == "" || $this->data->modified_time == $this->data->created_time)
		{
			$this->data->modified_time = Factory::getDate()->toSql();
		}

		if($this->data->owner_group_ids == '')
		{
			$this->data->owner_group_ids = '-1';
		}
	}


	public function duplicateDocument($id, $moving_category_id)
	{
		$config           = EDocmanHelper::loadConfig();
		$db				  = $this->getDbo();
		$query			  = $db->getQuery(true);
		$query->select('*')
			->from('#__edocman_documents')
			->where('id = ' . (int) $id);
		$db->setQuery($query);
		$row   = $db->loadObject();


		//get category of main document
		$query->clear()->select("category_id")->from('#__edocman_document_category')->where('document_id="'.$id.'" and is_main_category = "1"');
        $db->setQuery($query);
		$main_category = $db->loadResult();

		$document = Table::getInstance('Document','EDocmanTable');
		$document->id = 0;
		
		$document->title = '['.Text::_('EDOCMAN_COPY'). '] '.$row->title;
		$document->alias = Text::_('EDOCMAN_COPY').'-'.$row->alias;

		if(EDocmanHelper::isDropBoxTurnedOn() || EDocmanHelper::isGdriveTurnedOn() || EDocmanHelper::isAmazonS3TurnedOn())
        {
			$document->filename = $row->filename;
			$document->original_filename = $row->original_filename;
		}
		else
		{
			$filename = $row->original_filename;
			$document->original_filename = $row->original_filename;
			if($main_category == $moving_category_id)
			{
				$real_file_name = basename($row->filename);
				if($config->get('position_of_unique_number') == 0)
				{
					$savedFilename  = uniqid('file_') . '_' . $real_file_name;
				}
				elseif($config->get('position_of_unique_number') == 1)
				{
					$fileNameArr	= explode(".", $real_file_name);
					$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];
				}
				
				$new_file_path = str_replace( $real_file_name, $savedFilename, $row->filename);
				File::copy($config->get('documents_path').'/'.$row->filename, $config->get('documents_path').'/'.$new_file_path);
				$document->filename = $new_file_path;
			}
			else
			{
				$real_file_name = basename($row->filename);
				$new_file_path = "";
				if($config->get('activate_herachical_folder_structure'))
				{
					$query->clear()->select('path')->from('#__edocman_categories')->where('id='.$moving_category_id);
					$db->setQuery($query);
					$path = $db->loadResult();

					if($path != "")
					{
						$new_file_path = $path .'/'. $real_file_name;
						File::copy($config->get('documents_path').'/'.$row->filename, $config->get('documents_path').'/'.$new_file_path);
					}
					$document->filename = $new_file_path;
				}
			}
		}
		$document->document_version = $row->document_version;
		$document->image = $row->image;
		$document->document_url = $row->document_url;

		$document->access = $row->access;
		$document->license_id = $row->license_id;
		$document->short_description = $row->short_description;
		$document->description = $row->description;
		$document->metakey = $row->metakey;
		$document->metadesc = $row->metadesc;
		$document->created_user_id = $row->created_user_id;
		$document->created_time = gmdate("Y-m-d H:i:s");
		$document->modified_user_id = $row->modified_user_id;

		$document->modified_time = $row->modified_time;
		$db->setQuery("Select ordering from #__edocman_documents order by ordering desc limit 1");
		$ordering = (int) $db->loadResult() + 1;
		$document->ordering = $ordering;
		$document->published = $row->published;
		$document->user_ids = $row->user_ids;
		$document->language = $row->language;
		$document->indexed_content = $row->indexed_content;
		$document->tags = $row->tags;
		$document->indicators = $row->indicators;
		$document->publish_up = $row->publish_up;
		$document->publish_down = $row->publish_down;
		$document->params = $row->params;
		$document->view_url = $row->view_url;
		$document->file_size = $row->file_size;
		$document->document_history = $row->document_history;
		$document->owner_group_ids = $row->owner_group_ids;

		$document->accesspicker = $row->accesspicker;
		$document->download_limit_per_user = $row->download_limit_per_user;
		$document->download_password = $row->download_password;
		$document->disable_download = $row->disable_download;
		$document->exclude_indexing = $row->exclude_indexing;
		$document->hide_search_engines = $row->hide_search_engines;

		$document->store();
		$new_document_id = $document->id;

		if($main_category == $moving_category_id)
		{
			$query->clear();
			$query->select('*')->from('#__edocman_document_category')->where('document_id='.$id);
			$db->setQuery($query);
			$categories = $db->loadObjectList();

			foreach($categories as $category)
			{
				$query->clear();
				$columns = array('id', 'document_id', 'category_id', 'is_main_category');
				$values  = array('NULL',$new_document_id,$category->category_id,$category->is_main_category);
				$query->insert("#__edocman_document_category")->columns($columns)->values(implode(',',$values));
				$db->setQuery($query);
				$db->execute();
			}
		}
		else
		{
			$query->clear();
			$columns = array('id', 'document_id', 'category_id', 'is_main_category');
			$values  = array('NULL',$new_document_id,$moving_category_id,1);
			$query->insert("#__edocman_document_category")->columns($columns)->values(implode(',',$values));
			$db->setQuery($query);
			$db->execute();

			
			$query->clear();
			$query->select('*')->from('#__edocman_document_category')->where('document_id='.$id)->where('category_id <> '.$main_category.' and category_id <> '.$moving_category_id);
			$db->setQuery($query);
			$categories = $db->loadObjectList();

			foreach($categories as $category)
			{
				$query->clear();
				$columns = array('id', 'document_id', 'category_id', 'is_main_category');
				$values  = array('NULL',$new_document_id,$category->category_id,0);
				$query->insert("#__edocman_document_category")->columns($columns)->values(implode(',',$values));
				$db->setQuery($query);
				$db->execute();
			}
		}

		$query->clear();
		$query->select('asset_id')->from('#__edocman_categories')->where("id = '$moving_category_id'");
		$db->setQuery($query);
		$asset_id = $db->loadResult();

		if ($config->get('access_level_inheritance')) 
		{
			$query->clear();
			// Fields to update.
			$fields = array(
				$db->quoteName('asset_id') . ' = ' . $asset_id
			);

			// Conditions for which records should be updated.
			$conditions = array(
				$db->quoteName('id') . ' = '.$new_document_id
			);
			$query->update('#__edocman_documents')->set($fields)->where($conditions);
			$db->setQuery($query);
			$db->execute();
		}
		
		$query->clear()->select('tag_id')->from('#__edocman_document_tags')->where('document_id='.$id);
		$db->setQuery($query);
		$tags = $db->loadObjectList();
		if(count($tags))
		{
			foreach($tags as $tag)
			{
				$query->clear();
				$columns = array('id', 'document_id', 'tag_id');
				$values  = array('NULL',$new_document_id,$tag->id);
				$query->insert("#__edocman_document_tags")->columns($columns)->values(implode(',',$values));
				$db->setQuery($query);
				$db->execute();
			}
		}

		$query->clear()->select('groups')->from('#__edocman_levels')->where('item_id='.$id .' and data_type=1 and `groups` <> ""');
		$db->setQuery($query);
		$levels = $db->loadObjectList();
		if(count($levels) > 0)
		{
			foreach($levels as $level)
			{
				$query->clear();
				$columns = array('id', 'data_type' , 'item_id', 'groups');
				$values  = array('NULL','1',$new_document_id,$level->groups);
				$query->insert("#__edocman_levels")->columns($columns)->values(implode(',',$values));
				$db->setQuery($query);
				$db->execute();
			}
		}
	}
}
