<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Carbon;
use Illuminate\View\View;
use App\Models\UserActivity;

class UserProfileController extends Controller
{
    /**
     * Display the user's profile.
     *
     * @param User|null $user
     * @return View|\Illuminate\Http\RedirectResponse
     */
    public function show(User $user = null)
    {
        // If no user is provided or user param is empty, show the authenticated user's profile
        if ($user === null || !$user->exists) {
            $user = Auth::user();
            
            // Redirect to login if not logged in
            if (!$user) {
                return redirect()->route('login.steam');
            }
        }

        // Get paginated activities - 10 per page
        $activities = UserActivity::where('user_id', $user->id)
                                ->latest()
                                ->paginate(10);
                                
        // Get achievements
        $achievements = $user->achievements;
        $unlocked_today = $user->achievements()->where('unlocked_at', '>=', Carbon::yesterday())->get();

        return view('users.profile', compact('user', 'activities', 'achievements', 'unlocked_today'));
    }

    /**
     * Show the form for editing the user's profile.
     *
     * @return View
     */
    public function edit(): View
    {
        $user = Auth::user();
        
        return view('users.edit', compact('user'));
    }

    /**
     * Update the user's profile information.
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(Request $request)
    {
        $user = Auth::user();
        
        $validated = $request->validate([
            'name' => 'sometimes|string|max:255',
            'slug' => 'sometimes|string|max:24|unique:users,slug,' . $user->id,
            'banner' => 'sometimes|image|mimes:jpeg,png,jpg,gif|max:2048'
        ]);
        
        // Handle banner upload if provided
        if ($request->hasFile('banner')) {
            $this->handleBannerUpload($request->file('banner'), $user);
        }
        
        // Remove name and banner from validated data since we handle them separately
        $profileData = collect($validated)->except(['banner'])->toArray();
        
        if (!empty($profileData)) {
            $user->update($profileData);
        }

        $user->unlock(new \App\Achievements\EditedProfile());
        
        return redirect()->route('profile.show', ['user' => $user->slug])
                         ->with('success', 'Profile updated successfully!');
    }
    
    /**
     * Handle banner image upload
     * 
     * @param \Illuminate\Http\UploadedFile $file
     * @param User $user
     * @return void
     */
    private function handleBannerUpload($file, User $user)
    {
        // Delete old banner if exists
        if ($user->banner) {
            Storage::disk('public')->delete('user_banners/' . $user->banner);
        }
        
        // Generate filename using user ID and random string
        $filename = $user->id . '_' . uniqid() . '.' . $file->getClientOriginalExtension();
        
        // Store the file
        $file->storeAs('user_banners', $filename, 'public');
        
        // Update user with new banner
        $user->update(['banner' => $filename]);
    }
    
    /**
     * Delete the user's banner image
     * 
     * @return \Illuminate\Http\RedirectResponse
     */
    public function deleteBanner()
    {
        $user = Auth::user();
        
        if ($user->banner) {
            Storage::disk('public')->delete('user_banners/' . $user->banner);
            $user->update(['banner' => null]);
        }
        
        return redirect()->route('profile.edit')
                         ->with('success', 'Banner removed successfully!');
    }
}