<?php


class SupsysticTablesPro_Importer_Controller extends SupsysticTables_Core_BaseController
{
    /**
     * @param \RscDtgs_Http_Request $request
     * @return \RscDtgs_Http_Response
     */
    public function importAction(RscDtgs_Http_Request $request)
    {
        $this->includePHPExcel();
        $importer  = $this->getImporter();
        $settings  = $request->post->get('settings', array());
        $extension = $request->post->get('extension');
        $id        = $request->post->get('id');
        $file      = $request->files->get('file');
        $isAdmin   = is_admin();

        try {
            // check for ability do export to xlsx excell format
            if (in_array($extension, array(
                'xls',
                'xlsx',
                'spreadsheets'
            )) && !class_exists('ZipArchive')) {
                throw new SupsysticTablesPro_Importer_Exception($this->translate('You need to enable ZipArchive extension in PHP config file on your server. Please, contact to your server administrator.'));
            }
            if ($extension == 'spreadsheets') {
                $importer->importSpreadheets($id, $settings);
            } else {
                $importer->import($id, $file, $settings);
            }
            $this->getEnvironment()->getModule('tables')->getController()->cleanCache($id);
        }
        catch (SupsysticTablesPro_Importer_Exception_Upload $e) {
            if ($isAdmin) {
                return $this->response('@importer/upload_error.twig', array(
                    'error' => $e
                ));
            } else {
                $this->getModule()->setFrontendImportErrorMsg($e->getMessage());
            }
        }
        catch (SupsysticTablesPro_Importer_Exception_UnsupportedType $e) {
            if ($isAdmin) {
                return $this->response('@importer/unsupported_type_error.twig', array(
                    'error' => $e
                ));
            } else {
                $this->getModule()->setFrontendImportErrorMsg($e->getMessage());
            }

        }
        catch (SupsysticTablesPro_Importer_Exception $e) {
            if ($isAdmin) {
                return $this->response('@importer/error.twig', array(
                    'error' => $e
                ));
            } else {
                $this->getModule()->setFrontendImportErrorMsg($e->getMessage());
            }
        }

        if ($isAdmin) {
            return $this->redirect($this->generateUrl('tables', 'view', array(
                'id' => $id,
                'nonce' => wp_create_nonce('dtgs_nonce')
            )));
        } else {
            if (isset($_SERVER['REQUEST_URI'])) {
                return $this->redirect($_SERVER['REQUEST_URI']);
            }
        }
    }

    /**
     * @return SupsysticTablesPro_Importer_Module
     */
    protected function getModule()
    {
        $resolver = $this->getEnvironment()->getResolver();

        return $resolver->getModulesList()->get('importer');
    }

    /**
     * @return \SupsysticTablesPro_Importer_Model_Importer
     */
    public function getImporter()
    {
        /** @var SupsysticTables_Core_Module $core */
        $core    = $this->getEnvironment()->getModule('core');
        $factory = $core->getModelsFactory();

        return $factory->get('importer', $this->getModule());
    }

    public function includePHPExcel()
    {
        if (!class_exists('PhpOffice\PhpSpreadsheet\Spreadsheet')) {
            $config = $this->getEnvironment()->getConfig();
            require_once dirname($config->get('pro_modules_path')) . '/vendor/PHPOffice/PhpSpreadsheet/Autoloader.php';
            require_once dirname($config->get('pro_modules_path')) . '/vendor/PHPOffice/PhpSpreadsheet/Spreadsheet.php';
        }
    }
}
