<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use App\Http\Resources\UserResource;
use App\Models\User;
use App\Traits\GlobalApiResponse;
use Illuminate\Support\Facades\Hash;
use Illuminate\Http\Request;

class UsersController extends Controller
{
    use GlobalApiResponse;
    public function login(LoginRequest $request){
        $user = User::where('email', $request->email)->first();

        if(!$user || !Hash::check($request->password, $user->password)){
            return response(['message' => 'Invalid credentials'], 401);
        }

        $token = $user->createToken($_ENV['APP_KEY'])->plainTextToken;

        return response(['user' => $user, 'token' => $token], 200);
    }
    public function index(Request $request){
        $query = User::query();
        if($request->has('search') && !empty($request->get("search"))){
            $query->where('name', 'LIKE', '%'.$request->get('search').'%');
        }
        return UserResource::collection($query->paginate());
    }
    public function logout(Request $request){
        $request->user()->tokens()->delete();
        return response()->json(['message' => 'logged out successfully']);
    }
}
