<?php

namespace Drupal\ufc\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManager;
use Drupal\Core\Url;
use Drupal\node\Entity\Node;
use Drupal\Core\Cache\CacheableJsonResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;

class RecentFightsController extends ControllerBase {

  protected $entityTypeManager;

  public function __construct(
    EntityTypeManager $entityTypeManager
  ) {
    $this->entityTypeManager = $entityTypeManager;
  }

 /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('entity_type.manager'),
    );
  }

  /**
   * Gets recent fights.
   */
  public function getRecentFights() {
    $query = $this->entityTypeManager->getStorage('node')->getQuery();
    $query->accessCheck(TRUE);
    $query->condition('type', 'fight')->sort('field_fight_date', 'DESC');
    $query->range(0, 15);
    $nids = $query->execute();
    $all_fights = Node::loadMultiple($nids);
    $fights = [];
    foreach ($all_fights as $fight) {
      $f1 = Node::load($fight->field_fighter_one->target_id);
      $f2 = Node::load($fight->field_fighter_two->target_id);

      /* $result = Node::load($fight->field_result->target_id) ?? FALSE; */
      $alias = \Drupal::service('path_alias.manager')->getAliasByPath("/" . $fight->toUrl()->getInternalPath());
      if ($f1 && $f2) {

        $f1_uri = $f1->field_player_photo->entity->field_media_image->entity->getFileUri() ?? 'public://player-headshots/headshot-default.jpeg';
        $f2_uri = $f2->field_player_photo->entity->field_media_image->entity->getFileUri() ?? 'public://player-headshots/headshot-default.jpeg';

        $f1_pic_url = str_replace("public://", "/sites/default/files/", $f1_uri);
        $f2_pic_url = str_replace("public://", "/sites/default/files/", $f2_uri);

        $fights[] = [
          'fighter_one' => $f1->getTitle(),
          'fighter_one_image' => $f1_pic_url,
          'fighter_two' => $f2->getTitle(),
          'fighter_two_image' => $f2_pic_url,
          'url' => $alias
        ];
      }
    }

    return new CacheableJsonResponse($fights);
  }


}
