<?php

namespace App\Http\Controllers;

use App\Models\Avatar;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Validation\Rule;
use Illuminate\View\View;

class ProfilePhotoController extends Controller
{
    public function edit(Request $request): View
    {
        return view('profile.photo', [
            'user' => $request->user(),
            'avatars' => Avatar::active()->orderByDesc('is_default')->orderBy('name')->get(),
        ]);
    }

    public function upload(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'profile_photo' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'],
        ]);

        $user = $request->user();

        if ($user->profile_photo) {
            Storage::disk('public')->delete($user->profile_photo);
        }

        $path = $data['profile_photo']->store('profile-photos', 'public');

        $user->update([
            'profile_photo' => $path,
            'selected_avatar' => null,
            'avatar_type' => 'custom',
        ]);

        return back()->with('success', 'Profile picture uploaded successfully.');
    }

    public function selectAvatar(Request $request): RedirectResponse
    {
        $data = $request->validate([
            'avatar_id' => ['required', Rule::exists('avatars', 'id')->where('status', Avatar::STATUS_ACTIVE)],
        ]);

        $avatar = Avatar::findOrFail($data['avatar_id']);
        $user = $request->user();

        if ($user->profile_photo) {
            Storage::disk('public')->delete($user->profile_photo);
        }

        $user->update([
            'profile_photo' => null,
            'selected_avatar' => $avatar->image_path,
            'avatar_type' => 'avatar',
        ]);

        return back()->with('success', 'Avatar selected successfully.');
    }

    public function remove(Request $request): RedirectResponse
    {
        $user = $request->user();

        if ($user->profile_photo) {
            Storage::disk('public')->delete($user->profile_photo);
        }

        $user->update([
            'profile_photo' => null,
            'selected_avatar' => null,
            'avatar_type' => 'default',
        ]);

        return back()->with('success', 'Profile picture removed. The default avatar is now active.');
    }
}
