<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\{Episode, Season, Show};
use App\Services\{MediaStorageService, ReceiverDatabaseSyncService, TmdbService};
use Illuminate\Http\Request;

class SeasonsController extends Controller
{
    public function index(Request $request)
    {
        $query = Season::with(['show'])->withCount('episodes')->latest();

        if ($request->filled('q')) {
            $term = '%' . $request->string('q') . '%';
            $query->where(function ($builder) use ($term) {
                $builder->where('title', 'like', $term)
                    ->orWhereHas('show', fn ($show) => $show->where('title', 'like', $term));
            });
        }

        return view('admin.seasons', [
            'items' => $query->paginate(40)->withQueryString(),
            'shows' => Show::orderBy('title')->get(),
        ]);
    }

    public function import(Request $request, TmdbService $tmdb, MediaStorageService $media, ReceiverDatabaseSyncService $receiverSync)
    {
        $data = $request->validate([
            'show_id' => ['required', 'exists:shows,id'],
            'season_number' => ['required', 'integer', 'min:0'],
        ]);

        $show = Show::findOrFail($data['show_id']);
        $payload = $tmdb->season($show->tmdb_id, $data['season_number']);
        $old = Season::where('show_id', $show->id)->where('season_number', $payload['season_number'])->first();
        $poster = $old?->poster_path ?: $media->storeRemoteImage($payload['poster_path'] ?? null, 'shows/seasons', 'w780');

        $season = Season::updateOrCreate(
            ['show_id' => $show->id, 'season_number' => $payload['season_number']],
            [
                'tmdb_id' => $payload['id'] ?? null,
                'title' => $payload['name'] ?? ('Season ' . $payload['season_number']),
                'overview' => $payload['overview'] ?? '',
                'poster_path' => $poster,
                'air_date' => !empty($payload['air_date']) ? $payload['air_date'] : null,
                'is_active' => true,
            ]
        );

        foreach ($payload['episodes'] ?? [] as $episodeData) {
            $oldEpisode = Episode::where('season_id', $season->id)
                ->where('episode_number', $episodeData['episode_number'])
                ->first();
            $still = $oldEpisode?->still_path ?: $media->storeRemoteImage($episodeData['still_path'] ?? null, 'shows/episodes', 'w780');

            Episode::updateOrCreate(
                ['season_id' => $season->id, 'episode_number' => $episodeData['episode_number']],
                [
                    'show_id' => $show->id,
                    'tmdb_id' => $episodeData['id'],
                    'title' => $episodeData['name'],
                    'overview' => $episodeData['overview'] ?? '',
                    'still_path' => $still,
                    'air_date' => !empty($episodeData['air_date']) ? $episodeData['air_date'] : null,
                    'runtime' => $episodeData['runtime'] ?? null,
                    'vote_average' => $episodeData['vote_average'] ?? null,
                    'is_active' => true,
                ]
            );
        }

        $receiverSync->syncSeason($season->fresh(['show.genres', 'episodes']));

        return back()->with('ok', 'Season, episodes and images imported and synchronized to Fojik.');
    }

    public function toggle(Season $season)
    {
        $season->update(['is_active' => !$season->is_active]);
        return back();
    }

    public function destroy(Season $season, MediaStorageService $media)
    {
        $season->load('episodes');
        $media->delete($season->poster_path);
        foreach ($season->episodes as $episode) {
            $media->delete($episode->still_path);
        }
        $season->delete();

        return back()->with('ok', 'Season deleted successfully.');
    }
}
