<?php

namespace App\Http\Controllers\Api;

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

class AuthController extends Controller
{
    public function register(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',
            'email' => 'required|string|max:255|unique:users',
            'password' => 'required|string|min:8'
        ]);

        if ($validator->fails()) {
            return response()->json($validator->errors());
        }

        $user = User::create([
            'name' => $request->name,
            'email' => $request->email,
            'password' => Hash::make($request->password)
        ]);

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'data' => $user,
            'access_token' => $token,
            'token_type' => 'Bearer'
        ]);
    }

    public function login(Request $request)
    {
        if (!Auth::attempt($request->only('nik', 'password'))) {
            return response()->json([
                'message' => 'Unauthorized'
            ], 401);
        }

        $user = Auth::user(); 
        
        return response()->json([
            'message' => 'Login success',
            'nik' => $user->nik, 
            'email' => $user->email,
            'username' => $user->username,
            'fullname' => $user->fullname
        ]);
    }

    public function users(Request $request){
        $id = $request->id;
        $data = DB::table('users_sales')
            ->get()->toArray();

        return response()->json($data, 200, [], JSON_PRETTY_PRINT);
    }

    public function usersId(Request $request){
        $id = $request->id;
        $user = DB::table('users_sales')
            ->where('id', $id)
            ->first();

        return response()->json($user, 200, [], JSON_PRETTY_PRINT);
    }

    public function logout()
    {
        Auth::user()->tokens()->delete();
        return response()->json([
            'message' => 'logout success'
        ]);
    }
}