<?php


class SupsysticTablesPro_Exporter_Type_Csv implements SupsysticTablesPro_Exporter_Interface
{
    /**
     * Exports specified data.
     * @param array $data
     * @return mixed
     * @throws \SupsysticTablesPro_Exporter_Exception
     */
    public function export(array $data)
    {
        $letters = range('A', 'Z');
		$prefix = array_merge(array(''), $letters);
		$countIndex = 0;
		$letterIndex = 0;
        $excel = new PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $excel->getActiveSheet();

        foreach ($data['table']->rows as $rowIndex => $row) {
            foreach ($row['cells'] as $colIndex => $cell) {
				//echo '<pre>'; print_r($cell); echo '</pre>';
                if (strpos($cell['data'], '%3C') !== false) {
                    $cell['data'] = urldecode($cell['data']);
                }

                if (strpos($cell['data'], '&#') !== false) {
                    $cell['data'] = html_entity_decode($cell['data']);
                }

                $cell['data'] = preg_replace('/<a href="#" class="delete-upload-file" title="(.*?)">(.*?)<\/a>/', '', $cell['data']);

                $cellIndex = $prefix[$countIndex] . $letters[$letterIndex] . ($rowIndex + 1);
                $sheet->setCellValue($cellIndex, addslashes($cell['data']));

                if ($sheet->getCell($cellIndex)->isFormula()) {
					$cellValue = str_replace(';', ',', $cell['data']);
					$sheet->setCellValue($cellIndex, $cellValue);
				}

				if($letters[$letterIndex] == 'Z') {
					$letterIndex = 0;
					$countIndex++;
				} else {
					$letterIndex++;
				}
            }
			$letterIndex = 0;
			$countIndex = 0;
        }
        //die;

        $writer = PhpOffice\PhpSpreadsheet\IOFactory::createWriter($excel, 'Csv')
            ->setDelimiter(';')
            ->setEnclosure('')
            ->setLineEnding("\r\n");
        $writer->save('php://output');
    }
}
