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

defined('_JEXEC') or die;

use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\Factory;

class EdocmanModelExportimport extends OSModel
{
    /**
     * Get statistics about Edocman data
     */
    public function getStatistics()
    {
        $db = $this->getDbo();
        $stats = array();
        
        $tables = array(
            'categories' => '#__edocman_categories',
            'documents' => '#__edocman_documents',
            'document_categories' => '#__edocman_document_category',
            'tags' => '#__edocman_tags',
            'document_tags' => '#__edocman_document_tags',
            'levels' => '#__edocman_levels'
        );
        
        foreach ($tables as $name => $table) {
            $query = $db->getQuery(true)
                ->select('COUNT(*)')
                ->from($table);
            $db->setQuery($query);
            $stats[$name] = (int) $db->loadResult();
        }
        
        return $stats;
    }
    
    /**
     * Get recent categories
     */
    public function getRecentCategories($limit = 10)
    {
        $db = $this->getDbo();
        $query = $db->getQuery(true)
            ->select('id, title, alias, published, created_time, level')
            ->from('#__edocman_categories')
            ->order('created_time DESC')
            ->setLimit($limit);
        
        $db->setQuery($query);
        return $db->loadObjectList();
    }
    
    /**
     * Get recent documents
     */
    public function getRecentDocuments($limit = 10)
    {
        $db = $this->getDbo();
        $query = $db->getQuery(true)
            ->select('id, title, alias, published, created_time, downloads, file_size')
            ->from('#__edocman_documents')
            ->order('created_time DESC')
            ->setLimit($limit);
        
        $db->setQuery($query);
        return $db->loadObjectList();
    }
    
    /**
     * Get database size information
     */
    public function getDatabaseSize()
    {
        $db = $this->getDbo();
        $config = Factory::getApplication()->getConfig();
        $dbName = $config->get('db');
        
        $query = "SELECT 
            TABLE_NAME as table_name,
            ROUND(((DATA_LENGTH + INDEX_LENGTH) / 1024 / 1024), 2) as size_mb
            FROM information_schema.TABLES 
            WHERE TABLE_SCHEMA = " . $db->quote($dbName) . "
            AND TABLE_NAME LIKE " . $db->quote($db->getPrefix() . 'edocman_%');
        
        $db->setQuery($query);
        return $db->loadObjectList();
    }
}
