<?php

namespace App\Http\Controllers\Admin;

use App\Models\Episode;
use App\Models\EpisodeSubtitle;
use App\Models\Subtitle;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class SubtitleController extends Controller
{
    /**
     * Add new Subtitle.
     */
    public function store(Request $request): \Illuminate\Http\RedirectResponse
    {
        $subtitle = Subtitle::create([
            'name'  => $request->name,
            'slug'  => $request->slug,
        ]);

        // Add to Episode
        EpisodeSubtitle::create([
            'episode_id' => $request->episode_id,
            'subtitle_id' => $subtitle->id,
        ]);

        return redirect()->back();
    }

    /**
     * Update Episode Subtitles.
     */
    public function update(Request $request): \Illuminate\Http\RedirectResponse
    {
        $episode = Episode::where('id', $request->input('episode_id'))->firstOrFail();

        // Clear everything
        foreach($episode->subtitles as $sub) {
            $sub->forceDelete();
        }

        if (! $request->input('subtitles')) {
            return redirect()->back();
        }

        // Re-Add
        foreach (json_decode($request->input('subtitles')) as $sub) {
            $subtitle = Subtitle::where('name', $sub->value)->firstOrFail();

            // Add to Episode
            EpisodeSubtitle::create([
                'episode_id' => $episode->id,
                'subtitle_id' => $subtitle->id,
            ]);
        }

        return redirect()->back();
    }
}
