<?php

use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class Rtga_export extends Rtgrid_top_action implements \SplObserver
{
    private $columns;

    public function __construct($name = '', $text = '', $callback = '', $message = '')
    {
        $name = empty($name) ? 'export' : $name;
        $text = empty($text) ?
            '<a href="?export=1" class="btn"><i class="fa fa-cloud-download"></i> ' . get_instance()->lang->line('Export') . '</a>'
            : $text;

        parent::__construct($name, $text, $callback, $message);
    }

    /**
     * @param $columns string
     * @return $this
     */
    public function set_columns($columns)
    {
        $this->columns = $columns;
        return $this;
    }

    public function update(SplSubject $subject)
    {
        $event_name = $subject->get_event_name();

        if ($event_name == 'POST_RENDER' && get_instance()->input->get('export')) {
            $subject->columns($this->columns);
            $display_as = $subject->get_option('_display_as');

            $spreadsheet = new Spreadsheet();
            $spreadsheet->getProperties()->setCreator('Ciext');
            $sheet = $spreadsheet->getActiveSheet();

            // Add head
            if (!empty($this->columns)) {
                $column = 1;
                foreach (explode(',', $this->columns) as $value) {
                    $value = !empty($display_as[trim($value)]) ? $display_as[trim($value)] : ucfirst($value);
                    $sheet->setCellValueByColumnAndRow($column, 1, $value);
                    $column++;
                }
            }

            // Add data
            $row = 2;
            foreach ($subject->export() as $item) {
                $column = 1;
                foreach ($item as $value) {
                    $sheet->setCellValueByColumnAndRow($column, $row, $value);
                    $column++;
                }
                $row++;
            }

            header('Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="export_' . date('Y-m-d') . '.xlsx"');
            header('Cache-Control: max-age=0');

            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');

            exit;
        }
    }
}