<?php

namespace App\Http\Controllers;

use App\Http\Requests\ProfileUpdateRequest;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redirect;
use Illuminate\View\View;

class ProfileController extends Controller
{
    /**
     * Display user profile.
     * 
     * If no user is specified, shows authenticated user's profile.
     * If user is specified, checks "view users" permission.
     * 
     * @param User|null $user
     * @return View
     */
    public function show(?User $user = null): View
    {
        // If no user specified, show authenticated user's profile
        if (!$user) {
            $user = auth()->user();
        } else {
            // Check if user has permission to view other users' profiles
            abort_unless(
                auth()->user()->can('view users'),
                403,
                'You do not have permission to view other users\' profiles.'
            );
        }

        // Eager load roles for display
        $user->load('roles');

        return view('profile.show', compact('user'));
    }

    /**
     * Display the user's profile form.
     * Only allows editing own profile.
     */
    public function edit(Request $request): View
    {
        return view('profile.edit', [
            'user' => $request->user(),
        ]);
    }

    /**
     * Update the user's profile information.
     * 
     * Allows updating name, email, username, phone, and avatar.
     * Prevents modification of roles and is_active status.
     */
    public function update(ProfileUpdateRequest $request): RedirectResponse
    {
        $user = $request->user();
        
        $validated = $request->validated();
        
        // Allow updating profile fields (not password — that has its own route)
        $allowedFields = ['name', 'email', 'username', 'phone'];
        $updateData = array_intersect_key($validated, array_flip($allowedFields));
        
        // Handle avatar upload separately
        if ($request->hasFile('avatar')) {
            $path = $request->file('avatar')->store('avatars', 'public');
            $updateData['avatar'] = $path;
        }
        
        // Fill only allowed fields
        $user->fill($updateData);

        // Reset email verification if email changed
        if ($user->isDirty('email')) {
            $user->email_verified_at = null;
        }

        $user->save();

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

    /**
     * Update the user's password.
     */
    public function updatePassword(Request $request): RedirectResponse
    {
        $request->validate([
            'current_password'      => ['required', 'current_password'],
            'password'              => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $request->user()->update([
            'password' => \Illuminate\Support\Facades\Hash::make($request->password),
        ]);

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

    /**
     * Delete the user's account.
     */
    public function destroy(Request $request): RedirectResponse
    {
        $request->validateWithBag('userDeletion', [
            'password' => ['required', 'current_password'],
        ]);

        $user = $request->user();

        Auth::logout();

        $user->delete();

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

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

    /**
     * Display active sessions for the authenticated user.
     */
    public function sessions(Request $request): View
    {
        $sessions = collect();

        // If using database session driver, load sessions from DB
        if (config('session.driver') === 'database') {
            try {
                $sessions = \DB::table('sessions')
                    ->where('user_id', $request->user()->id)
                    ->orderByDesc('last_activity')
                    ->get();
            } catch (\Exception $e) {
                // Sessions table may not exist yet
            }
        }

        return view('settings.sessions', compact('sessions'));
    }

    /**
     * Logout all other devices/sessions.
     */
    public function logoutOtherDevices(Request $request): RedirectResponse
    {
        $request->validate([
            'password' => ['required', 'current_password'],
        ]);

        Auth::logoutOtherDevices($request->password);

        return Redirect::route('settings.sessions')
            ->with('success', 'All other devices have been logged out successfully.');
    }

    /**
     * Display security settings for the authenticated user.
     */
    public function security(Request $request): View
    {
        $user = $request->user();

        // Load recent login attempts
        $loginAttempts = collect();
        try {
            $loginAttempts = \App\Models\LoginAttempt::where('email_attempted', $user->email)
                ->orderByDesc('attempted_at')
                ->limit(20)
                ->get();
        } catch (\Exception $e) {
            // LoginAttempt model may not be available
        }

        $twoFactorEnabled = false;

        return view('settings.security', compact('loginAttempts', 'twoFactorEnabled'));
    }
}
