<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use App\Models\Podcast;
use App\Models\Artworks;
use App\Models\Episode;
use App\Http\Resources\LatestEpisodeResource;


class PodcastController extends Controller
{
    public function show(Request $request, $slug)
    {
        $user = auth()->user();
        $podcast = Podcast::where('slug', $slug)
            ->where('published', true)
            ->firstOrFail();
        $episodes = Episode::where('published', true)
            ->whereNotNull('artwork_id')
            ->with('artwork')
            ->with('approvedArtworks')
            ->where('podcast_id', $podcast->id)
            ->orderBy('episode_number', 'desc')->paginate(100);
        $podcasts = Podcast::where('published', true)->with('episodes')->get();
        return view('podcasts.podcast', [
            'user'      => $user,
            'pageTitle' => $podcast->name,
            'podcast'   => $podcast,
            'episodes'  => $episodes,
            'podcasts'  => $podcasts,
        ]);
    }

    /**
     * Display the latest episode's chosen artwork for third party tools.
     *
     * @param $slug
     * @return \Illuminate\Http\Response
     */
    public function latest_artwork(Request $request, $slug)
    {
        $podcast = Podcast::with('latestArtwork.artist')
            ->where('slug', $slug)
            ->where('published', true)
            ->firstOrFail();
        $art = $podcast->latestArtwork;

        return new LatestEpisodeResource($podcast);
        return response()->json([
            'episode_number' => optional($podcast->latestEpisode)->episode_number,
            'artwork'        => $art,
            'artist'         => optional($art)->artist,
        ]);
    }
}
