<commit_before><?php

  namespace App\Services\Models;

  use App\Episode as Model;
  use App\Item;
  use App\Services\TMDB;
  use App\Setting;
  use Carbon\Carbon;

  class EpisodeService {

    private $model;
    private $tmdb;
    private $item;

    /**
     * @param Model $model
     * @param TMDB  $tmdb
     * @param Item  $item
     */
    public function __construct(Model $model, TMDB $tmdb, Item $item)
    {
      $this->model = $model;
      $this->tmdb = $tmdb;
      $this->item = $item;
    }

    /**
     * @param $item
     */
    public function create($item)
    {
      if($item->media_type == 'tv') {
        $seasons = $this->tmdb->tvEpisodes($item->tmdb_id);

        foreach($seasons as $season) {
          $seasonAirDate = isset($season->air_date) ? ($season->air_date ?: Item::FALLBACK_DATE) : Item::FALLBACK_DATE;
          $releaseSeason = Carbon::createFromFormat('Y-m-d', $seasonAirDate);

          foreach($season->episodes as $episode) {
            $episodeAirDate = isset($episode->air_date) ? ($episode->air_date ?: Item::FALLBACK_DATE) : Item::FALLBACK_DATE;
            $releaseEpisode = Carbon::createFromFormat('Y-m-d', $episodeAirDate);

            $this->model->updateOrCreate(
              [
                'season_number' => $episode->season_number,
                'episode_number' => $episode->episode_number,
                'tmdb_id' => $item->tmdb_id,
              ],
              [
                'season_tmdb_id' => $season->id,
                'episode_tmdb_id' => $episode->id,
                'release_episode' => $releaseEpisode->getTimestamp() >= 0 ? $releaseEpisode->getTimestamp() : 0,
                'release_season' => $releaseSeason->getTimestamp() >= 0 ? $releaseSeason->getTimestamp() : 0,
                'name' => substr($episode->name, 0, 255),
              ]
            );
          }
        }
      }
    }

    /**
     * Remove all episodes by tmdb_id.
     *
     * @param $tmdbId
     */
    public function remove($tmdbId)
    {
      $this->model->where('tmdb_id', $tmdbId)->delete();
    }

    /**
     * Get all episodes of a tv show grouped by seasons,
     * the data for the next unseen episode, which will be used in the modal as an indicator,
     * and the setting option to check if spoiler protection is enabled.
     *
     * @param $tmdbId
     * @return array
     */
    public function getAllByTmdbId($tmdbId)
    {
      Carbon::setLocale(config('app.TRANSLATION'));

      $episodes = $this->model->findByTmdbId($tmdbId)->get();

      return [
        'episodes' => $episodes->sortBy('episode_number')->groupBy('season_number'),
        'next_episode' => $episodes->where('seen', 0)->first(),
        'spoiler' => Setting::first()->episode_spoiler_protection,
      ];
    }

    /**
     * Set an episode as seen / unseen.
     *
     * @param $id
     * @return mixed
     */
    public function toggleSeen($id)
    {
      $episode = $this->model->find($id);

      if($episode) {
        // Update the parent relation only if we mark the episode as seen.
        if( ! $episode->seen) {
          $this->item->updateLastSeenAt($episode->tmdb_id);
        }

        return $episode->update([
          'seen' => ! $episode->seen,
        ]);
      }
    }

    /**<commit_msg>fix next episode sorting<commit_after><?php

  namespace App\Services\Models;

  use App\Episode as Model;
  use App\Item;
  use App\Services\TMDB;
  use App\Setting;
  use Carbon\Carbon;

  class EpisodeService {

    private $model;
    private $tmdb;
    private $item;

    /**
     * @param Model $model
     * @param TMDB  $tmdb
     * @param Item  $item
     */
    public function __construct(Model $model, TMDB $tmdb, Item $item)
    {
      $this->model = $model;
      $this->tmdb = $tmdb;
      $this->item = $item;
    }

    /**
     * @param $item
     */
    public function create($item)
    {
      if($item->media_type == 'tv') {
        $seasons = $this->tmdb->tvEpisodes($item->tmdb_id);

        foreach($seasons as $season) {
          $seasonAirDate = isset($season->air_date) ? ($season->air_date ?: Item::FALLBACK_DATE) : Item::FALLBACK_DATE;
          $releaseSeason = Carbon::createFromFormat('Y-m-d', $seasonAirDate);

          foreach($season->episodes as $episode) {
            $episodeAirDate = isset($episode->air_date) ? ($episode->air_date ?: Item::FALLBACK_DATE) : Item::FALLBACK_DATE;
            $releaseEpisode = Carbon::createFromFormat('Y-m-d', $episodeAirDate);

            $this->model->updateOrCreate(
              [
                'season_number' => $episode->season_number,
                'episode_number' => $episode->episode_number,
                'tmdb_id' => $item->tmdb_id,
              ],
              [
                'season_tmdb_id' => $season->id,
                'episode_tmdb_id' => $episode->id,
                'release_episode' => $releaseEpisode->getTimestamp() >= 0 ? $releaseEpisode->getTimestamp() : 0,
                'release_season' => $releaseSeason->getTimestamp() >= 0 ? $releaseSeason->getTimestamp() : 0,
                'name' => substr($episode->name, 0, 255),
              ]
            );
          }
        }
      }
    }

    /**
     * Remove all episodes by tmdb_id.
     *
     * @param $tmdbId
     */
    public function remove($tmdbId)
    {
      $this->model->where('tmdb_id', $tmdbId)->delete();
    }

    /**
     * Get all episodes of a tv show grouped by seasons,
     * the data for the next unseen episode, which will be used in the modal as an indicator,
     * and the setting option to check if spoiler protection is enabled.
     *
     * @param $tmdbId
     * @return array
     */
    public function getAllByTmdbId($tmdbId)
    {
      Carbon::setLocale(config('app.TRANSLATION'));

      $episodes = $this->model->findByTmdbId($tmdbId)->get();

      return [
        'episodes' => $episodes->sortBy('episode_number')->groupBy('season_number'),
        'next_episode' => $episodes->where('seen', 0)->sortBy('season_number')->first(),
        'spoiler' => Setting::first()->episode_spoiler_protection,
      ];
    }

    /**
     * Set an episode as seen / unseen.
     *
     * @param $id
     * @return mixed
     */
    public function toggleSeen($id)
    {
      $episode = $this->model->find($id);

      if($episode) {
        // Update the parent relation only if we mark the episode as seen.
        if( ! $episode->seen) {
          $this->item->updateLastSeenAt($episode->tmdb_id);
        }

        return $episode->update([
          'seen' => ! $episode->seen,
        ]);
      }
    }

    /**
{'fraction_non_alphanumeric': 0.15063520871143377, 'fraction_numerical': 0.0027223230490018148, 'mean_word_length': 2.08011178388449, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 118, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5775424', 'n_tokens_mistral': 2262, 'n_tokens_neox': 2100, 'n_words': 413}