<?php

namespace Drupal\simple_interactive_maps\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use function fclose;
use function fopen;
use function fputcsv;

/**
 * Base class for data export controllers.
 */
abstract class DataExportControllerBase extends ControllerBase {

  /**
   * Generic function to write a csv to a temporary file and return it.
   *
   * @param array $data
   *   File data.
   * @param array $headers
   *   File headers.
   * @param string $filename
   *   Filename to download as.
   */
  protected function exportCsvFile(array $data, array $headers, string $filename): BinaryFileResponse {

    $filePath = 'temporary://' . $filename;
    $fh = fopen($filePath, 'w');
    fputcsv($fh, $headers);

    foreach ($data as $row) {
      \fputcsv($fh, $row);
    }

    fclose($fh);

    $response = new BinaryFileResponse($filePath);
    $response->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $filename);
    $response->setPrivate();

    return $response;
  }

}
