<?php
/**
 * OrokuBlocks - SportsPress Integration
 * 
 * @package OrokuBlocks
 * @author OrokuBlocks (https://orokublocks.com/)
 * 
 * @since 1.0.0
 * 
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
  exit;
}

final class OrokuBlocks_Sportspress {
  /**
   * Prevent more than one instance from being created
   * 
   * @since 1.0.0
   * 
   * @access private
   */
  private function __construct() {}

  /**
   * Prevent cloning
   * 
   * @since 1.0.0
   * 
   * @access private
   */
  private function __clone() {}

  /**
   * Return metric data
   * 
   * @since 1.0.0
   * 
   * @return array $metric_data         Metric data.
   */
  public static function metricsGet() {
    return sp_get_var_labels( 'sp_metric', null, false );
  }

  /**
   * Return nationality data by slug or false if not found.
   * 
   * @since 1.0.0
   * 
   * @param string      $nationality_slug         Nationality slug.
   * @return array|bool $nationality_data         Nationality data or false if not found.
   * 
   * @access private
   */
  private static function nationalityGet( $nationality_slug ) {
    $nationality_data = false;

    $countries = SP()->countries->countries;

    if ( array_key_exists( $nationality_slug, $countries ) ) {
      $nationality_data = [
        'name'      => $countries[$nationality_slug],
        'slug'      => $nationality_slug,
        'image_url' => plugin_dir_url( SP_PLUGIN_FILE ) . 'assets/images/flags/' . $nationality_slug . '.png'
      ];

      $args = [
        'post_type'       => 'attachment',
        'title'           => $nationality_slug,
        'posts_per_page'  => 1,
        'fields'          => 'ids'
      ];

      $custom_flag = get_posts( $args );

      if( $custom_flag ){
        $custom_flag_post_id = $custom_flag[0];

        if ( $custom_flag_post_id ) {
          $nationality_data['image_url'] = wp_get_attachment_image_url( $custom_flag_post_id );
        }
      }
    }

    return $nationality_data;
  }

  /**
   * Return team data by id or false if not found.
   * 
   * @since 1.0.0
   * 
   * @param string      $team_id          Team id.
   * @return array|bool $team_data          Team data or false if not found.
   * 
   * @access private
   */
  private static function teamGet( $team_id ) {
    $team_data = false;

    $team = new SP_Team( $team_id );
    $team_post = $team->get_post_data();

    if ( ( $team_post instanceof WP_Post ) && ( $team_post->ID == $team_id ) ) {
      $team_data = [
        'id'            => $team_id,
        'slug'          => $team_post->post_name,
        'title'         => $team_post->post_title,
        'content'       => $team_post->post_content,
        'image_url'     => OrokuBlocks_Blog::postThumbnailUrlGet( $team_id ),
        'short_name'    => sp_team_short_name( $team_id ),
        'abbreviation'  => sp_team_abbreviation( $team_id )
      ];
    }

    return $team_data;
  }

  /**
   * Return player data by id or false if not found.
   * 
   * @since 1.0.0
   * 
   * @param string      $player_id          Player id.
   * @return array|bool $player_data        Player data or false if not found.
   */
  public static function playerGet( $player_id ) {
    $player_data = false;

    $post_player_data = get_posts(
      [
        'post_type' => 'sp_player',
        'post__in'  => [ $player_id ]
      ]
    );

    // only get player information if indeed a player type post
    if ( count( $post_player_data ) > 0 ) {
      $player = new SP_Player( $player_id );
      $player_post = $player->get_post_data();

      if ( ( $player_post instanceof WP_Post ) && ( $player_post->ID == $player_id ) ) {
        $player_data = [
          'id'          => $player_id,
          'slug'        => $player_post->post_name,
          'title'       => $player_post->post_title,
          'content'     => $player_post->post_content,
          'number'      => get_post_meta( $player_id, 'sp_number', true ),
          'image_url'   => OrokuBlocks_Blog::postThumbnailUrlGet( $player_id ),
          'metrics'     => $player->metrics(),
          'nationality' => [],
          'team'        => [],
          'position'    => []
        ];

        // get player nationality data
        $player_nationalities = $player->nationalities();

        if ( is_array( $player_nationalities ) && ( count( $player_nationalities ) > 0 ) ) {
          $player_nationality_slug = $player_nationalities[0];

          $player_data['nationality'] = self::nationalityGet( $player_nationality_slug );
        }

        // get player team data
        $player_current_teams = $player->current_teams();

        if ( is_array( $player_current_teams ) && ( count( $player_current_teams ) > 0 ) ) {
          $player_team_id = $player_current_teams[0];

          $player_data['team'] = self::teamGet( $player_team_id );
        }

        // get player position data
        $player_positions = $player->positions();

        if ( is_array( $player_positions ) && ( count( $player_positions ) > 0 ) ) {
          $player_position = $player_positions[0];

          $player_data['position'] = [
            'name'  => $player_position->name,
            'slug'  => $player_position->slug
          ];
        }
      }
    }

    return $player_data;
  }

  /**
   * Return league data by event id.
   * 
   * @since 1.1.0
   * 
   * @param int           $event_id       Event id.
   * @return array|bool   $league_data    League data or false if not found.
   * 
   * @access private
   */
  private static function eventLeagueGet( $event_id ) {
    $league_data = false;

    $league = get_the_terms( $event_id, 'sp_league' );

    if ( is_array( $league ) && ( count( $league ) > 0 ) ) {
      $league_data = [
        'id'          => $league[0]->term_id,
        'name'        => $league[0]->name,
        'slug'        => $league[0]->slug,
        'description' => $league[0]->description
      ];
    }

    return $league_data;
  }

  /**
   * Return season data by event id.
   * 
   * @since 1.1.0
   * 
   * @param int           $event_id       Event id.
   * @return array|bool   $season_data    Season data or false if not found.
   * 
   * @access private
   */
  private static function eventSeasonGet( $event_id ) {
    $season_data = false;

    $season = get_the_terms( $event_id, 'sp_season' );

    if ( is_array( $season ) && ( count( $season ) > 0 ) ) {
      $season_data = [
        'id'          => $season[0]->term_id,
        'name'        => $season[0]->name,
        'slug'        => $season[0]->slug,
        'description' => $season[0]->description
      ];
    }

    return $season_data;
  }

  /**
   * Return event data by id or false if not found.
   * 
   * @since 1.1.0
   * 
   * @param string      $event_id          Event id.
   * @return array|bool $event_data        Event data or false if not found.
   */
  public static function eventGet( $event_id ) {
    $event_data = false;

    $post_event_data = get_posts(
      [
        'post_type'   => 'sp_event',
        'post__in'    => [ $event_id ],
        'post_status' => [ 'publish', 'future' ]
      ]
    );

    // only get event information if indeed a event type post
    if ( count( $post_event_data ) > 0 ) {
      $event = new SP_Event( $event_id );
      $event_post = $event->get_post_data();

      if ( ( $event_post instanceof WP_Post ) && ( $event_post->ID == $event_id ) ) {
        $event_data = [
          'id'        => $event_id,
          'status'    => $event_post->post_status,
          'slug'      => $event_post->post_name,
          'title'     => $event_post->post_title,
          'content'   => $event_post->post_content,
          'date'      => $event_post->post_date,
          'permalink' => $event_post->guid,
          'league'    => self::eventLeagueGet( $event_id ),
          'season'    => self::eventSeasonGet( $event_id ),
          'teams'     => [],
          'result'    => []
        ];

        // get team data
        $event_teams_ids = get_post_meta( $event_id, 'sp_team', false );

        foreach ( $event_teams_ids as $team_id ) {
          $event_data['teams'][] = self::teamGet( $team_id );
        }

        // get result data
        $event_winner_team_id = $event->winner();

        $event_data['result']['winner'] = false;

        if ( ! is_null( $event_winner_team_id ) ) {
          $event_data['result']['winner'] = $event_winner_team_id;
        }

        $event_score = $event->main_results();

        $event_data['result']['points'] = [];

        foreach ( $event_teams_ids as $team_id ) {
          $event_data['result']['points'][$team_id] = '-';
          
          // if match is already done (not currently being played or future match)
          if ( count( $event_score ) > 0 ) {
            if ( $event_data['status'] === 'publish' ) {
              if ( $event_data['result']['winner'] ) {
                $event_data['result']['points'][$team_id] = $event_winner_team_id == $team_id ? max( $event_score ) : min( $event_score );
              } else {
                $event_data['result']['points'][$team_id] = $event_score[0];
              }
            }
          }
        }
      }
    }

    return $event_data;
  }
}