<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class ProfileController extends Controller
{
    public function edit()
    {
        return view('auth.profile', ['user' => auth()->user()]);
    }

    public function update(Request $request)
    {
        $user = $request->user();

        $data = $request->validate([
            'name'      => ['required', 'string', 'max:255'],
            'username'  => ['required', 'alpha_dash', 'min:3', 'max:30', 'unique:users,username,' . $user->id],
            'email'     => ['required', 'email', 'unique:users,email,' . $user->id],
            'bio'       => ['nullable', 'string', 'max:1000'],
            'phone'     => ['nullable', 'string', 'max:30'],
            'country'   => ['nullable', 'string', 'max:100'],
            'website'   => ['nullable', 'url', 'max:255'],
            'twitter'   => ['nullable', 'string', 'max:100'],
            'facebook'  => ['nullable', 'string', 'max:100'],
            'linkedin'  => ['nullable', 'string', 'max:100'],
        ]);

        $user->update($data);
        return back()->with('success', 'Profile updated.');
    }

    public function updatePassword(Request $request)
    {
        $request->validate([
            'current_password' => ['required'],
            'password'         => ['required', 'min:8', 'confirmed'],
        ]);

        if (!Hash::check($request->current_password, $request->user()->password)) {
            return back()->withErrors(['current_password' => 'Current password is incorrect.']);
        }

        $request->user()->update(['password' => Hash::make($request->password)]);
        return back()->with('success', 'Password updated.');
    }

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

        $user = $request->user();
        $file = $request->file('avatar');
        $filename = 'avatar_' . $user->id . '_' . time() . '.' . $file->getClientOriginalExtension();
        $file->move(public_path('uploads/avatars'), $filename);

        if ($user->avatar) {
            @unlink(public_path('uploads/avatars/' . $user->avatar));
        }
        $user->update(['avatar' => $filename]);
        return back()->with('success', 'Avatar updated.');
    }
}
