<?php


class SupsysticTablesPro_Exporter_Controller extends SupsysticTables_Core_BaseController
{
	/**
     * Generates download url.
     * @param \Rsc_Http_Request $request
     * @return \Rsc_Http_Response
     */
    public function generateUrlAction(Rsc_Http_Request $request)
    {
		$id = $request->post->get_esc_html('id');
		$slug = $this->getEnvironment()->getMenu()->getMenuSlug();
		$type = $request->post->get_esc_html('type', 'csv');

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

    public function export(Rsc_Http_Request $request)
    {
		$type = $request->query->get_esc_html('type');
		$export_data = array(
			'type' => $type,
			'title' => $type == 'pdf' ? $request->post['title'] : 'table',
			'table' => null,
			'values_only' => false,
			'pdf-table-data' => $type == 'pdf' && !empty($request->post['pdf-table-data']) ? $request->post['pdf-table-data'] : '',
			'columns' => $type == 'pdf' && !empty($request->post['columns']) ? $request->post['columns'] : 10,
			'paper_size' => $type == 'pdf' && !empty($request->post['paper_size'])? $request->post['paper_size'] : 'auto',
			'orientation' => $type == 'pdf' && !empty($request->post['orientation'])? $request->post['orientation'] : 'portrait',
			'export_fonts' => $type == 'pdf' && !empty($request->post['export_font'])? $request->post['export_fonts'] : 'off',
		);

		if($export_data['type'] != 'pdf') {
			// csv, xls, xlsx, xls_values, xlsx_values
			if(in_array($export_data['type'], array('xls_values', 'xlsx_values'))) {
				// export without html and formulas
				$export_data['values_only'] = true;
				$export_data['type'] = str_replace('_values', '', $export_data['type']);
			}
			// check for ability do export to xlsx excel format
			if($export_data['type'] === 'xlsx' && !class_exists('ZipArchive')) {
				wp_die($this->translate('You need to enable ZipArchive extension in PHP config file on your server. Please, contact to your server administrator.'));
			}

			$id = (int)$request->query->get_esc_html('id');
			
			$tables = $this->getModel('tables');
			$table = $tables->getById($id);

			$rows = $request->post['rows'];
			$sqlValues = $request->post['sql'];
			if(isset($sqlValues) && !empty($sqlValues)) {
				$sqlValues = json_decode($sqlValues, true);
			} else {
				$sqlValues = false;
			}
			if(isset($table->settings['exportOnlyVisible']) && $table->settings['exportOnlyVisible'] == 'on' && isset($rows)) {
				$table->rows = $tables->getRowsByIds($id, $table->settings, json_decode($rows), $sqlValues);
			} else {
				$table->rows = $tables->getNeededRows($id, $table->settings, false, $sqlValues, true);
			}

			$export_data['table'] = $table;

			if (null === $export_data['table']) {
				wp_die(sprintf($this->translate('The table ID %s not found.'), $id));
			}
			$export_data['title'] = $export_data['table']->title;
		}
		// Init export
		$this->getModel('exporter', $this->getModule())->export($export_data['type'], $export_data);
        die;
    }

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

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