<?php

namespace App\Http\Controllers\Profile;

use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Profile\ProfileBasicInfo;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;

class ProfileBasicInfoController extends Controller
{
    public function create(Request $req)
    {

        $valid = Validator::make($req->all(), [
            'name' => 'required|string',
        ]);

        if ($valid->fails()) {
            return response()->json([
                'message' => $valid->errors()
            ], 400);
        }

        DB::beginTransaction();

        try {
            ProfileBasicInfo::updateOrCreate(
                ['user_id' => Auth::id()],

                [
                    'user_id' => Auth::id(),
                    'birthday' => $req->birthday,
                    'gender' => $req->gender,
                ]
            );
            User::where('id', Auth::id())->update([
                'name' => $req->name
            ]);
            DB::commit();
            return response()->json([
                'text' => 'Profile Basic Information has been created or updated.'
            ]);
        } catch (Exception $e) {
            DB::rollBack();
            return response()->json([
                'errors' => ['There is a problem in creating or updating Profile Basic Information.'],
                'message' => $e->getMessage()
            ], 500);
        }
    }
}
