<?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\Controller;

defined('_JEXEC') or die;

use Balbooa\Component\Forms\Administrator\Controller\Trait\HasDownloadFile;
use Balbooa\Component\Forms\Administrator\Controller\Trait\HasSessionTokenCheck;
use Balbooa\Component\Forms\Administrator\Helper\AccessGuard;
use Balbooa\Component\Forms\Administrator\Helper\BaformsHelper;
use Balbooa\Component\Forms\Administrator\Helper\ExtensionInfo;
use Balbooa\Component\Forms\Administrator\Helper\Filesystem\File;
use Balbooa\Component\Forms\Administrator\Helper\Filesystem\Folder;
use Joomla\CMS\MVC\Controller\AdminController;
use Joomla\CMS\Language\Text;
use Joomla\Archive\Archive;
use Joomla\CMS\Factory;
use Joomla\CMS\Installer\Installer;

class FormsController extends AdminController
{
    use HasSessionTokenCheck;
    use HasDownloadFile;

    public function getModel($name = 'Form', $prefix = 'Administrator', $config = ['ignore_request' => true])
    {
        return parent::getModel($name, $prefix, $config);
    }

    public function pasteDesign()
    {
        AccessGuard::check('core.edit');

        $model = $this->getModel();
        $id = $this->input->get('id', 0, 'int');
        $str = $this->input->get('design', '{}', 'raw');
        $design = json_decode($str);
        $model->pasteDesign($id, $design);
        echo Text::_('DESIGN_PASTED_SUCCESSFULLY');
        exit;
    }

    public function getFormDesign()
    {
        $model = $this->getModel();
        $id = $this->input->get('id', 0, 'int');
        $options = $model->getFormOptions();
        $settings = BaformsHelper::getFormsSettings($id, $options);
        print_r($settings->design);exit;
    }

    public function delete()
    {
        AccessGuard::check('core.delete');
        $cid = $this->input->get('cid', [], 'array');
        $model = $this->getModel();
        $model->delete($cid);
        echo Text::_($this->text_prefix.'_N_ITEMS_DELETED');
        exit;
    }

    public function versionCompare()
    {
        $about = ExtensionInfo::get();
        $version = $this->input->get('version', '', 'string');
        $compare = version_compare($about->version, $version);
        echo $compare;
        exit();
    }

    public function checkFormsState()
    {
        $state = BaformsHelper::checkFormsState();
        print_r($state);exit();
    }

    public function getUserLicense()
    {
        $input = Factory::getApplication()->input;
        $data = $input->get('data', '', 'string');
        BaformsHelper::setAppLicense($data);
    }

    public function setFilters()
    {
        $input = Factory::getApplication()->input;
        $view = $input->get('view', '', 'string');
        $model = $this->getModel($view);
        $model->populateState();
        exit;
    }

    public function restore()
    {
        AccessGuard::check('core.edit');

        $pks = $this->input->getVar('cid', [], 'post', 'array');
        $model = $this->getModel();
        $model->restore($pks);
        echo Text::_('ITEMS_RESTORED');
        exit;
    }

    public function trash()
    {
        AccessGuard::check('core.delete');

        $pks = $this->input->getVar('cid', [], 'post', 'array');
        $model = $this->getModel();
        $model->publish($pks, -2);
        echo Text::_('COM_BAFORMS_N_ITEMS_TRASHED');
        exit;
    }

    public function publish()
    {
        AccessGuard::check('core.edit.state');

        $cid = Factory::getApplication()->input->get('cid', [], 'array');
        $task = $this->getTask();
        switch ($task) {
            case 'trash':
                $value = -2;
                $text = 'COM_BAFORMS_N_ITEMS_TRASHED';
                break;
            case 'unpublish':
                $value = 0;
                $text = 'COM_BAFORMS_N_ITEMS_UNPUBLISHED';
                break;
            default:
                $value = 1;
                $text = 'COM_BAFORMS_N_ITEMS_PUBLISHED';
                break;
        }
        $model = $this->getModel();
        $model->publish($cid, $value);
        echo Text::_($text);
        exit;
    }

    public function contextDuplicate()
    {
        AccessGuard::check('core.duplicate');

        $id = $this->input->get('id', 0, 'int');
        $model = $this->getModel();
        $model->duplicate([$id]);
        echo Text::_('FORM_DUPLICATED');
        exit;
    }

    public function contextRename()
    {
        AccessGuard::check('core.edit');

        $id = $this->input->get('id', 0, 'int');
        $title = $this->input->get('title', '', 'string');
        $model = $this->getModel();
        $model->rename($id, $title);
        echo Text::_('ITEM_SUCCESSFULLY_RENAMED');
        exit;
    }

    public function contextTrash()
    {
        AccessGuard::check('core.delete');

        $id = $this->input->get('id', 0, 'int');
        $model = $this->getModel();
        $pks = [$id];
        $model->publish($pks, -2);
        echo Text::_('COM_BAFORMS_N_ITEMS_TRASHED');
        exit;
    }
    
    public function duplicate()
    {
        AccessGuard::check('core.duplicate');

        $pks = $this->input->getVar('cid', [], 'post', 'array');
        $model = $this->getModel();
        $model->duplicate($pks);
        echo Text::_('FORM_DUPLICATED');
        exit;
    }
    
    public function updateForms()
    {
        AccessGuard::check('core.admin');

        $config = Factory::getConfig();
        $path = $config->get('tmp_path').'/pkg_BaForms.zip';
        $package = $this->input->get('package', '', 'raw');
        $data = base64_decode($package);
        $file = fopen($path, "w+");
        fputs($file, $data);
        fclose($file);
        $this->extract($path, $config->get('tmp_path').'/pkg_BaForms');
        $installer = Installer::getInstance();
        $installer->update($config->get('tmp_path').'/pkg_BaForms');
        File::delete($path);
        Folder::delete($config->get('tmp_path').'/pkg_BaForms');
        exit;
    }

    public function addLanguage()
    {
        AccessGuard::check('core.admin');

        $url = $this->input->get('url', '', 'string');
        $zip = $this->input->get('zip', '', 'string');
        $name = explode('/', $url);
        $name = end($name);
        $config = Factory::getConfig();
        $tmp_path = $config->get('tmp_path');
        $path = $tmp_path.'/'.$name;
        $name = explode('.', $name);
        $data = base64_decode($zip);
        $file = fopen($path, "w+");
        fputs($file, $data);
        fclose($file);
        $this->extract($path, $tmp_path.'/'.$name[0]);
        $installer = Installer::getInstance();
        $installer->install($tmp_path.'/'.$name[0]);
        File::delete($path);
        Folder::delete($tmp_path.'/'.$name[0]);
        echo Text::_('SUCCESS_INSTALL');
        exit;
    }

    public function addLibrary()
    {
        $folder = $this->input->get('folder', '', 'string');
        $zip = $this->input->get('zip', '', 'string');
        $package = $this->input->get('package', '', 'string');
        $data = base64_decode($package);
        $path = JPATH_ROOT.'/components/com_baforms/libraries/';
        $file = fopen($path.$zip, "w+");
        fputs($file, $data);
        fclose($file);
        $this->extract($path.$zip, $path.$folder);
        File::delete($path.$zip);
        echo Text::_('SUCCESS_INSTALL');
        exit;
    }

    public function extract($from, $to)
    {
        $archive = new Archive();
        $archive->extract($from, $to);
    }

    public function exportForms()
    {
        $model = $this->getModel();
        $model->exportForms();
    }

    public function exportForm()
    {
        AccessGuard::check('core.edit');

        $input = Factory::getApplication()->input;
        $export = $input->get('export_id', '', 'string');
        $cid = explode(';', $export);
        $model = $this->getModel();
        $model->exportForm($cid);
    }

    public function download()
    {
        $this->downloadFile('forms.xml');
    }

    public function importForms()
    {
        AccessGuard::check('core.edit');

        $model = $this->getModel();
        $files = $this->input->files->get('ba-files', '', 'array');
        foreach ($files as $item) {
            $name = JPATH_ROOT.'/tmp/'.$item['name'];
            if (!File::upload($item['tmp_name'], $name)) {
                echo Text::_('UPLOAD_ERROR');
                exit;
            }
        }
        $xml = simplexml_load_file($name);
        $model->importForms($xml);
        echo Text::_('SUCCESS_UPLOAD');
        exit;
    }
}