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

defined('_JEXEC') or die;

use Balbooa\Component\Gridbox\Administrator\Helper\Filesystem\File;
use Balbooa\Component\Gridbox\Administrator\Helper\GridboxHelper;
use Balbooa\Component\Gridbox\Administrator\Trait\BulkActionsControllerTrait;
use Balbooa\Component\Gridbox\Site\Helper\AssetsHelper;
use Joomla\Archive\Archive;
use Joomla\CMS\Factory;
use Joomla\CMS\Installer\Installer;
use Joomla\CMS\Language\Text;
use Joomla\CMS\MVC\Controller\AdminController;

class PagesController extends AdminController
{
    use BulkActionsControllerTrait;

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

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

    public function orderPages()
    {
        GridboxHelper::checkUserEditLevel();
        $model = $this->getModel();
        $model->orderPages();
        exit();
    }

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

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

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

    public function checkBlogsTour()
    {
        GridboxHelper::checkUserEditLevel();
        $model = $this->getModel();
        $model->checkBlogsTour();
    }

    public function checkSidebarTour()
    {
        GridboxHelper::checkUserEditLevel();
        $model = $this->getModel();
        $model->checkSidebarTour();
    }

    public function addTrash()
    {
        $pks = $this->input->getVar('cid', [], 'post', 'array');
        $flag = true;
        foreach ($pks as $pk) {
            $assets = new AssetsHelper($pk, 'page');
            $flag = $assets->checkPermission('core.delete');
            if (!$flag) {
                break;
            }
        }
        if ($flag) {
            $model = $this->getModel();
            $model->trash($pks);
            GridboxHelper::ajaxReload($this->text_prefix . '_N_ITEMS_TRASHED');
        } else {
            GridboxHelper::ajaxReload('JERROR_CORE_DELETE_NOT_PERMITTED');
        }
    }

    public function contextTrash()
    {
        $input = Factory::getApplication()->input;
        $id = $input->get('context-item', 0, 'int');
        $assets = new AssetsHelper($id, 'page');
        $flag = $assets->checkPermission('core.delete');
        if ($flag) {
            $array = [];
            $array[] = $id;
            $model = $this->getModel();
            $model->trash($array);
            GridboxHelper::ajaxReload($this->text_prefix.'_N_ITEMS_TRASHED');
        } else {
            GridboxHelper::ajaxReload('JERROR_CORE_DELETE_NOT_PERMITTED');
        }
    }

    public function checkGridboxState()
    {
        $state = GridboxHelper::checkGridboxState();
        print_r($state);exit();
    }

    public function getAppLicense()
    {
        GridboxHelper::checkUserEditLevel();
        $input = Factory::getApplication()->input;
        $data = $input->get('data', '', 'string');
        GridboxHelper::setAppLicense($data);
        GridboxHelper::setAppLicenseBalbooa($data);
        GridboxHelper::ajaxReload('SUCCESS_INSTALL');
    }

    public function addPlugins()
    {
        GridboxHelper::checkUserEditLevel();
        $input = Factory::getApplication()->input;
        $plugins = $input->get('plugins', '', 'string');
        $data = json_decode($plugins);
        $db = Factory::getDbo();
        foreach ($data as $group) {
            foreach ($group as $plugin) {
                $db->insertObject('#__gridbox_plugins', $plugin);
            }
        }
    }

    public function applySingle()
    {
        GridboxHelper::checkUserEditLevel();
        $model = $this->getModel();
        $model->applySingle();
    }

    public function deleteGridboxAppItem()
    {
        GridboxHelper::checkUserEditLevel();
        $model = $this->getModel();
        $model->deleteApp();
    }

    public function deleteApp()
    {
        $input = Factory::getApplication()->input;
        $id = $input->get('blog', 0, 'int');
        $user = Factory::getUser();
        if ($user->authorise('core.delete.app.'.$id, 'com_gridbox')) {
            $model = $this->getModel();
            $model->deleteApp();
            $this->setRedirect('index.php?option=com_gridbox');
            GridboxHelper::ajaxReload('COM_GRIDBOX_N_ITEMS_DELETED');
        } else {
            GridboxHelper::ajaxReload('JERROR_CORE_DELETE_NOT_PERMITTED');
        }
    }

    public function duplicateApp()
    {
        GridboxHelper::checkUserEditLevel();
        $model = $this->getModel();
        $model->duplicateApp();
        GridboxHelper::ajaxReload('GRIDBOX_DUPLICATED');
    }

    public function addApp()
    {
        GridboxHelper::checkUserEditLevel();
        $input = Factory::getApplication()->input;
        $type = $input->get('type', '', 'string');
        $model = $this->getModel();
        $id = $model->addApp($type);
        if ($type != 'single') {
            $model = $this->getModel('category');
            $model->createCat('Uncategorised', $id);
        }
        if ($type == 'products') {
            $appslist = $this->getModel('appslist');
            $appslist->addSystemApp('reviews');
        }
        exit();
    }

    public function publish()
    {
        $cid = Factory::getApplication()->input->get('cid', [], 'array');
        $task = $this->getTask();
        if ($task != 'unpublish') {
            $value = 1;
            $text = $this->text_prefix . '_N_ITEMS_PUBLISHED';
        } else {
            $value = 0;
            $text = $this->text_prefix . '_N_ITEMS_UNPUBLISHED';
        }
        $flag = true;
        foreach ($cid as $pk) {
            $assets = new AssetsHelper($pk, 'page');
            $flag = $assets->checkPermission('core.edit.state');
            if (!$flag) {
                break;
            }
        }
        if ($flag) {
            $model = $this->getModel();
            $model->publish($cid, $value);
            $model->sendSubmissionEmail($cid, $value);
            GridboxHelper::triggerEvent('onGidboxPagesAfterPublish', [$cid], 'finder');
        } else {
            $text = 'JLIB_APPLICATION_ERROR_EDITSTATE_NOT_PERMITTED';
        }
        GridboxHelper::ajaxReload($text);
    }

    public function checkRate()
    {
        GridboxHelper::checkUserEditLevel();
        $model = $this->getModel();
        $model->checkRate();
    }

    public function contextDuplicate()
    {
        GridboxHelper::checkUserEditLevel();
        $input = Factory::getApplication()->input;
        $id = $input->get('context-item', 0, 'int');
        $array = [$id];
        $model = $this->getModel();
        $model->duplicate($array);
        GridboxHelper::ajaxReload('GRIDBOX_DUPLICATED');
    }
    
    public function duplicate()
    {
        GridboxHelper::checkUserEditLevel();
        $pks = $this->input->getVar('cid', [], 'post', 'array');
        $model = $this->getModel();
        $model->duplicate($pks);
        GridboxHelper::ajaxReload('GRIDBOX_DUPLICATED');
    }
    
    public function updateGridbox()
    {
        GridboxHelper::checkUserEditLevel();
        $config = Factory::getConfig();
        $path = $config->get('tmp_path').'/pkg_Gridbox.zip';
        $data = file_get_contents('php://input');
        $obj = json_decode($data);
        $method = $obj->method;
        $data = $method($obj->package);
        $file = fopen($path, "w+");
        fputs($file, $data);
        fclose($file);
        $this->extract($path, $config->get('tmp_path').'/pkg_Gridbox');
        $installer = Installer::getInstance();
        $installer->update($config->get('tmp_path').'/pkg_Gridbox');
        File::delete($path);
        GridboxHelper::deleteFolder($config->get('tmp_path').'/pkg_Gridbox');
        exit;
    }
    
    public function exportXML()
    {
        GridboxHelper::checkUserEditLevel();
        $model = $this->getModel();
        $model->exportXML();
    }

    public function download()
    {
        $file = $this->input->get('file', '', 'string');
        if (file_exists($file)) {
            header('Content-Description: File Transfer');
            header('Content-Type: application/octet-stream');
            header('Content-Disposition: attachment; filename=gridbox.xml');
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: '.filesize($file));
            readfile($file);
            exit;
        }
    }
}