<?php

namespace App\Traits;

use App\Models\User;
use Illuminate\Http\UploadedFile; // Add this import
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;

trait ProfileTrait
{
    public function profile_update($request)
    {        
        $value = [
            'first_name' => $request['first_name'],
            'last_name' => $request['last_name'],
            'email' => Str::lower((string) ($request['email'] ?? '')),
            'phone' => $request['phone'] ?? null,
            'date_of_birth' => $request['date_of_birth'] ?? null,
            'gender' => $request['gender'] ?? null,
        ];

        if (isset($request['image']) && $request['image'] instanceof UploadedFile) {
            $this->imageDelete(auth()->user()->id, 'user', 'image');
            $requestImage = $request['image'];
            $response = $this->saveImage($requestImage, '_user_');
            $value['image'] = json_encode($response['images']);
        }
        User::where('id', auth()->user()->id)->update($value);

        return true;
    }

    public function profile_password_update($request)
    {
        $user = User::find(auth()->user()->id);
        if ($user && Hash::check($request['current_password'], $user->password)) {
            $user->update(['password' => Hash::make($request['new_password'])]);
            return true;
        }
        return false;
    }
}
