<?php

namespace App\Modules\Users\Http\Controllers;

use App\Core\Http\Controllers\BaseApiController;
use App\Http\Requests\Api\UpdateProfileRequest;
use App\Http\Resources\UserResource;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

/**
 * ملف المستخدم الحالي (JSON).
 */
class ProfileController extends BaseApiController
{
    public function show(Request $request): JsonResponse
    {
        return $this->successResponse('تم جلب الملف الشخصي', [
            'user' => (new UserResource($request->user()))->resolve(),
        ]);
    }

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

        $newPassword = $data['password'] ?? null;
        if ($newPassword !== null && $newPassword !== '') {
            $current = $data['current_password'] ?? '';
            if (! Hash::check($current, $user->password)) {
                throw ValidationException::withMessages([
                    'current_password' => ['كلمة المرور الحالية غير صحيحة.'],
                ]);
            }
            $user->password = $newPassword;
        }

        unset($data['password'], $data['password_confirmation'], $data['current_password']);

        $user->fill($data);
        $user->save();

        return $this->successResponse('تم تحديث الملف الشخصي', [
            'user' => (new UserResource($user->fresh()))->resolve(),
        ]);
    }
}
