<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProfileUpdateRequest;
use App\Models\Episode;
use App\Models\User;
use Conner\Tagging\Model\Tag;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\View\View;
use Intervention\Image\Laravel\Facades\Image;

class ProfileController extends Controller
{
    /**
     * Display the user page.
     */
    public function index(Request $request): View
    {
        return view('profile.index', [
            'user' => $request->user(),
        ]);
    }

    /**
     * Display the user's settings form.
     */
    public function settings(Request $request): View
    {
        $example = Episode::where('title', 'Succubus Yondara Gibo ga Kita!?')->first();

        return view('profile.settings', [
            'user' => $request->user(),
            'example' => $example,
        ]);
    }

    /**
     * Update the user's profile information.
     */
    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $user = $request->user();

        // Fill everything except the image
        $user->fill($request->safe()->except('image'));

        if ($request->user()->isDirty('email')) {
            $request->user()->email_verified_at = null;
        }

        if ($request->hasFile('image')) {
            $this->storeAvatar($request->file('image'), $user);
        }

        $user->save();

        return Redirect::route('profile.settings')->with('status', 'profile-updated');
    }

    /**
     * Display the user's watched page.
     */
    public function watched(Request $request): View
    {
        return view('profile.watched', [
            'user' => $request->user(),
        ]);
    }

    /**
     * Display the user's comments page.
     */
    public function comments(Request $request): View
    {
        return view('profile.comments', [
            'user' => $request->user(),
        ]);
    }

    /**
     * Display the user's likes page.
     */
    public function likes(Request $request): View
    {
        return view('profile.likes', [
            'user' => $request->user(),
        ]);
    }

    /**
     * Update user settings.
     */
    public function saveSettings(Request $request): RedirectResponse
    {
        $user = $request->user();
        $user->search_design = $request->input('searchDesign') == 'thumbnail';
        $user->home_top_design = $request->input('topDesign') == 'thumbnail';
        $user->home_middle_design = $request->input('middleDesign') == 'thumbnail';
        $user->save();

        return Redirect::route('profile.settings')->with('status', 'design-updated');
    }

    /**
     * Update user tag blacklist.
     */
    public function saveBlacklist(Request $request): RedirectResponse
    {
        $user = $request->user();
        $tags = json_decode($request->input('tags'));

        if (! $tags) {
            $user->tag_blacklist = null;
            $user->save();

            return Redirect::route('profile.settings')->with('status', 'blacklist-updated');
        }

        $blacklist = [];
        foreach ($tags as $tag) {
            $t = Tag::where('slug', Str::slug($tag->value))->firstOrFail();
            $blacklist[] = $t->slug;
        }

        $user->tag_blacklist = $blacklist;
        $user->save();

        return Redirect::route('profile.settings')->with('status', 'blacklist-updated');
    }

    /**
     * Delete the user's account.
     */
    public function destroy(Request $request): RedirectResponse
    {
        $user = $request->user();

        // Verify password if user has password
        if (! is_null($user->password)) {
            $request->validateWithBag('userDeletion', [
                'password' => ['required', 'current_password'],
            ]);
        }

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

        // Delete Profile Picture
        if ($user->avatar) {
            Storage::disk('public')->delete($user->avatar);
        }

        Auth::logout();

        $user->delete();

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

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

        cache()->flush();

        return Redirect::to('/');
    }

    /**
     * Store custom user avatar.
     */
    protected function storeAvatar(UploadedFile $file, User $user): void
    {
        // Create Folder for Image Upload
        if (! Storage::disk('public')->exists('/images/avatars')) {
            Storage::disk('public')->makeDirectory('/images/avatars');
        }

        // Delete old avatar if it exists
        if ($user->avatar) {
            Storage::disk('public')->delete($user->avatar);
        }

        $filename = "images/avatars/{$user->id}.webp";

        $image = Image::read($file->getRealPath())
            ->cover(128, 128)
            ->toWebp(quality: 85);

        Storage::disk('public')->put($filename, $image);

        $user->avatar = $filename;
    }
}
