<?php
/**
 * @package   Essentials YOOtheme Pro 2.2.16 build 0813.1608
 * @author    ZOOlanders https://www.zoolanders.com
 * @copyright Copyright (C) Joolanders, SL
 * @license   http://www.gnu.org/licenses/gpl.html GNU/GPL
 */

namespace ZOOlanders\YOOessentials\Form\Action\SaveCsv;

use RuntimeException;
use ZOOlanders\YOOessentials\Form\Action\ActionConfigurationException;
use ZOOlanders\YOOessentials\Form\Action\SaveToAction;
use ZOOlanders\YOOessentials\Form\Http\FormSubmissionResponse;

class SaveCsvAction extends SaveToAction
{
    use InteractsWithCsv;

    public const NAME = 'save-csv';

    public function __invoke(FormSubmissionResponse $response, callable $next): FormSubmissionResponse
    {
        $config = (object) $this->getConfig();
        $data = $this->resolveData($config->content ?? []);

        try {
            $headers = self::readCsvHeader($config);
            $data = self::sortDataFromHeaders($headers, $data);
            self::writeCsv($data, $config);
        } catch (RuntimeException $e) {
            throw ActionConfigurationException::create($this, $e->getMessage(), $e);
        }

        return $next(
            $response->withDataLog([
                self::NAME => [
                    'config' => $config,
                    'data' => $data,
                ],
            ])
        );
    }
}
