<?php

namespace Drupal\simple_interactive_maps\Form;

use Drupal\Core\File\FileExists;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Base class for data import forms.
 */
abstract class DataImportFormBase extends FormBase {

  /**
   * File upload validation function.
   *
   * @param array $element
   *   File upload form element.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   Form state data.
   */
  public function validateFileUpload(array &$element, FormStateInterface $form_state): void {

    $fieldId = $this->getUploadFieldId();

    $file = file_save_upload($fieldId, [
      'FileExtension' => ['extensions' => 'csv CSV'],
    ], FALSE, 0, FileExists::Replace);
    if ($file) {
      $form_state->setValue($fieldId, $file);
    }
    else {
      $form_state->setError($element, $this->t('File upload failed.'));
    }
  }

  /**
   * Abstract function to define which field in the form contains the file.
   *
   * @return string
   *   Form field id.
   */
  abstract protected function getUploadFieldId(): string;

}
