<?php


class SupsysticTablesPro_Migration_Controller extends SupsysticTables_Core_BaseController
{
    /**
     * Generates download url.
     * @param \RscDtgs_Http_Request $request
     * @return \RscDtgs_Http_Response
     */
    public function generateUrlAction(RscDtgs_Http_Request $request)
    {
        if (!$this->_checkNonce($request))
            die();
        $id = $request->post->get_esc_html('id');

        $slug = $this->getEnvironment()->getMenu()->getMenuSlug();

        return $this->ajaxSuccess(array(
            'url' => admin_url(sprintf('admin.php?page=%s&module=migration&migration-supsystic-table=true&id=%s', $slug, $id))
        ));
    }

    public function export(RscDtgs_Http_Request $request)
    {
        if (!$this->_checkNonce($request))
            die();
        $id  = $request->query->get_esc_html('id');
        $ids = explode(';', $id);
        if (!is_array($ids)) {
            wp_die(sprintf($this->translate('The table IDs %s not found.'), $id));
        }
        $tables   = $this->getModel('tables');
        $exporter = $this->getModel('exporter', $this->getModule());
        foreach ($ids as $i => $id) {
            $table = $tables->getById((int) $id);
            if (null === $table) {
                wp_die(sprintf($this->translate('The table ID %s not found.'), $id));
            }
        }
        $exporter->export($ids);
        die;

    }

    public function importAction(RscDtgs_Http_Request $request)
    {
        if (!$this->_checkNonce($request))
            die();
        $file     = $request->files->get('file');
        $importer = $this->getModel('importer', $this->getModule());
        try {
            $importer->import($file);
        }
        catch (SupsysticTablesPro_Migration_Exception_Upload $e) {
            return $this->response('@migration/upload_error.twig', array(
                'error' => $e
            ));
        }

        return $this->redirect($this->generateUrl('tables', 'index', array(
            'nonce' => wp_create_nonce('dtgs_nonce')
        )));
    }

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

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