<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Models\Playlist;
use App\Models\PlaylistEpisode;
use App\Models\Watched;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class UserController extends Controller
{
    /**
     * Display User Page.
     */
    public function index(string $username): \Illuminate\View\View
    {
        $user = User::where('username', $username)
            ->select('id', 'username', 'global_name', 'avatar', 'created_at', 'is_patreon')
            ->firstOrFail();
        
        return view('user.index', [
            'user' => $user,
        ]);
    }

    /**
     * Delete User.
     */
    public function delete(Request $request): \Illuminate\Http\RedirectResponse
    {
        $user = User::where('id', $request->user()->id)->firstOrFail();

        // Delete Playlist
        $playlists = Playlist::where('user_id', $user->id)->get();
        foreach($playlists as $playlist) {
            PlaylistEpisode::where('playlist_id', $playlist->id)->forceDelete();
            $playlist->forceDelete();
        }

        // Update comments to deleted user
        DB::table('comments')->where('commenter_id', '=', $user->id)->update(['commenter_id' => 1]);

        $user->forceDelete();

        Auth::guard('web')->logout();

        $request->session()->invalidate();

        $request->session()->regenerateToken();

        cache()->flush();

        return redirect('/');
    }
}
