<?php

/**
 * @version        1.11.0
 * @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\CMS\Table\Table;
use Joomla\CMS\Plugin\PluginHelper;

class EdocmanModelUpload extends OSModel
{
	public function __construct(array $config = array())
	{
		parent::__construct();
		$this->state->insert('category_id', 'int', 0)
			->insert('published', 'int', 0)
            ->insert('accesspicker','int',0)
            ->insert('groups', 'array', array())
			->insert('access', 'int', 0);
	}

	/**
	 * Store list of uploaded documents
	 *
	 * @param array $data
	 *
	 * @return boolean
	 */
	public function store($data)
	{
		$db             = $this->getDbo();
		$app			= Factory::getApplication();
		$config         = EDocmanHelper::getConfig();
		$query          = $db->getQuery(true);
		$categoryId     = (int) $data['category_id'];

		//if($config->access_level_inheritance)
		//{
		    $query->clear();
		    $query->select('*')->from('#__edocman_categories')->where('id = '.$categoryId);
		    $db->setQuery($query);
		    $categoryAccess = $db->loadObject();
		    $categoryGroups = EDocmanHelper::getGroupLevels(0, $categoryId);
        //}
	
		$files          = $data['file'];
		$originalFiles  = $data['original_file'];
		$titles         = $data['title'];
		$descriptions   = $data['description'];
        $filesize       = $data['filesize'];
        $fileid         = $data['fileid'];
        //echo $data['accesspicker'];die();
		if (count($files))
		{
			for ($i = 0, $n = count($files); $i < $n; $i++)
			{
				$documentData                      = array();
                $documentData['accesspicker']      = $categoryAccess->accesspicker;
                $documentData['access']            = $categoryAccess->access;
                $documentData['groups']            = $categoryGroups;

                if($documentData['accesspicker'] == 1)
                {
                    $documentData['access']        = 255;
                }
                if($config->require_admin_approve == 1)
                {
                    $documentData['published']     = 0;
                }
                else
                {
                    $documentData['published']     = 1;
                }
				$owner_user_ids					   = [];
				$user_ids_array					   = [];
                
				if($config->owner_inheritance == 1)
				{
					$user_ids                      = $categoryAccess->user_ids;
					$user_ids_array				   = explode(",", $user_ids);
					//$data['user_ids']              = $user_ids;

					$owner_group_ids               = $categoryAccess->owner_group_ids;
					$documentData['owner_group_ids']       = $owner_group_ids;
				}

				if($config->owner_assigned == 1)
                {
                    //$documentData['user_ids']      = Factory::getApplication()->getIdentity()->id;
					$current_user_id				 = Factory::getApplication()->getIdentity()->id;
					//$owner_user_ids[]				 = Factory::getApplication()->getIdentity()->id;
					if(!in_array($current_user_id, $user_ids_array))
					{
						$user_ids_array[]			 = $current_user_id;
					}
                }
				//$owner_user_ids					   = array_merge($owner_user_ids, $user_ids_array);
				if(count($user_ids_array))
				{
					$documentData['user_ids']		= implode(",", $user_ids_array);
				}
				$documentData['title']             = $titles[$i];
				$documentData['original_filename'] = $originalFiles[$i];
				$documentData['filename']          = $files[$i];
				$documentData['alias']             = '';
				$documentData['short_description'] = $descriptions[$i];
                $documentData['file_size']         = $filesize[$i];

				// Check if the document is existed or not
				$sql = 'SELECT COUNT(id) FROM #__edocman_documents WHERE filename="' . $documentData['filename'] . '"';
				$db->setQuery($sql);
				$total = (int) $db->loadResult();
				if ($total > 0)
				{
					continue;
				}

				$auto_approval           = $categoryAccess->auto_approval;
				if($auto_approval == 0)
				{
					if (!$app->isClient('administrator') && $config->require_admin_approve == 0)
					{
						$documentData['published']  = 1;
						//do nothing
					}
					if (!$app->isClient('administrator') && $config->require_admin_approve == 1)
					{
						$documentData['published']  = 0;
					}
				}
				elseif($auto_approval == 1)
				{
					$documentData['published']      = 1;
				}
				elseif($auto_approval == 2)
				{
					$documentData['published']      = 0;
				}

				$row        = Table::getInstance('Document', 'EdocmanTable');
				$row->bind($documentData);
				$row->setMainCategory($categoryId);
				EDocmanHelper::prepareDocument($row, $categoryId);
				$row->check();
				$row->store();

                //generate thumbnail picture
                EDocmanHelper::generateThumbImages($row);

				if ($config->upload_notification)
				{
					EDocmanHelper::sendUploadNotificationEmail($row, $config, (int) $categoryId);
				}
				if (strlen(trim($row->user_ids)) && $config->document_assigned_notification)
				{
					EDocmanHelper::sendDocumentAssignedEmails($row, '');
				}

				PluginHelper::importPlugin('edocman');
				$results = array();
				$results = $app->triggerEvent('onDocumentAfterSave', array('com_edocman.upload', $row, true));

				$db->setQuery("Insert into #__edocman_document_category (category_id, document_id, is_main_category) values (".$categoryId.", ".$row->id.", 1)");
				$db->execute();
				$query->clear();

                if($documentData['accesspicker'] == 1)
                {
                    $query->select('count(id)')->from('#__edocman_levels')->where('data_type = 1')->where('item_id = ' . $row->id);
                    $db->setQuery($query);
                    $count      = $db->loadResult();
                    $groups     = $documentData['groups'];
                    if ($count == 0)
                    {
                        $db->setQuery("Insert into #__edocman_levels (id,data_type,item_id,`groups`) values (NULL,'1',$row->id,'" . $groups . "')");
                        $db->execute();
                    }
                    else
                    {
                        $db->setQuery("Update #__edocman_levels set `groups` = '" . $groups . "' where data_type = 1 and item_id = $row->id");
                        $db->execute();
                    }
                }
				else
				{
					$query->select('count(id)')->from('#__edocman_levels')->where('data_type = 1')->where('item_id = ' . $row->id);
                    $db->setQuery($query);
                    $count      = $db->loadResult();
                    $groups     = $documentData['groups'];
                    if ($count == 0) 
					{
                        $db->setQuery("Insert into #__edocman_levels (id,data_type,item_id,`groups`) values (NULL,'1',$row->id,'')");
                        $db->execute();
                    } 
					else 
					{
                        $db->setQuery("Update #__edocman_levels set `groups` = '' where data_type = 1 and item_id = $row->id");
                        $db->execute();
                    }
				}

                //for google drive
                if(EDocmanHelper::isGdriveTurnedOn())
                {
                    if ($fileid[$i] != '')
                    {
                        $gdrive = Table::getInstance('Googledrive', 'EdocmanTable');
                        $gdrive->id = 0;
                        $gdrive->type = 1;
                        $gdrive->element_id = $row->id;
                        $gdrive->cloud_id = $fileid[$i];
                        $gdrive->store();
                    }
                }
			}
		}
		return true;
	}
}
