<?php

namespace App\Http\Controllers\Api\V1\Profile;

use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class ProfileController extends Controller
{
    /**
     * Users profile
     */
    public function index(): JsonResponse
    {
        $user = auth()->user();

        return response()->rest([
            'first_name' => $user->first_name,
            'last_name' => $user->last_name,
            'phone_number' => $user->phone_number,
            'address' => $user->options->get('address'),
        ]);
    }

    /**
     * Store
     */
    public function store(Request $request)
    {
        $request->validate([
            'name' => ['required', 'string', 'max:255'],
            'phone_number' => ['required', 'int', 'between:61000000,71999999', Rule::unique('users', 'phone_number')->ignore(auth()->id())],
            'address' => ['required', 'string', 'max:255'],
        ]);

        auth()->user()->update([
            'first_name' => $request->name,
            'phone_number' => $request->phone_number,
        ]);

        auth()->user()->options->set('address', $request->address);

        return response()->rest();
    }
}
