<?php

/**
 * @param $form
 * @param $form_state
 *
 * @return mixed
 */
function corpus_config_form($form, &$form_state) {

  $site_name = variable_get('site_name');
  //var_dump($site_name);
  $form['site_information']['site_name'] = [
    '#type' => 'textfield',
    '#title' => t('Site name'),
    '#default_value' => variable_get('site_name', 'Drupal'),
    '#required' => TRUE,
  ];
  $form['header_background_color'] = [
    '#type' => 'textfield',
    '#title' => t('Couleur de la bannière'),
    '#description' => t('Code hexadécimal'),
    '#default_value' => variable_get('header_background_color', '#0085cb'),
    '#required' => TRUE,
  ];
  //  $form['#attributes']['enctype'] = "multipart/form-data";
  $url_file_exixt = variable_get('header_image');
  $form['header_image'] = [
    '#type' => 'managed_file',
    '#title' => t('Image'),
    '#description' => $url_file_exixt ? t('Image actuelle: ' . $url_file_exixt . '.<br/> Cliquez sur "Choisissez un fichier" pour sélectionner une nouvelle image à télécharger (format à respecter : 1140x88px).') : t('Cliquez sur "Choisissez un fichier" pour sélectionner une image à télécharger (format à respecter : 1140x88px).'),
    '#size' => 44,
    '#upload_location' => 'public://',
  ];
  $form['actions'] = ['#type' => 'actions'];
  $form['actions']['submit'] = [
    '#type' => 'submit',
    '#value' => t('Save and continue'),
    '#weight' => 15,
  ];

  return $form;
}

/**
 * @param $form
 * @param $form_state
 */
function corpus_config_validate($form, &$form_state) {
  if ($form_state['values']['header_image']) {
    $file = file_save_upload('header_image', [
      'file_validate_is_image' => [],
      'file_validate_extensions' => ['png gif jpg jpeg'],
    ]);
    if ($file) {
      if ($file = file_move($file, 'public://')) {
        $form_state['values']['header_image'] = $file;
      }
      else {
        form_set_error('header_image', t('Failed to write the uploaded file in the site\'s file folder.'));
      }
    }
    else {
      form_set_error('header_image', t('No file was uploaded.'));
    }
  }
}

/**
 * @param $form
 * @param $form_state
 */
function corpus_config_form_submit($form, &$form_state) {
  variable_set('site_name', $form_state['values']['site_name']);
  variable_set('header_background_color', $form_state['values']['header_background_color']);

  if (isset($form_state['values']['header_image']) && $form_state['values']['header_image'] != 0) {
    $file = file_load($form_state['values']['header_image']);

    $file->status = FILE_STATUS_PERMANENT;

    $file_saved = file_save($file);

    // Record that the module is using the file.
    file_usage_add($file_saved, 'corpus_config_form', 'header_image', $file_saved->fid);
    $uri = $file->uri;
    $url = file_create_url($uri);
    variable_set('header_image', $url);
  }
}