<?php 

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Storage;

class ProfileController extends Controller
{
    public function edit()
    {
        $user = Auth::user();
        return view('backend.profile', compact('user'));
    }

    public function update(Request $request)
    {
        $user = Auth::user();

        $validated = $request->validate([
            'name'   => ['required','string','max:191'],
            'email'  => ['nullable','email','max:191', Rule::unique('users','email')->ignore($user->id)],
            'phone'  => ['nullable','string','max:50'],
            'avatar' => ['nullable','image'], // 1MB
        ]);

        // avatar handle
        if ($request->hasFile('avatar')) {
            // পুরোনো ছবি থাকলে ডিলিট
            if ($user->avatar && Storage::disk('public')->exists($user->avatar)) {
                Storage::disk('public')->delete($user->avatar);
            }

            $path = $request->file('avatar')->store('avatars', 'public');
            $user->avatar = $path;
        }

        $user->name  = $validated['name'];
        $user->email = $validated['email'] ?? null;
        $user->phone = $validated['phone'] ?? null;

        $user->save();

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

    public function updatePassword(Request $request)
    {
        $user = Auth::user();

        $request->validate([
            'current_password' => ['required'],
            'password'         => ['required','confirmed'],
        ]);

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

        $user->password = Hash::make($request->password);
        $user->save();

        return back()->with('success','Password updated successfully.');
    }
}
