<?php

namespace App\Http\Controllers\Web;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\UpdateProfileRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\View\View;

final class SettingsController extends Controller
{
    public function index(Request $request): View
    {
        return view('web.settings.index', ['user' => $request->user()]);
    }

    public function update(UpdateProfileRequest $request): RedirectResponse
    {
        $user = $request->user();
        $data = $request->validated();

        $user->fill([
            'full_name' => $data['full_name'] ?? $user->full_name,
            'username' => $data['username'] ?? $user->username,
            'phone' => $data['phone'] ?? $user->phone,
            'email' => $data['email'] ?? $user->email,
        ]);

        if (! empty($data['password'] ?? null)) {
            if (empty($data['current_password'] ?? null) || ! Hash::check($data['current_password'], $user->password)) {
                return back()->withErrors(['current_password' => 'كلمة المرور الحالية غير صحيحة.'])->withInput();
            }
            $user->password = Hash::make($data['password']);
        }

        $user->save();

        return back()->with('success', 'تم حفظ الإعدادات.');
    }
}
