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

namespace Balbooa\Component\Gridbox\Site\Controller;

defined('_JEXEC') or die;

use Balbooa\Component\Gridbox\Administrator\Helper\Filesystem\File;
use Balbooa\Component\Gridbox\Administrator\Helper\Filesystem\Folder;
use Balbooa\Component\Gridbox\Site\Helper\GridboxHelper;
use Joomla\Archive\Archive;
use Joomla\CMS\Factory;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\FormController;

class IconsController extends FormController
{
    public function getModel($name = 'Icons', $prefix = 'Site', $config = ['ignore_request' => false])
	{
		return parent::getModel($name, $prefix, $config);
	}

    public function addCustomIcons()
    {
        GridboxHelper::checkUserEditLevel();
        $model = $this->getModel();
        $obj = new \stdClass();
        $input = Factory::getApplication()->input;
        $icon = $name = $input->get('icon_name', '', 'string');
        $name = str_replace(' ', '+', $name);
        $file = GridboxHelper::replace($name);
        $file = File::makeSafe($file.'.zip');
        $name = str_replace('-', '', $file);
        $name = str_replace('zip', '', $name);
        $name = str_replace('.', '', $name);
        if ($name == '') {
            $file = date("Y-m-d-H-i-s").'.zip';
        }
        $name = strtolower($file);
        $fileName = str_replace('.zip', '', $name);
        $dir = JPATH_ROOT. '/templates/gridbox/library/icons/custom-icons';
        if (!Folder::exists($dir)) {
            Folder::create($dir);
        }
        if (Folder::exists($dir.'/'.$fileName)) {
            $obj->msg = Text::_('ICONS_ALREADY_INSTALLED');
            $obj->type = 'ba-alert';
        } else {
            $input = Factory::getApplication()->input;
            $files = $_FILES['custom-files'];
            move_uploaded_file($files['tmp_name'], $dir.'/'.$name);
            if (!Folder::exists($dir.'/tmp')) {
                Folder::create($dir.'/tmp');
            }
            Folder::create($dir.'/'.$fileName);
            $archive = new Archive();
            $archive->extract($dir.'/'.$name, $dir.'/tmp/'.$fileName);
            File::delete($dir.'/'.$name);
            $model->installIcons($fileName, $icon);
            GridboxHelper::deleteFolder($dir.'/tmp');
            $obj->msg = Text::_('ICONS_IS_ADDED');
            $obj->type = '';
        }
        echo json_encode($obj);
        exit;
    }
    
    public function delete()
    {
        GridboxHelper::checkUserEditLevel();
        $model = $this->getModel();
        $model->delete();
        echo Text::_('COM_GRIDBOX_N_ITEMS_DELETED');
        exit;
    }
}