<?php

/**
 * @file
 * Theme and preprocess functions for html wrapper.
 */

use Drupal\block_content\Entity\BlockContent;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\file\Entity\File;
use Drupal\file\Plugin\Field\FieldType\FileFieldItemList;
use Drupal\media\Entity\Media;

/**
 * Implements hook_theme_preprocess_html().
 */
function sector_demo_preprocess_html(&$variables) {
  if (!\Drupal::currentUser()->isAnonymous()) {
    $variables['#attached']['library'][] = 'sector_demo/contextual';
  }

  // theme_get_setting('apply_glitter')
  if (theme_get_setting('brand')) {
    $brand = BlockContent::load(theme_get_setting('brand'));
    $brandmark = $brand->field_brand_mark->first();
    if (!$brandmark) {
      return;
    }

    if ($brandmark instanceof EntityReferenceItem) {

      $media = Media::load($brandmark->target_id);
      if (!$media->hasField('field_media_image')) {
        return;
      }

      if ($media->field_media_image instanceof FileFieldItemList) {
        $fid = $media->field_media_image->target_id;
        $file = File::load($fid);

        $variables['page']['#attached']['html_head_link'][] = [
            [
              'rel' => 'shortcut icon',
              'type' => 'image/svg+xml',
              'href' => \Drupal::service('file_url_generator')->generateAbsoluteString($file->getFileUri()),
            ],
        ];
      }
    }
  }
}
