<?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;
use Joomla\CMS\Language\Text;
use Joomla\Filesystem\File;
use Joomla\Filesystem\Path;

class EdocmanModelImportdb extends OSModel
{
    /**
     * Import data from uploaded file
     */
    public function importData($options = array())
    {
        $app = Factory::getApplication();
        $input = $app->getInput();
        
        // Get uploaded file
        $files = $input->files->get('jform');
        $uploadedFile = $files['import_file'];
        
        if (!$uploadedFile || $uploadedFile['error'] !== UPLOAD_ERR_OK) {
            return array(
                'success' => false,
                'message' => Text::_('EDOCMAN_IMPORT_NO_FILE')
            );
        }
        
        // Validate file
        $allowedTypes = array('application/sql', 'text/plain', 'application/octet-stream');
        if (!in_array($uploadedFile['type'], $allowedTypes) && 
            !preg_match('/\.sql$/i', $uploadedFile['name'])) {
            return array(
                'success' => false,
                'message' => Text::_('EDOCMAN_IMPORT_INVALID_FILE_TYPE')
            );
        }
        
        try {
            $sqlContent = file_get_contents($uploadedFile['tmp_name']);
            
            if (empty($sqlContent)) {
                throw new Exception('Empty file content');
            }
            
            return $this->executeSQLImport($sqlContent, $options);
            
        } catch (Exception $e) {
            return array(
                'success' => false,
                'message' => Text::_('EDOCMAN_IMPORT_ERROR') . ': ' . $e->getMessage()
            );
        }
    }
    
    /**
     * Execute SQL import
     */
    protected function executeSQLImport($sqlContent, $options)
    {
        $db = $this->getDbo();
        
        try {
            $db->transactionStart();
            
            // Clear existing data if requested
            if (isset($options['clear_existing']) && $options['clear_existing']) {
                $this->clearExistingData();
            }
            
            // Split SQL into statements
            $statements = $this->splitSQLStatements($sqlContent);
            $executedCount = 0;
            
            foreach ($statements as $statement) {
                $statement = trim($statement);
                
                // Skip empty statements and comments
                if (empty($statement) || strpos($statement, '--') === 0 || strpos($statement, '/*') === 0) {
                    continue;
                }
                
                // Skip certain statements
                if (preg_match('/^(SET|START TRANSACTION|COMMIT)/i', $statement)) {
                    continue;
                }
                
                $db->setQuery($statement);
                $db->execute();
                $executedCount++;
            }
            
            $db->transactionCommit();
            
            return array(
                'success' => true,
                'message' => Text::sprintf('EDOCMAN_IMPORT_SUCCESS', $executedCount)
            );
            
        } catch (Exception $e) {
            $db->transactionRollback();
            throw $e;
        }
    }
    
    /**
     * Clear existing data
     */
    protected function clearExistingData()
    {
        $db = $this->getDbo();
        
        $tables = array(
            '#__edocman_document_tags',
            '#__edocman_document_category',
            '#__edocman_levels',
            '#__edocman_documents',
            '#__edocman_categories',
            '#__edocman_tags'
        );
        
        foreach ($tables as $table) {
            $query = "TRUNCATE TABLE " . $db->quoteName($table);
            $db->setQuery($query);
            $db->execute();
        }
    }
    
    /**
     * Split SQL content into individual statements
     */
    protected function splitSQLStatements($sql)
    {
        $statements = array();
        $current = '';
        $inString = false;
        $stringChar = '';
        $length = strlen($sql);
        
        for ($i = 0; $i < $length; $i++) {
            $char = $sql[$i];
            
            if (!$inString && ($char === '"' || $char === "'")) {
                $inString = true;
                $stringChar = $char;
            } elseif ($inString && $char === $stringChar) {
                // Check for escaped quotes
                if ($i > 0 && $sql[$i - 1] !== '\\') {
                    $inString = false;
                }
            }
            
            $current .= $char;
            
            if (!$inString && $char === ';') {
                $statements[] = $current;
                $current = '';
            }
        }
        
        if (!empty(trim($current))) {
            $statements[] = $current;
        }
        
        return $statements;
    }
    
    /**
     * Get current statistics
     */
    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;
    }
}
