<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class AuthController extends Controller
{
    public function login (Request $request)
    {
        $request->validate([
            'mobileNumber' => 'required',
            'userType' => 'required',
        ]);
        $existingUser = User::where('mobileNumber', $request->mobileNumber)->first();
        if($existingUser) {
            $existingUser->deviceToken = $request->deviceToken;
            $existingUser->save();
            return response()->json([
                "message" => "User logged in successfully",
                "user"=>$existingUser,
                "alreadyRegistered"=>true
            ]);
        }else {
            $user = new User ;
            $user->mobileNumber = $request->mobileNumber;
            $user->deviceToken = $request->deviceToken;
            $user->userType = $request->userType;
            $user->save();

            return response()->json([
                "message" => "User logged in successfully",
                "user"=>$user,
                "alreadyRegistered"=>false
            ]);
        }
    }

    public function update (Request $request, $id) 
    {
        $request->validate([
            'name' => 'required',
        ]);
        $user = User::find($id);
        if ($request->hasFile('image')) {
            // Retrieve the uploaded file
            $image = $request->file('image');
            $fileName = time() . '.' . $image->getClientOriginalExtension();
            $destinationPath = public_path('images'); 

            // Move the file to the destination path
            $image->move($destinationPath, $fileName);
        }

        $user->name = $request->name;
        $user->email = $request->email;
        $user->company = $request->company;
        $user->address = $request->address;
        $user->image = $fileName ? $fileName : null;
        $user->update();

        return response()->json([
            "message" => "User updated successfully",
            "user"=>$user,
        ]);
        
    }
}
