<?php

declare(strict_types=1);

namespace App\Http\Controllers\Backend;

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

class AdminProfile extends Controller
{
    public function edit(Request $request)
    {
        $user = $request->user();
        return view('backend.profile.edit', compact('user'));
    }

    // Card 2: Info update (name, email, ইত্যাদি)
    public function updateInfo(ProfileUpdateRequest $request)
    {
        $user = $request->user();
        $data = $request->validated();

        // ইমেইল বদলালে ভেরিফিকেশন রিসেট
        if (array_key_exists('email', $data) && $data['email'] !== $user->email) {
            $user->email_verified_at = null;
        }

        // password ইনপুট এখানে নিলে অপসারণ করুন (এই ফর্মে পাসওয়ার্ড নেই)
        unset($data['password']);

        $user->update($data);

        return back()->with('status_info', 'প্রোফাইল তথ্য আপডেট হয়েছে!');
    }

    // Card 1: Avatar update (auto-submit on file change)
    public function updateAvatar(Request $request)
    {
        $request->validate([
            'avatar' => ['required','image','mimes:jpg,jpeg,png,webp','max:2048'],
        ]);

        $user = $request->user();

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

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

        return back()->with('status_avatar', 'প্রোফাইল ছবি আপডেট হয়েছে!');
    }

    // ঐচ্ছিক: Avatar remove
    public function destroyAvatar(Request $request)
    {
        $user = $request->user();

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

        $user->update(['avatar' => null]);

        return back()->with('status_avatar', 'প্রোফাইল ছবি মুছে ফেলা হয়েছে!');
    }

    // Card 4: Password change
    public function updatePassword(Request $request)
    {
        $request->validate([
            'old_password' => ['required','current_password'],
            'password'     => ['required','confirmed','min:8'], // password_confirmation ফিল্ড লাগবে
        ],[
            'old_password.current_password' => 'পুরনো পাসওয়ার্ড সঠিক নয়।',
        ]);

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

        return back()->with('status_password', 'পাসওয়ার্ড পরিবর্তন হয়েছে!');
    }
}
