<?php


class SupsysticTablesPro_Exporter_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();
		$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&nonce='.wp_create_nonce('dtgs_nonce'),
                    $slug,
                    $type,
					$id
                )
            )
        ));
    }

    public function export(RscDtgs_Http_Request $request)
    {
      if (!$this->_checkNonce($request) && !$this->_checkNonceFrontend($request)) die();
		$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',
      'full_width' => $type == 'pdf' && !empty($request->post['full_width'])? $request->post['full_width'] : '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)) {
				$visibleRows = json_decode($rows);
				$table->rows = $tables->getRowsByIds($id, $table->settings, $visibleRows, $sqlValues);
				if(!empty($table->meta['mergedCells'])) {
					$mergedCells = $table->meta['mergedCells'];
					$correctMerged = array();
					foreach($mergedCells as $mc) {
						$firstRow = $mc['row'] + 1;
						$lastRow = $firstRow + $mc['rowspan'] - 1;
						$rowspan = 0;
						for($r = $firstRow; $r <= $lastRow; $r++) {
							$rowNum = array_search($r, $visibleRows);
							if($rowNum !== false) {
								if($rowspan == 0) {
									$firstRow = $rowNum;
								}
								$rowspan++;
							}
						}
						if($rowspan > 0) {
							if($rowspan > 1 || $mc['colspan'] > 1) {
								$mc['rowspan'] = $rowspan;
								$mc['row'] = $firstRow;
								$correctMerged[] = $mc;
							}
						}
					}
					$table->meta['mergedCells'] = $correctMerged;
				}
			} 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');
    }
}
