<?php
/**
* @package   BaForms
* @author    Balbooa http://www.balbooa.com/
* @copyright Copyright @ Balbooa
* @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
*/

namespace Balbooa\Component\Forms\Administrator\Model;

defined('_JEXEC') or die;

use Balbooa\Component\Forms\Administrator\Helper\BaformsHelper;
use Balbooa\Component\Forms\Administrator\Helper\Filesystem\File;
use Balbooa\Component\Forms\Administrator\Helper\Filesystem\Folder;
use Joomla\CMS\MVC\Model\BaseDatabaseModel;
use Joomla\CMS\Factory;
use Joomla\CMS\Uri\Uri;
use Joomla\CMS\Component\ComponentHelper;

class UploaderModel extends BaseDatabaseModel
{
    protected $_parent;
    protected $_folders;
    protected array $images = ['jpg', 'png', 'gif', 'svg', 'jpeg', 'webp'];

    public function getParent()
    {
        return $this->_parent;
    }

    public function getFolderList()
    {
        $dir = $this->_folders;
        $name = str_replace(JPATH_ROOT.'/'.BaformsHelper::$image_path, '', $dir);
        $folders = Folder::folders($dir);
        $items = [];
        foreach ($folders as $folder) {
            $obj = new \stdClass();
            $obj->path = $name. '/' .$folder;
            $obj->name = $folder;
            $this->_folders = $dir. '/' .$folder;
            $obj->childs = $this->getFolderList();
            $items[] = $obj;
        }

        return $items;
    }

    public function getBreadcrumb()
    {
        $dir = JPATH_ROOT.'/'.BaformsHelper::$image_path;
        $this->_folders = $dir;
        $input = Factory::getApplication()->input;
        $name = $input->get('folder', '', 'string');
        $dir .= $name;
        $breadcrumb = array();
        if (!empty($name)) {
            $array = explode('/', $name);
            $path = '';
            foreach ($array as $value) {
                if (!empty($value)) {
                    $obj = new \stdClass();
                    $path .= '/'.$value;
                    $obj->path = $path;
                    $obj->title = $value;
                    $breadcrumb[] = $obj;
                }
            }
        }

        return $breadcrumb;
    }
    
    public function getFolders()
    {
        $dir = JPATH_ROOT.'/'.BaformsHelper::$image_path;
        $this->_folders = $dir;
        $input = Factory::getApplication()->input;
        $name = $input->get('folder', '', 'string');
        $dir .= $name;
        $items = array();
        if ($dir != JPATH_ROOT.'/'.BaformsHelper::$image_path) {
            $this->_parent = $dir;
        }
        $folders = Folder::folders($dir);
        if (!empty($folders)) {
            foreach ($folders as $folder) {
                $obj = new \stdClass();
                $obj->path = $name. '/' .$folder;
                $obj->name = $folder;
                $items[] = $obj;
            }
        }

        return $items;
    }

    public function getImages(): array
    {
        $dir = JPATH_ROOT . '/' . BaformsHelper::$image_path;
        $url = Uri::root() . BaformsHelper::$image_path;
        $input = Factory::getApplication()->input;
        $name = $input->get('folder', '', 'string');
        if ($name == "undefined") {
            $name = '';
        }

        if (!empty($name)) {
            $dir .= $name;
            $url .= $name;
        }
        $files = Folder::files($dir);
        $images = [];
        $types = $this->getFiletypes();
        foreach ($files as $file) {
            if ($file == '.' || $file == '..') {
                continue;
            }

            $ext = File::getExt($file);
            if (!in_array($ext, $types)) {
                continue;
            }

            $images[] = (object) [
                'ext' => $ext,
                'name' => $file,
                'path' => $name. '/' .$file,
                'size' => filesize($dir.'/'.$file),
                'url' => $url. '/' .$file,
            ];
        }

        return $images;
    }

    public function getBaseFolder(): string
    {
        return JPATH_ROOT . '/' . BaformsHelper::$image_path;
    }

    public function isPathInsideBaseDirectory(string $path, $isReal = false): bool
    {
        $basePath = $this->getBaseFolder();

        $realBase = realpath($basePath);
        $realPath = !$isReal ? realpath(JPATH_ROOT . "/$path") : $path;

        if ($realBase === false || $realPath === false) {
            return false;
        }

        return str_starts_with($realPath, $realBase);
    }

    public function isImage($ext): bool
    {
        return in_array($ext, $this->images);
    }

    public function getFiletypes(): array
    {
        $params = ComponentHelper::getParams('com_baforms');
        $default = 'csv, doc, gif, ico, jpg, jpeg, pdf, png, txt, xls, svg, mp4, webp';
        $files = $params->get('allowed_file_types', $default);
        $array = explode(',', $files);
        foreach ($array as $key => $value) {
            $value = trim($value);
            $value = strtolower($value);
            $array[$key] = $value;
        }

        return $array;
    }
}
